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