68b56af24da22f6324a7edba23f3a5d4425f110a
[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 /*
21  * $Id: http_command.c,v 1.66 2007-10-28 18:55:26 adam Exp $
22  */
23
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <sys/uio.h>
27 #include <unistd.h>
28 #include <stdlib.h>
29 #include <strings.h>
30 #include <ctype.h>
31 #include <sys/time.h>
32 #include <yaz/snprintf.h>
33 #if HAVE_CONFIG_H
34 #include <cconfig.h>
35 #endif
36
37 #include <yaz/yaz-util.h>
38
39 #include "config.h"
40 #include "util.h"
41 #include "eventl.h"
42 #include "pazpar2.h"
43 #include "http.h"
44 #include "http_command.h"
45 #include "settings.h"
46 #include "client.h"
47
48 // Update this when the protocol changes
49 #define PAZPAR2_PROTOCOL_VERSION "1"
50
51 struct http_session {
52     IOCHAN timeout_iochan;     // NOTE: This is NOT associated with a socket
53     struct session *psession;
54     unsigned int session_id;
55     int timestamp;
56     NMEM nmem;
57     struct http_session *next;
58 };
59
60 static struct http_session *session_list = 0;
61 void http_session_destroy(struct http_session *s);
62
63 static void session_timeout(IOCHAN i, int event)
64 {
65     struct http_session *s = iochan_getdata(i);
66     http_session_destroy(s);
67 }
68
69 struct http_session *http_session_create()
70 {
71     NMEM nmem = nmem_create();
72     struct http_session *r = nmem_malloc(nmem, sizeof(*r));
73
74     r->psession = new_session(nmem);
75     r->session_id = 0;
76     r->timestamp = 0;
77     r->nmem = nmem;
78     r->next = session_list;
79     session_list = r;
80     r->timeout_iochan = iochan_create(-1, session_timeout, 0);
81     iochan_setdata(r->timeout_iochan, r);
82     iochan_settimeout(r->timeout_iochan, global_parameters.session_timeout);
83
84     pazpar2_add_channel(r->timeout_iochan);
85     return r;
86 }
87
88 void http_session_destroy(struct http_session *s)
89 {
90     struct http_session **p;
91
92     for (p = &session_list; *p; p = &(*p)->next)
93         if (*p == s)
94         {
95             *p = (*p)->next;
96             break;
97         }
98     yaz_log(YLOG_LOG, "Destroying session %u", s->session_id);
99     iochan_destroy(s->timeout_iochan);
100     destroy_session(s->psession);
101     nmem_destroy(s->nmem);
102 }
103
104 static const char *get_msg(enum pazpar2_error_code code)
105 {
106     struct pazpar2_error_msg {
107         enum pazpar2_error_code code;
108         const char *msg;
109     };
110     static const struct pazpar2_error_msg ar[] = {
111         { PAZPAR2_NO_SESSION, "Session does not exist or it has expired"},
112         { PAZPAR2_MISSING_PARAMETER, "Missing parameter"},
113         { PAZPAR2_MALFORMED_PARAMETER_VALUE, "Malformed parameter value"},
114         { PAZPAR2_MALFORMED_PARAMETER_ENCODING, "Malformed parameter encoding"},
115         { PAZPAR2_MALFORMED_SETTING, "Malformed setting argument"},
116         { PAZPAR2_HITCOUNTS_FAILED, "Failed to retrieve hitcounts"},
117         { PAZPAR2_RECORD_MISSING, "Record missing"},
118         { PAZPAR2_NO_TARGETS, "No targets"},
119         { PAZPAR2_CONFIG_TARGET, "Target cannot be configured"},
120         { PAZPAR2_RECORD_FAIL, "Record command failed"},
121         { PAZPAR2_NOT_IMPLEMENTED, "Not implemented"},
122         { PAZPAR2_LAST_ERROR, "Last error"},
123         { 0, 0 }
124     };
125     int i = 0;
126     while (ar[i].msg)
127     {
128         if (code == ar[i].code)
129             return ar[i].msg;
130         i++;
131     }
132     return "No error";
133 }
134
135 static void error(struct http_response *rs, 
136                   enum pazpar2_error_code code,
137                   const char *addinfo)
138 {
139     struct http_channel *c = rs->channel;
140     WRBUF text = wrbuf_alloc();
141     const char *http_status = "417";
142     const char *msg = get_msg(code);
143     
144     rs->msg = nmem_strdup(c->nmem, msg);
145     strcpy(rs->code, http_status);
146
147     wrbuf_printf(text, "<error code=\"%d\" msg=\"%s\">", (int) code,
148                msg);
149     if (addinfo)
150         wrbuf_xmlputs(text, addinfo);
151     wrbuf_puts(text, "</error>");
152
153     yaz_log(YLOG_WARN, "HTTP %s %s%s%s", http_status,
154             msg, addinfo ? ": " : "" , addinfo ? addinfo : "");
155     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(text));
156     wrbuf_destroy(text);
157     http_send_response(c);
158 }
159
160 unsigned int make_sessionid()
161 {
162     static int seq = 0;
163     unsigned int res;
164
165     seq++;
166     if (global_parameters.debug_mode)
167         res = seq;
168     else
169     {
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     }
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     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     exit(0);
241 }
242
243 static void cmd_init(struct http_channel *c)
244 {
245     unsigned int sesid;
246     char buf[1024];
247     const char *clear = http_argbyname(c->request, "clear");
248     struct http_session *s = http_session_create();
249     struct http_response *rs = c->response;
250
251     yaz_log(YLOG_DEBUG, "HTTP Session init");
252     if (!clear || *clear == '0')
253         session_init_databases(s->psession);
254     else
255         yaz_log(YLOG_LOG, "No databases preloaded");
256     sesid = make_sessionid();
257     s->session_id = sesid;
258     if (process_settings(s->psession, c->request, c->response) < 0)
259         return;
260     sprintf(buf, "<init><status>OK</status><session>%u</session>"
261             "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol></init>", sesid);
262     rs->payload = nmem_strdup(c->nmem, buf);
263     http_send_response(c);
264 }
265
266 static void cmd_settings(struct http_channel *c)
267 {
268     struct http_response *rs = c->response;
269     struct http_request *rq = c->request;
270     struct http_session *s = locate_session(rq, rs);
271
272     if (!s)
273         return;
274
275     if (process_settings(s->psession, rq, rs) < 0)
276         return;
277     rs->payload = "<settings><status>OK</status></settings>";
278     http_send_response(c);
279 }
280
281 // Compares two hitsbytarget nodes by hitcount
282 static int cmp_ht(const void *p1, const void *p2)
283 {
284     const struct hitsbytarget *h1 = p1;
285     const struct hitsbytarget *h2 = p2;
286     return h2->hits - h1->hits;
287 }
288
289 // This implements functionality somewhat similar to 'bytarget', but in a termlist form
290 static void targets_termlist(WRBUF wrbuf, struct session *se, int num,
291                              NMEM nmem)
292 {
293     struct hitsbytarget *ht;
294     int count, i;
295
296     ht = hitsbytarget(se, &count, nmem);
297     qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
298     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
299     {
300
301         // do only print terms which have display names
302     
303         wrbuf_puts(wrbuf, "<term>\n");
304
305         wrbuf_puts(wrbuf, "<id>");
306         wrbuf_xmlputs(wrbuf, ht[i].id);
307         wrbuf_puts(wrbuf, "</id>\n");
308         
309         wrbuf_puts(wrbuf, "<name>");
310         if (!ht[i].name || !ht[i].name[0])
311             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
312         else
313             wrbuf_xmlputs(wrbuf, ht[i].name);
314         wrbuf_puts(wrbuf, "</name>\n");
315         
316         wrbuf_printf(wrbuf, "<frequency>%d</frequency>\n", ht[i].hits);
317         
318         wrbuf_puts(wrbuf, "<state>");
319         wrbuf_xmlputs(wrbuf, ht[i].state);
320         wrbuf_puts(wrbuf, "</state>\n");
321         
322         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
323                      ht[i].diagnostic);
324         wrbuf_puts(wrbuf, "</term>\n");
325     }
326 }
327
328 static void cmd_termlist(struct http_channel *c)
329 {
330     struct http_response *rs = c->response;
331     struct http_request *rq = c->request;
332     struct http_session *s = locate_session(rq, rs);
333     struct termlist_score **p;
334     int len;
335     int i;
336     char *name = http_argbyname(rq, "name");
337     char *nums = http_argbyname(rq, "num");
338     int num = 15;
339     int status;
340
341     if (!s)
342         return;
343
344     status = session_active_clients(s->psession);
345
346     if (!name)
347         name = "subject";
348     if (strlen(name) > 255)
349         return;
350     if (nums)
351         num = atoi(nums);
352
353     wrbuf_rewind(c->wrbuf);
354
355     wrbuf_puts(c->wrbuf, "<termlist>\n");
356     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", status);
357     while (*name)
358     {
359         char tname[256];
360         char *tp;
361
362         if (!(tp = strchr(name, ',')))
363             tp = name + strlen(name);
364         strncpy(tname, name, tp - name);
365         tname[tp - name] = '\0';
366
367         wrbuf_puts(c->wrbuf, "<list name=\"");
368         wrbuf_xmlputs(c->wrbuf, tname);
369         wrbuf_puts(c->wrbuf, "\">\n");
370         if (!strcmp(tname, "xtargets"))
371             targets_termlist(c->wrbuf, s->psession, num, c->nmem);
372         else
373         {
374             p = termlist(s->psession, tname, &len);
375             if (p)
376                 for (i = 0; i < len && i < num; i++){
377                     // prevnt sending empty term elements
378                     if (!p[i]->term || !p[i]->term[0])
379                         continue;
380
381                     wrbuf_puts(c->wrbuf, "<term>");
382                     wrbuf_puts(c->wrbuf, "<name>");
383                     wrbuf_xmlputs(c->wrbuf, p[i]->term);
384                     wrbuf_puts(c->wrbuf, "</name>");
385                         
386                     wrbuf_printf(c->wrbuf, 
387                                  "<frequency>%d</frequency>", 
388                                  p[i]->frequency);
389                     wrbuf_puts(c->wrbuf, "</term>\n");
390                }
391         }
392         wrbuf_puts(c->wrbuf, "</list>\n");
393         name = tp;
394         if (*name == ',')
395             name++;
396     }
397     wrbuf_puts(c->wrbuf, "</termlist>\n");
398     rs->payload = nmem_strdup(rq->channel->nmem, wrbuf_cstr(c->wrbuf));
399     http_send_response(c);
400 }
401
402
403 static void cmd_bytarget(struct http_channel *c)
404 {
405     struct http_response *rs = c->response;
406     struct http_request *rq = c->request;
407     struct http_session *s = locate_session(rq, rs);
408     struct hitsbytarget *ht;
409     int count, i;
410
411     if (!s)
412         return;
413     ht = hitsbytarget(s->psession, &count, c->nmem);
414     wrbuf_rewind(c->wrbuf);
415     wrbuf_puts(c->wrbuf, "<bytarget><status>OK</status>");
416
417     for (i = 0; i < count; i++)
418     {
419         wrbuf_puts(c->wrbuf, "\n<target>");
420
421         wrbuf_puts(c->wrbuf, "<id>");
422         wrbuf_xmlputs(c->wrbuf, ht[i].id);
423         wrbuf_puts(c->wrbuf, "</id>\n");
424
425         wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", ht[i].hits);
426         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
427         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
428
429         wrbuf_puts(c->wrbuf, "<state>");
430         wrbuf_xmlputs(c->wrbuf, ht[i].state);
431         wrbuf_puts(c->wrbuf, "</state>\n");
432
433         wrbuf_puts(c->wrbuf, "</target>");
434     }
435
436     wrbuf_puts(c->wrbuf, "</bytarget>");
437     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
438     http_send_response(c);
439 }
440
441 static void write_metadata(WRBUF w, struct conf_service *service,
442         struct record_metadata **ml, int full)
443 {
444     int imeta;
445
446     for (imeta = 0; imeta < service->num_metadata; imeta++)
447     {
448         struct conf_metadata *cmd = &service->metadata[imeta];
449         struct record_metadata *md;
450         if (!cmd->brief && !full)
451             continue;
452         for (md = ml[imeta]; md; md = md->next)
453         {
454             wrbuf_printf(w, "\n<md-%s>", cmd->name);
455
456             switch (cmd->type)
457             {
458                 case Metadata_type_generic:
459                     wrbuf_xmlputs(w, md->data.text.disp);
460                     break;
461                 case Metadata_type_year:
462                     wrbuf_printf(w, "%d", md->data.number.min);
463                     if (md->data.number.min != md->data.number.max)
464                         wrbuf_printf(w, "-%d", md->data.number.max);
465                     break;
466                 default:
467                     wrbuf_puts(w, "[can't represent]");
468             }
469             wrbuf_printf(w, "</md-%s>", cmd->name);
470         }
471     }
472 }
473
474 static void write_subrecord(struct record *r, WRBUF w,
475         struct conf_service *service, int show_details)
476 {
477     const char *name = session_setting_oneval(
478         client_get_database(r->client), PZ_NAME);
479
480     wrbuf_puts(w, "<location id=\"");
481     wrbuf_xmlputs(w, client_get_database(r->client)->database->url);
482     wrbuf_puts(w, "\" ");
483
484     wrbuf_puts(w, "name=\"");
485     wrbuf_xmlputs(w,  *name ? name : "Unknown");
486     wrbuf_puts(w, "\">");
487
488     if (show_details)
489         write_metadata(w, service, r->metadata, 1);
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_printf(c->wrbuf, "<recid>%s</recid>\n", rec->recid);
616         write_metadata(c->wrbuf, service, rec->metadata, 1);
617         for (r = rec->records; r; r = r->next)
618             write_subrecord(r, c->wrbuf, service, 1);
619         wrbuf_puts(c->wrbuf, "</record>\n");
620         rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
621         http_send_response(c);
622     }
623 }
624
625 static void cmd_record_ready(void *data)
626 {
627     struct http_channel *c = (struct http_channel *) data;
628
629     cmd_record(c);
630 }
631
632 static void show_records(struct http_channel *c, int active)
633 {
634     struct http_request *rq = c->request;
635     struct http_response *rs = c->response;
636     struct http_session *s = locate_session(rq, rs);
637     struct record_cluster **rl;
638     struct reclist_sortparms *sp;
639     char *start = http_argbyname(rq, "start");
640     char *num = http_argbyname(rq, "num");
641     char *sort = http_argbyname(rq, "sort");
642     int startn = 0;
643     int numn = 20;
644     int total;
645     int total_hits;
646     int i;
647
648     if (!s)
649         return;
650
651     // We haven't counted clients yet if we're called on a block release
652     if (active < 0)
653         active = session_active_clients(s->psession);
654
655     if (start)
656         startn = atoi(start);
657     if (num)
658         numn = atoi(num);
659     if (!sort)
660         sort = "relevance";
661     if (!(sp = reclist_parse_sortparms(c->nmem, sort)))
662     {
663         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
664         return;
665     }
666
667     rl = show(s->psession, sp, startn, &numn, &total, &total_hits, c->nmem);
668
669     wrbuf_rewind(c->wrbuf);
670     wrbuf_puts(c->wrbuf, "<show>\n<status>OK</status>\n");
671     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
672     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
673     wrbuf_printf(c->wrbuf, "<total>%d</total>\n", total_hits);
674     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
675     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
676
677     for (i = 0; i < numn; i++)
678     {
679         int ccount;
680         struct record *p;
681         struct record_cluster *rec = rl[i];
682         struct conf_service *service = global_parameters.server->service;
683
684         wrbuf_puts(c->wrbuf, "<hit>\n");
685         write_metadata(c->wrbuf, service, rec->metadata, 0);
686         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
687             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
688         if (ccount > 1)
689             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
690         wrbuf_printf(c->wrbuf, "<recid>%s</recid>\n", rec->recid);
691         wrbuf_puts(c->wrbuf, "</hit>\n");
692     }
693
694     wrbuf_puts(c->wrbuf, "</show>\n");
695     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
696     http_send_response(c);
697 }
698
699 static void show_records_ready(void *data)
700 {
701     struct http_channel *c = (struct http_channel *) data;
702
703     show_records(c, -1);
704 }
705
706 static void cmd_show(struct http_channel *c)
707 {
708     struct http_request *rq = c->request;
709     struct http_response *rs = c->response;
710     struct http_session *s = locate_session(rq, rs);
711     char *block = http_argbyname(rq, "block");
712     int status;
713
714     if (!s)
715         return;
716
717     status = session_active_clients(s->psession);
718
719     if (block)
720     {
721         if (status && (!s->psession->reclist || !s->psession->reclist->num_records))
722         {
723             // if there is already a watch/block. we do not block this one
724             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
725                                   show_records_ready, c, c) != 0)
726             {
727                 yaz_log(YLOG_DEBUG, "Blocking on cmd_show");
728             }
729             return;
730         }
731     }
732
733     show_records(c, status);
734 }
735
736 static void cmd_ping(struct http_channel *c)
737 {
738     struct http_request *rq = c->request;
739     struct http_response *rs = c->response;
740     struct http_session *s = locate_session(rq, rs);
741     if (!s)
742         return;
743     rs->payload = "<ping><status>OK</status></ping>";
744     http_send_response(c);
745 }
746
747 static int utf_8_valid(const char *str)
748 {
749     yaz_iconv_t cd = yaz_iconv_open("utf-8", "utf-8");
750     if (cd)
751     {
752         /* check that query is UTF-8 encoded */
753         char *inbuf = (char *) str; /* we know iconv does not alter this */
754         size_t inbytesleft = strlen(inbuf);
755
756         size_t outbytesleft = strlen(inbuf) + 10;
757         char *out = xmalloc(outbytesleft);
758         char *outbuf = out;
759         size_t r = yaz_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
760
761         /* if OK, try flushing the rest  */
762         if (r != (size_t) (-1))
763             r = yaz_iconv(cd, 0, 0, &outbuf, &outbytesleft);
764         yaz_iconv_close(cd);
765         xfree(out);
766         if (r == (size_t) (-1))
767             return 0;
768     }
769     return 1;
770 }
771
772 static void cmd_search(struct http_channel *c)
773 {
774     struct http_request *rq = c->request;
775     struct http_response *rs = c->response;
776     struct http_session *s = locate_session(rq, rs);
777     char *query = http_argbyname(rq, "query");
778     char *filter = http_argbyname(rq, "filter");
779     enum pazpar2_error_code code;
780     const char *addinfo = 0;
781
782     if (!s)
783         return;
784     if (!query)
785     {
786         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
787         return;
788     }
789     if (!utf_8_valid(query))
790     {
791         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
792         return;
793     }
794     code = search(s->psession, query, filter, &addinfo);
795     if (code)
796     {
797         error(rs, code, addinfo);
798         return;
799     }
800     rs->payload = "<search><status>OK</status></search>";
801     http_send_response(c);
802 }
803
804
805 static void cmd_stat(struct http_channel *c)
806 {
807     struct http_request *rq = c->request;
808     struct http_response *rs = c->response;
809     struct http_session *s = locate_session(rq, rs);
810     struct statistics stat;
811     int clients;
812
813     if (!s)
814         return;
815
816     clients = session_active_clients(s->psession);
817     statistics(s->psession, &stat);
818
819     wrbuf_rewind(c->wrbuf);
820     wrbuf_puts(c->wrbuf, "<stat>");
821     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
822     wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", stat.num_hits);
823     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
824     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
825     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
826     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
827     wrbuf_printf(c->wrbuf, "<initializing>%d</initializing>\n", stat.num_initializing);
828     wrbuf_printf(c->wrbuf, "<searching>%d</searching>\n", stat.num_searching);
829     wrbuf_printf(c->wrbuf, "<presenting>%d</presenting>\n", stat.num_presenting);
830     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
831     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
832     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
833     wrbuf_puts(c->wrbuf, "</stat>");
834     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
835     http_send_response(c);
836 }
837
838 static void cmd_info(struct http_channel *c)
839 {
840     char yaz_version_str[20];
841     struct http_response *rs = c->response;
842
843     wrbuf_rewind(c->wrbuf);
844     wrbuf_puts(c->wrbuf, "<info>\n");
845     wrbuf_puts(c->wrbuf, " <version>\n");
846     wrbuf_puts(c->wrbuf, "<pazpar2>");
847     wrbuf_xmlputs(c->wrbuf, VERSION);
848     wrbuf_puts(c->wrbuf, "</pazpar2>");
849
850
851     yaz_version(yaz_version_str, 0);
852     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
853     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
854     wrbuf_puts(c->wrbuf, "\">");
855     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
856     wrbuf_puts(c->wrbuf, "</yaz>\n");
857
858     wrbuf_puts(c->wrbuf, " </version>\n");
859     
860     wrbuf_puts(c->wrbuf, "</info>");
861     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
862     http_send_response(c);
863 }
864
865 struct {
866     char *name;
867     void (*fun)(struct http_channel *c);
868 } commands[] = {
869     { "init", cmd_init },
870     { "settings", cmd_settings },
871     { "stat", cmd_stat },
872     { "bytarget", cmd_bytarget },
873     { "show", cmd_show },
874     { "search", cmd_search },
875     { "termlist", cmd_termlist },
876     { "exit", cmd_exit },
877     { "ping", cmd_ping },
878     { "record", cmd_record },
879     { "info", cmd_info },
880     {0,0}
881 };
882
883 void http_command(struct http_channel *c)
884 {
885     char *command = http_argbyname(c->request, "command");
886     struct http_response *rs = http_create_response(c);
887     int i;
888
889     c->response = rs;
890
891     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
892     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
893
894     if (!command)
895     {
896         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
897         return;
898     }
899     for (i = 0; commands[i].name; i++)
900         if (!strcmp(commands[i].name, command))
901         {
902             (*commands[i].fun)(c);
903             break;
904         }
905     if (!commands[i].name)
906         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
907
908     return;
909 }
910
911 /*
912  * Local variables:
913  * c-basic-offset: 4
914  * indent-tabs-mode: nil
915  * End:
916  * vim: shiftwidth=4 tabstop=8 expandtab
917  */