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