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