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