Indented.
[pazpar2-moved-to-github.git] / src / http_command.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2010 Index Data
3
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 #if HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23 #include <stdio.h>
24 #include <sys/types.h>
25 #if HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #include <stdlib.h>
29 #include <string.h>
30 #if HAVE_SYS_TIME_H
31 #include <sys/time.h>
32 #endif
33 #include <yaz/snprintf.h>
34 #include <yaz/yaz-util.h>
35
36 #include "ppmutex.h"
37 #include "eventl.h"
38 #include "parameters.h"
39 #include "session.h"
40 #include "http.h"
41 #include "settings.h"
42 #include "client.h"
43
44 // Update this when the protocol changes
45 #define PAZPAR2_PROTOCOL_VERSION "1"
46
47 #define HTTP_COMMAND_RESPONSE_PREFIX "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
48
49 struct http_session {
50     IOCHAN timeout_iochan;     // NOTE: This is NOT associated with a socket
51     struct session *psession;
52     unsigned int session_id;
53     int timestamp;
54     int destroy_counter;
55     int activity_counter;
56     NMEM nmem;
57     http_sessions_t http_sessions;
58     struct http_session *next;
59 };
60
61 struct http_sessions {
62     struct http_session *session_list;
63     YAZ_MUTEX mutex;
64 };
65
66 http_sessions_t http_sessions_create(void)
67 {
68     http_sessions_t hs = xmalloc(sizeof(*hs));
69     hs->session_list = 0;
70     hs->mutex = 0;
71     pazpar2_mutex_create(&hs->mutex, "http_sessions");
72     return hs;
73 }
74
75 void http_sessions_destroy(http_sessions_t hs)
76 {
77     if (hs)
78     {
79         struct http_session *s = hs->session_list;
80         while (s)
81         {
82             struct http_session *s_next = s->next;
83             iochan_destroy(s->timeout_iochan);
84             destroy_session(s->psession);
85             nmem_destroy(s->nmem);
86             s = s_next;
87         }
88         yaz_mutex_destroy(&hs->mutex);
89         xfree(hs);
90     }
91 }
92
93 void http_session_destroy(struct http_session *s);
94
95 static void session_timeout(IOCHAN i, int event)
96 {
97     struct http_session *s = iochan_getdata(i);
98     http_session_destroy(s);
99 }
100
101 struct http_session *http_session_create(struct conf_service *service,
102                                          http_sessions_t http_sessions,
103                                          unsigned int sesid)
104 {
105     NMEM nmem = nmem_create();
106     struct http_session *r = nmem_malloc(nmem, sizeof(*r));
107     char tmp_str[50];
108
109     sprintf(tmp_str, "session#%u", sesid);
110     r->psession = new_session(nmem, service, tmp_str);
111     r->session_id = sesid;
112     r->timestamp = 0;
113     r->nmem = nmem;
114     r->destroy_counter = r->activity_counter = 0;
115     r->http_sessions = http_sessions;
116
117     yaz_mutex_enter(http_sessions->mutex);
118     r->next = http_sessions->session_list;
119     http_sessions->session_list = r;
120     yaz_mutex_leave(http_sessions->mutex);
121
122     r->timeout_iochan = iochan_create(-1, session_timeout, 0, "http_session_timeout");
123     iochan_setdata(r->timeout_iochan, r);
124     yaz_log(YLOG_LOG, "%p HTTP session %u created. timeout chan=%p timeout=%d", r, sesid, r->timeout_iochan, service->session_timeout);
125     iochan_settimeout(r->timeout_iochan, service->session_timeout);
126
127     iochan_add(service->server->iochan_man, r->timeout_iochan);
128     return r;
129 }
130
131 void http_session_destroy(struct http_session *s)
132 {
133     int must_destroy = 1;
134
135     http_sessions_t http_sessions = s->http_sessions;
136
137     yaz_log(YLOG_LOG, "%p HTTP session destroy %u", s, s->session_id);
138     yaz_mutex_enter(http_sessions->mutex);
139
140     /* only if http_session destroy was already called, we will allow it
141        to be destroyed */
142     if (s->destroy_counter != s->activity_counter)
143         must_destroy = 0;
144
145     s->destroy_counter = s->activity_counter = 0;
146     if (must_destroy)
147     {
148         struct http_session **p = 0;
149         for (p = &http_sessions->session_list; *p; p = &(*p)->next)
150             if (*p == s)
151             {
152                 *p = (*p)->next;
153                 break;
154             }
155     }
156     yaz_mutex_leave(http_sessions->mutex);
157     if (must_destroy)
158     {   /* destroying for real */
159                 yaz_log(YLOG_LOG, "%p HTTP session destroying. session id %u", s, s->session_id);               iochan_destroy(s->timeout_iochan);
160         destroy_session(s->psession);
161         nmem_destroy(s->nmem);
162     }
163     else {
164         yaz_log(YLOG_DEBUG, "%p HTTP Session. Active clients on session %u. Waiting for new timeout.", s, s->session_id);
165     }
166
167 }
168
169 static const char *get_msg(enum pazpar2_error_code code)
170 {
171     struct pazpar2_error_msg {
172         enum pazpar2_error_code code;
173         const char *msg;
174     };
175     static const struct pazpar2_error_msg ar[] = {
176         { PAZPAR2_NO_SESSION, "Session does not exist or it has expired"},
177         { PAZPAR2_MISSING_PARAMETER, "Missing parameter"},
178         { PAZPAR2_MALFORMED_PARAMETER_VALUE, "Malformed parameter value"},
179         { PAZPAR2_MALFORMED_PARAMETER_ENCODING, "Malformed parameter encoding"},
180         { PAZPAR2_MALFORMED_SETTING, "Malformed setting argument"},
181         { PAZPAR2_HITCOUNTS_FAILED, "Failed to retrieve hitcounts"},
182         { PAZPAR2_RECORD_MISSING, "Record missing"},
183         { PAZPAR2_NO_TARGETS, "No targets"},
184         { PAZPAR2_CONFIG_TARGET, "Target cannot be configured"},
185         { PAZPAR2_RECORD_FAIL, "Record command failed"},
186         { PAZPAR2_NOT_IMPLEMENTED, "Not implemented"},
187         { PAZPAR2_NO_SERVICE, "No service"},
188         { PAZPAR2_LAST_ERROR, "Last error"},
189         { 0, 0 }
190     };
191     int i = 0;
192     while (ar[i].msg)
193     {
194         if (code == ar[i].code)
195             return ar[i].msg;
196         i++;
197     }
198     return "No error";
199 }
200
201 static void error(struct http_response *rs, 
202                   enum pazpar2_error_code code,
203                   const char *addinfo)
204 {
205     struct http_channel *c = rs->channel;
206     WRBUF text = wrbuf_alloc();
207     const char *http_status = "417";
208     const char *msg = get_msg(code);
209     
210     rs->msg = nmem_strdup(c->nmem, msg);
211     strcpy(rs->code, http_status);
212
213     wrbuf_printf(text, HTTP_COMMAND_RESPONSE_PREFIX "<error code=\"%d\" msg=\"%s\">", (int) code,
214                msg);
215     if (addinfo)
216         wrbuf_xmlputs(text, addinfo);
217     wrbuf_puts(text, "</error>");
218
219     yaz_log(YLOG_WARN, "HTTP %s %s%s%s", http_status,
220             msg, addinfo ? ": " : "" , addinfo ? addinfo : "");
221     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(text));
222     wrbuf_destroy(text);
223     http_send_response(c);
224 }
225
226 unsigned int make_sessionid(void)
227 {
228     static int seq = 0; /* thread pr */
229     unsigned int res;
230
231     seq++;
232     if (global_parameters.debug_mode)
233         res = seq;
234     else
235     {
236 #ifdef WIN32
237         res = seq;
238 #else
239         struct timeval t;
240
241         if (gettimeofday(&t, 0) < 0)
242         {
243             yaz_log(YLOG_WARN|YLOG_ERRNO, "gettimeofday");
244             exit(1);
245         }
246         /* at most 256 sessions per second .. 
247            (long long would be more appropriate)*/
248         res = t.tv_sec;
249         res = ((res << 8) | (seq & 0xff)) & ((1U << 31) - 1);
250 #endif
251     }
252     return res;
253 }
254
255 static struct http_session *locate_session(struct http_channel *c)
256 {
257     struct http_response *rs = c->response;
258     struct http_request *rq = c->request;
259     struct http_session *p;
260     const char *session = http_argbyname(rq, "session");
261     http_sessions_t http_sessions = c->http_sessions;
262     unsigned int id;
263
264     if (!session)
265     {
266         error(rs, PAZPAR2_MISSING_PARAMETER, "session");
267         return 0;
268     }
269     id = atoi(session);
270     yaz_mutex_enter(http_sessions->mutex);
271     for (p = http_sessions->session_list; p; p = p->next)
272         if (id == p->session_id)
273             break;
274     if (p)
275         p->activity_counter++;
276     yaz_mutex_leave(http_sessions->mutex);
277     if (p)
278         iochan_activity(p->timeout_iochan);
279     else
280         error(rs, PAZPAR2_NO_SESSION, session);
281     return p;
282 }
283
284 // Decode settings parameters and apply to session
285 // Syntax: setting[target]=value
286 static int process_settings(struct session *se, struct http_request *rq,
287                             struct http_response *rs)
288 {
289     struct http_argument *a;
290
291     for (a = rq->arguments; a; a = a->next)
292         if (strchr(a->name, '['))
293         {
294             char **res;
295             int num;
296             char *dbname;
297             char *setting;
298
299             // Nmem_strsplit *rules*!!!
300             nmem_strsplit(se->session_nmem, "[]", a->name, &res, &num);
301             if (num != 2)
302             {
303                 error(rs, PAZPAR2_MALFORMED_SETTING, a->name);
304                 return -1;
305             }
306             setting = res[0];
307             dbname = res[1];
308             session_apply_setting(se, dbname, setting,
309                     nmem_strdup(se->session_nmem, a->value));
310         }
311     return 0;
312 }
313
314 static void cmd_exit(struct http_channel *c)
315 {
316     yaz_log(YLOG_WARN, "exit");
317     http_close_server(c->server);
318 }
319
320 static void cmd_init(struct http_channel *c)
321 {
322     char buf[1024];
323     struct http_request *r = c->request;
324     const char *clear = http_argbyname(r, "clear");
325     const char *content_type = http_lookup_header(r->headers, "Content-Type");
326     unsigned int sesid;
327     struct http_session *s;
328     struct http_response *rs = c->response;
329     struct conf_service *service = 0; /* no service (yet) */
330     
331     if (r->content_len && content_type && 
332         !yaz_strcmp_del("text/xml", content_type, "; "))
333     {
334         xmlDoc *doc = xmlParseMemory(r->content_buf, r->content_len);
335         xmlNode *root_n;
336         if (!doc)
337         {
338             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
339             return;
340         }
341         root_n = xmlDocGetRootElement(doc);
342         service = service_create(c->server, root_n);
343         xmlFreeDoc(doc);
344         if (!service)
345         {
346             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
347             return;
348         }
349     }
350     
351     if (!service)
352     {
353         const char *service_name = http_argbyname(c->request, "service");
354         service = locate_service(c->server, service_name);
355         if (!service)
356         {
357             error(rs, PAZPAR2_NO_SERVICE, service_name ? service_name : "unnamed");
358             return;
359         }
360     }
361     sesid = make_sessionid();
362     s = http_session_create(service, c->http_sessions, sesid);
363     
364     yaz_log(YLOG_DEBUG, "HTTP Session init");
365     if (!clear || *clear == '0')
366         session_init_databases(s->psession);
367     else
368         yaz_log(YLOG_LOG, "No databases preloaded");
369     
370     if (process_settings(s->psession, c->request, c->response) < 0)
371         return;
372     
373     sprintf(buf, HTTP_COMMAND_RESPONSE_PREFIX 
374             "<init><status>OK</status><session>%d", sesid);
375     if (c->server->server_id)
376     {
377         strcat(buf, ".");
378         strcat(buf, c->server->server_id);
379     }
380     strcat(buf, "</session>"
381            "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol></init>");
382     rs->payload = nmem_strdup(c->nmem, buf);
383     http_send_response(c);
384 }
385
386 static void apply_local_setting(void *client_data,
387                                 struct setting *set)
388 {
389     struct session *se =  (struct session *) client_data;
390
391     session_apply_setting(se, nmem_strdup(se->session_nmem, set->target),
392                           nmem_strdup(se->session_nmem, set->name),
393                           nmem_strdup(se->session_nmem, set->value));
394 }
395
396 static void cmd_settings(struct http_channel *c)
397 {
398     struct http_response *rs = c->response;
399     struct http_request *rq = c->request;
400     struct http_session *s = locate_session(c);
401     const char *content_type = http_lookup_header(rq->headers, "Content-Type");
402
403     if (!s)
404         return;
405
406     if (rq->content_len && content_type && 
407         !yaz_strcmp_del("text/xml", content_type, "; "))
408     {
409         xmlDoc *doc = xmlParseMemory(rq->content_buf, rq->content_len);
410         xmlNode *root_n;
411         if (!doc)
412         {
413             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
414             return;
415         }
416         root_n = xmlDocGetRootElement(doc);
417
418         settings_read_node_x(root_n, s->psession, apply_local_setting);
419
420         xmlFreeDoc(doc);
421     }
422     if (process_settings(s->psession, rq, rs) < 0)
423         return;
424     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<settings><status>OK</status></settings>";
425     http_send_response(c);
426 }
427
428 // Compares two hitsbytarget nodes by hitcount
429 static int cmp_ht(const void *p1, const void *p2)
430 {
431     const struct hitsbytarget *h1 = p1;
432     const struct hitsbytarget *h2 = p2;
433     return h2->hits - h1->hits;
434 }
435
436 // This implements functionality somewhat similar to 'bytarget', but in a termlist form
437 static void targets_termlist(WRBUF wrbuf, struct session *se, int num,
438                              NMEM nmem)
439 {
440     struct hitsbytarget *ht;
441     int count, i;
442
443     ht = hitsbytarget(se, &count, nmem);
444     qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
445     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
446     {
447
448         // do only print terms which have display names
449     
450         wrbuf_puts(wrbuf, "<term>\n");
451
452         wrbuf_puts(wrbuf, "<id>");
453         wrbuf_xmlputs(wrbuf, ht[i].id);
454         wrbuf_puts(wrbuf, "</id>\n");
455         
456         wrbuf_puts(wrbuf, "<name>");
457         if (!ht[i].name || !ht[i].name[0])
458             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
459         else
460             wrbuf_xmlputs(wrbuf, ht[i].name);
461         wrbuf_puts(wrbuf, "</name>\n");
462         
463         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
464                      ht[i].hits);
465         
466         wrbuf_puts(wrbuf, "<state>");
467         wrbuf_xmlputs(wrbuf, ht[i].state);
468         wrbuf_puts(wrbuf, "</state>\n");
469         
470         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
471                      ht[i].diagnostic);
472         wrbuf_puts(wrbuf, "</term>\n");
473     }
474 }
475
476 static void cmd_termlist(struct http_channel *c)
477 {
478     struct http_response *rs = c->response;
479     struct http_request *rq = c->request;
480     struct http_session *s = locate_session(c);
481     struct termlist_score **p;
482     int len;
483     int i;
484     const char *name = http_argbyname(rq, "name");
485     const char *nums = http_argbyname(rq, "num");
486     int num = 15;
487     int status;
488
489     if (!s)
490         return;
491
492     status = session_active_clients(s->psession);
493
494     if (!name)
495         name = "subject";
496     if (strlen(name) > 255)
497         return;
498     if (nums)
499         num = atoi(nums);
500
501     wrbuf_rewind(c->wrbuf);
502
503     wrbuf_puts(c->wrbuf, "<termlist>\n");
504     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", status);
505     while (*name)
506     {
507         char tname[256];
508         const char *tp;
509
510         if (!(tp = strchr(name, ',')))
511             tp = name + strlen(name);
512         strncpy(tname, name, tp - name);
513         tname[tp - name] = '\0';
514
515         wrbuf_puts(c->wrbuf, "<list name=\"");
516         wrbuf_xmlputs(c->wrbuf, tname);
517         wrbuf_puts(c->wrbuf, "\">\n");
518         if (!strcmp(tname, "xtargets"))
519             targets_termlist(c->wrbuf, s->psession, num, c->nmem);
520         else
521         {
522             p = termlist(s->psession, tname, &len);
523             if (p)
524                 for (i = 0; i < len && i < num; i++){
525                     // prevnt sending empty term elements
526                     if (!p[i]->term || !p[i]->term[0])
527                         continue;
528
529                     wrbuf_puts(c->wrbuf, "<term>");
530                     wrbuf_puts(c->wrbuf, "<name>");
531                     wrbuf_xmlputs(c->wrbuf, p[i]->term);
532                     wrbuf_puts(c->wrbuf, "</name>");
533                         
534                     wrbuf_printf(c->wrbuf, 
535                                  "<frequency>%d</frequency>", 
536                                  p[i]->frequency);
537                     wrbuf_puts(c->wrbuf, "</term>\n");
538                }
539         }
540         wrbuf_puts(c->wrbuf, "</list>\n");
541         name = tp;
542         if (*name == ',')
543             name++;
544     }
545     wrbuf_puts(c->wrbuf, "</termlist>\n");
546     rs->payload = nmem_strdup(rq->channel->nmem, wrbuf_cstr(c->wrbuf));
547     http_send_response(c);
548 }
549
550
551 static void cmd_bytarget(struct http_channel *c)
552 {
553     struct http_response *rs = c->response;
554     struct http_request *rq = c->request;
555     struct http_session *s = locate_session(c);
556     struct hitsbytarget *ht;
557     const char *settings = http_argbyname(rq, "settings");
558     int count, i;
559
560     if (!s)
561         return;
562     ht = hitsbytarget(s->psession, &count, c->nmem);
563     wrbuf_rewind(c->wrbuf);
564     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<bytarget><status>OK</status>");
565
566     for (i = 0; i < count; i++)
567     {
568         wrbuf_puts(c->wrbuf, "\n<target>");
569
570         wrbuf_puts(c->wrbuf, "<id>");
571         wrbuf_xmlputs(c->wrbuf, ht[i].id);
572         wrbuf_puts(c->wrbuf, "</id>\n");
573
574         if (ht[i].name && ht[i].name[0]) 
575         {
576             wrbuf_puts(c->wrbuf, "<name>");
577             wrbuf_xmlputs(c->wrbuf, ht[i].name);
578             wrbuf_puts(c->wrbuf, "</name>\n");
579         }
580
581         wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", ht[i].hits);
582         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
583         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
584
585         wrbuf_puts(c->wrbuf, "<state>");
586         wrbuf_xmlputs(c->wrbuf, ht[i].state);
587         wrbuf_puts(c->wrbuf, "</state>\n");
588         if (settings && *settings == '1')
589         {
590             wrbuf_puts(c->wrbuf, "<settings>\n");
591             wrbuf_puts(c->wrbuf, wrbuf_cstr(ht[i].settings_xml));
592             wrbuf_puts(c->wrbuf, "</settings>\n");
593         }
594         wrbuf_puts(c->wrbuf, "</target>");
595         wrbuf_destroy(ht[i].settings_xml);
596     }
597
598     wrbuf_puts(c->wrbuf, "</bytarget>");
599     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
600     http_send_response(c);
601 }
602
603 static void write_metadata(WRBUF w, struct conf_service *service,
604         struct record_metadata **ml, int full)
605 {
606     int imeta;
607
608     for (imeta = 0; imeta < service->num_metadata; imeta++)
609     {
610         struct conf_metadata *cmd = &service->metadata[imeta];
611         struct record_metadata *md;
612         if (!cmd->brief && !full)
613             continue;
614         for (md = ml[imeta]; md; md = md->next)
615         {
616             struct record_metadata_attr *attr = md->attributes;
617             wrbuf_printf(w, "\n<md-%s", cmd->name);
618
619             for (; attr; attr = attr->next)
620             {
621                 wrbuf_printf(w, " %s=\"", attr->name);
622                 wrbuf_xmlputs(w, attr->value);
623                 wrbuf_puts(w, "\"");
624             }
625             wrbuf_puts(w, ">");
626             switch (cmd->type)
627             {
628                 case Metadata_type_generic:
629                     wrbuf_xmlputs(w, md->data.text.disp);
630                     break;
631                 case Metadata_type_year:
632                     wrbuf_printf(w, "%d", md->data.number.min);
633                     if (md->data.number.min != md->data.number.max)
634                         wrbuf_printf(w, "-%d", md->data.number.max);
635                     break;
636                 default:
637                     wrbuf_puts(w, "[can't represent]");
638             }
639             wrbuf_printf(w, "</md-%s>", cmd->name);
640         }
641     }
642 }
643
644 static void write_subrecord(struct record *r, WRBUF w,
645         struct conf_service *service, int show_details)
646 {
647     const char *name = session_setting_oneval(
648         client_get_database(r->client), PZ_NAME);
649
650     wrbuf_puts(w, "<location id=\"");
651     wrbuf_xmlputs(w, client_get_database(r->client)->database->url);
652     wrbuf_puts(w, "\" ");
653
654     wrbuf_puts(w, "name=\"");
655     wrbuf_xmlputs(w,  *name ? name : "Unknown");
656     wrbuf_puts(w, "\">");
657
658     write_metadata(w, service, r->metadata, show_details);
659     wrbuf_puts(w, "</location>\n");
660 }
661
662 static void show_raw_record_error(void *data, const char *addinfo)
663 {
664     http_channel_observer_t obs = data;
665     struct http_channel *c = http_channel_observer_chan(obs);
666     struct http_response *rs = c->response;
667
668     http_remove_observer(obs);
669
670     error(rs, PAZPAR2_RECORD_FAIL, addinfo);
671 }
672
673 static void show_raw_record_ok(void *data, const char *buf, size_t sz)
674 {
675     http_channel_observer_t obs = data;
676     struct http_channel *c = http_channel_observer_chan(obs);
677     struct http_response *rs = c->response;
678
679     http_remove_observer(obs);
680
681     wrbuf_write(c->wrbuf, buf, sz);
682     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
683     http_send_response(c);
684 }
685
686
687 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
688 {
689     http_channel_observer_t obs = data;
690     struct http_channel *c = http_channel_observer_chan(obs);
691     struct http_response *rs = c->response;
692
693     http_remove_observer(obs);
694
695     wrbuf_write(c->wrbuf, buf, sz);
696     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
697
698     rs->content_type = "application/octet-stream";
699     http_send_response(c);
700 }
701
702
703 void show_raw_reset(void *data, struct http_channel *c, void *data2)
704 {
705     //struct client *client = data;
706     //client_show_raw_remove(client, data2);
707 }
708
709 static void cmd_record_ready(void *data);
710
711 static void cmd_record(struct http_channel *c)
712 {
713     struct http_response *rs = c->response;
714     struct http_request *rq = c->request;
715     struct http_session *s = locate_session(c);
716     struct record_cluster *rec, *prev_r, *next_r;
717     struct record *r;
718     struct conf_service *service;
719     const char *idstr = http_argbyname(rq, "id");
720     const char *offsetstr = http_argbyname(rq, "offset");
721     const char *binarystr = http_argbyname(rq, "binary");
722     
723     if (!s)
724         return;
725     service = s->psession->service;
726     if (!idstr)
727     {
728         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
729         return;
730     }
731     wrbuf_rewind(c->wrbuf);
732     if (!(rec = show_single_start(s->psession, idstr, &prev_r, &next_r)))
733     {
734         if (session_active_clients(s->psession) == 0)
735         {
736             error(rs, PAZPAR2_RECORD_MISSING, idstr);
737         }
738         else if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
739                               cmd_record_ready, c, c) != 0)
740         {
741             error(rs, PAZPAR2_RECORD_MISSING, idstr);
742         }
743         return;
744     }
745     if (offsetstr)
746     {
747         int offset = atoi(offsetstr);
748         const char *syntax = http_argbyname(rq, "syntax");
749         const char *esn = http_argbyname(rq, "esn");
750         int i;
751         struct record*r = rec->records;
752         int binary = 0;
753
754         if (binarystr && *binarystr != '0')
755             binary = 1;
756
757         for (i = 0; i < offset && r; r = r->next, i++)
758             ;
759         if (!r)
760         {
761             error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
762         }
763         else
764         {
765             http_channel_observer_t obs =
766                 http_add_observer(c, r->client, show_raw_reset);
767             int ret = client_show_raw_begin(r->client, r->position,
768                                         syntax, esn, 
769                                         obs /* data */,
770                                         show_raw_record_error,
771                                         (binary ? 
772                                          show_raw_record_ok_binary : 
773                                          show_raw_record_ok),
774                                         (binary ? 1 : 0));
775             if (ret == -1)
776             {
777                 http_remove_observer(obs);
778                 error(rs, PAZPAR2_NO_SESSION, 0);
779             }
780         }
781     }
782     else
783     {
784         wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<record>\n");
785         wrbuf_puts(c->wrbuf, "<recid>");
786         wrbuf_xmlputs(c->wrbuf, rec->recid);
787         wrbuf_puts(c->wrbuf, "</recid>\n");
788         if (prev_r)
789         {
790             wrbuf_puts(c->wrbuf, "<prevrecid>");
791             wrbuf_xmlputs(c->wrbuf, prev_r->recid);
792             wrbuf_puts(c->wrbuf, "</prevrecid>\n");
793         }
794         if (next_r)
795         {
796             wrbuf_puts(c->wrbuf, "<nextrecid>");
797             wrbuf_xmlputs(c->wrbuf, next_r->recid);
798             wrbuf_puts(c->wrbuf, "</nextrecid>\n");
799         }
800         wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", 
801                      session_active_clients(s->psession));
802         write_metadata(c->wrbuf, service, rec->metadata, 1);
803         for (r = rec->records; r; r = r->next)
804             write_subrecord(r, c->wrbuf, service, 1);
805         wrbuf_puts(c->wrbuf, "</record>\n");
806         rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
807         http_send_response(c);
808     }
809     show_single_stop(s->psession, rec);
810 }
811
812 static void cmd_record_ready(void *data)
813 {
814     struct http_channel *c = (struct http_channel *) data;
815
816     cmd_record(c);
817 }
818
819 static void show_records(struct http_channel *c, int active)
820 {
821     struct http_request *rq = c->request;
822     struct http_response *rs = c->response;
823     struct http_session *s = locate_session(c);
824     struct record_cluster **rl;
825     struct reclist_sortparms *sp;
826     const char *start = http_argbyname(rq, "start");
827     const char *num = http_argbyname(rq, "num");
828     const char *sort = http_argbyname(rq, "sort");
829     int startn = 0;
830     int numn = 20;
831     int total;
832     Odr_int total_hits;
833     int i;
834
835     if (!s)
836         return;
837
838     // We haven't counted clients yet if we're called on a block release
839     if (active < 0)
840         active = session_active_clients(s->psession);
841
842     if (start)
843         startn = atoi(start);
844     if (num)
845         numn = atoi(num);
846     if (!sort)
847         sort = "relevance";
848     if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
849     {
850         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
851         return;
852     }
853
854     
855     rl = show_range_start(s->psession, sp, startn, &numn, &total, &total_hits);
856
857     wrbuf_rewind(c->wrbuf);
858     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<show>\n<status>OK</status>\n");
859     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
860     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
861     wrbuf_printf(c->wrbuf, "<total>" ODR_INT_PRINTF "</total>\n", total_hits);
862     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
863     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
864
865     for (i = 0; i < numn; i++)
866     {
867         int ccount;
868         struct record *p;
869         struct record_cluster *rec = rl[i];
870         struct conf_service *service = s->psession->service;
871
872         wrbuf_puts(c->wrbuf, "<hit>\n");
873         write_metadata(c->wrbuf, service, rec->metadata, 0);
874         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
875             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
876         if (ccount > 1)
877             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
878         if (strstr(sort, "relevance"))
879             wrbuf_printf(c->wrbuf, "<relevance>%d</relevance>\n",
880                          rec->relevance_score);
881         wrbuf_puts(c->wrbuf, "<recid>");
882         wrbuf_xmlputs(c->wrbuf, rec->recid);
883         wrbuf_puts(c->wrbuf, "</recid>\n");
884         wrbuf_puts(c->wrbuf, "</hit>\n");
885     }
886
887     show_range_stop(s->psession, rl);
888
889     wrbuf_puts(c->wrbuf, "</show>\n");
890     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
891     http_send_response(c);
892 }
893
894 static void show_records_ready(void *data)
895 {
896     struct http_channel *c = (struct http_channel *) data;
897
898     show_records(c, -1);
899 }
900
901 static void cmd_show(struct http_channel *c)
902 {
903     struct http_request *rq = c->request;
904     struct http_session *s = locate_session(c);
905     const char *block = http_argbyname(rq, "block");
906     int status;
907
908     if (!s)
909         return;
910
911     status = session_active_clients(s->psession);
912
913     if (block)
914     {
915         if (status && reclist_get_num_records(s->psession->reclist) == 0)
916         {
917             // if there is already a watch/block. we do not block this one
918             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
919                                   show_records_ready, c, c) != 0)
920             {
921                 yaz_log(YLOG_DEBUG, "Blocking on cmd_show");
922             }
923             return;
924         }
925     }
926
927     show_records(c, status);
928 }
929
930 static void cmd_ping(struct http_channel *c)
931 {
932     struct http_response *rs = c->response;
933     struct http_session *s = locate_session(c);
934     if (!s)
935         return;
936     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<ping><status>OK</status></ping>";
937     http_send_response(c);
938 }
939
940 static int utf_8_valid(const char *str)
941 {
942     yaz_iconv_t cd = yaz_iconv_open("utf-8", "utf-8");
943     if (cd)
944     {
945         /* check that query is UTF-8 encoded */
946         char *inbuf = (char *) str; /* we know iconv does not alter this */
947         size_t inbytesleft = strlen(inbuf);
948
949         size_t outbytesleft = strlen(inbuf) + 10;
950         char *out = xmalloc(outbytesleft);
951         char *outbuf = out;
952         size_t r = yaz_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
953
954         /* if OK, try flushing the rest  */
955         if (r != (size_t) (-1))
956             r = yaz_iconv(cd, 0, 0, &outbuf, &outbytesleft);
957         yaz_iconv_close(cd);
958         xfree(out);
959         if (r == (size_t) (-1))
960             return 0;
961     }
962     return 1;
963 }
964
965 static void cmd_search(struct http_channel *c)
966 {
967     struct http_request *rq = c->request;
968     struct http_response *rs = c->response;
969     struct http_session *s = locate_session(c);
970     const char *query = http_argbyname(rq, "query");
971     const char *filter = http_argbyname(rq, "filter");
972     const char *maxrecs = http_argbyname(rq, "maxrecs");
973     const char *startrecs = http_argbyname(rq, "startrecs");
974     enum pazpar2_error_code code;
975     const char *addinfo = 0;
976
977     if (!s)
978         return;
979     if (!query)
980     {
981         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
982         return;
983     }
984     if (!utf_8_valid(query))
985     {
986         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
987         return;
988     }
989     code = search(s->psession, query, startrecs, maxrecs, filter, &addinfo);
990     if (code)
991     {
992         error(rs, code, addinfo);
993         return;
994     }
995     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<search><status>OK</status></search>";
996     http_send_response(c);
997 }
998
999
1000 static void cmd_stat(struct http_channel *c)
1001 {
1002     struct http_response *rs = c->response;
1003     struct http_session *s = locate_session(c);
1004     struct statistics stat;
1005     int clients;
1006
1007     float progress = 0;
1008
1009     if (!s)
1010         return;
1011
1012     clients = session_active_clients(s->psession);
1013     statistics(s->psession, &stat);
1014
1015     if (stat.num_clients > 0) {
1016         progress = (stat.num_clients  - clients) / (float)stat.num_clients;
1017     }
1018
1019     wrbuf_rewind(c->wrbuf);
1020     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<stat>");
1021     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
1022     wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", stat.num_hits);
1023     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
1024     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
1025     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
1026     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
1027     wrbuf_printf(c->wrbuf, "<working>%d</working>\n", stat.num_working);
1028     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
1029     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
1030     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
1031     wrbuf_printf(c->wrbuf, "<progress>%.2f</progress>\n", progress);
1032     wrbuf_puts(c->wrbuf, "</stat>");
1033     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1034     http_send_response(c);
1035 }
1036
1037 static void cmd_info(struct http_channel *c)
1038 {
1039     char yaz_version_str[20];
1040     struct http_response *rs = c->response;
1041
1042     wrbuf_rewind(c->wrbuf);
1043     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<info>\n");
1044     wrbuf_puts(c->wrbuf, " <version>\n");
1045     wrbuf_puts(c->wrbuf, "<pazpar2");
1046 #ifdef PAZPAR2_VERSION_SHA1
1047     wrbuf_printf(c->wrbuf, " sha1=\"%s\"", PAZPAR2_VERSION_SHA1);
1048 #endif
1049     wrbuf_puts(c->wrbuf, ">");
1050     wrbuf_xmlputs(c->wrbuf, VERSION);
1051     wrbuf_puts(c->wrbuf, "</pazpar2>");
1052
1053
1054     yaz_version(yaz_version_str, 0);
1055     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
1056     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
1057     wrbuf_puts(c->wrbuf, "\">");
1058     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
1059     wrbuf_puts(c->wrbuf, "</yaz>\n");
1060
1061     wrbuf_puts(c->wrbuf, " </version>\n");
1062     
1063     wrbuf_puts(c->wrbuf, "</info>");
1064     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1065     http_send_response(c);
1066 }
1067
1068 struct {
1069     char *name;
1070     void (*fun)(struct http_channel *c);
1071 } commands[] = {
1072     { "init", cmd_init },
1073     { "settings", cmd_settings },
1074     { "stat", cmd_stat },
1075     { "bytarget", cmd_bytarget },
1076     { "show", cmd_show },
1077     { "search", cmd_search },
1078     { "termlist", cmd_termlist },
1079     { "exit", cmd_exit },
1080     { "ping", cmd_ping },
1081     { "record", cmd_record },
1082     { "info", cmd_info },
1083     {0,0}
1084 };
1085
1086 void http_command(struct http_channel *c)
1087 {
1088     const char *command = http_argbyname(c->request, "command");
1089     struct http_response *rs = http_create_response(c);
1090     int i;
1091
1092     c->response = rs;
1093
1094     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
1095     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
1096
1097     if (!command)
1098     {
1099         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
1100         return;
1101     }
1102     for (i = 0; commands[i].name; i++)
1103         if (!strcmp(commands[i].name, command))
1104         {
1105             (*commands[i].fun)(c);
1106             break;
1107         }
1108     if (!commands[i].name)
1109         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
1110
1111     return;
1112 }
1113
1114 /*
1115  * Local variables:
1116  * c-basic-offset: 4
1117  * c-file-style: "Stroustrup"
1118  * indent-tabs-mode: nil
1119  * End:
1120  * vim: shiftwidth=4 tabstop=8 expandtab
1121  */
1122