Renamed config.[ch] to pazpar2_config.[ch].
[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 "util.h"
40 #include "eventl.h"
41 #include "pazpar2.h"
42 #include "http.h"
43 #include "http_command.h"
44 #include "settings.h"
45 #include "client.h"
46
47 // Update this when the protocol changes
48 #define PAZPAR2_PROTOCOL_VERSION "1"
49
50 struct http_session {
51     IOCHAN timeout_iochan;     // NOTE: This is NOT associated with a socket
52     struct session *psession;
53     unsigned int session_id;
54     int timestamp;
55     NMEM nmem;
56     struct http_session *next;
57 };
58
59 static struct http_session *session_list = 0;
60 void http_session_destroy(struct http_session *s);
61
62 static void session_timeout(IOCHAN i, int event)
63 {
64     struct http_session *s = iochan_getdata(i);
65     http_session_destroy(s);
66 }
67
68 struct http_session *http_session_create()
69 {
70     NMEM nmem = nmem_create();
71     struct http_session *r = nmem_malloc(nmem, sizeof(*r));
72
73     r->psession = new_session(nmem);
74     r->session_id = 0;
75     r->timestamp = 0;
76     r->nmem = nmem;
77     r->next = session_list;
78     session_list = r;
79     r->timeout_iochan = iochan_create(-1, session_timeout, 0);
80     iochan_setdata(r->timeout_iochan, r);
81     iochan_settimeout(r->timeout_iochan, global_parameters.session_timeout);
82
83     pazpar2_add_channel(r->timeout_iochan);
84     return r;
85 }
86
87 void http_session_destroy(struct http_session *s)
88 {
89     struct http_session **p;
90
91     for (p = &session_list; *p; p = &(*p)->next)
92         if (*p == s)
93         {
94             *p = (*p)->next;
95             break;
96         }
97     yaz_log(YLOG_LOG, "Destroying session %u", s->session_id);
98     iochan_destroy(s->timeout_iochan);
99     destroy_session(s->psession);
100     nmem_destroy(s->nmem);
101 }
102
103 static const char *get_msg(enum pazpar2_error_code code)
104 {
105     struct pazpar2_error_msg {
106         enum pazpar2_error_code code;
107         const char *msg;
108     };
109     static const struct pazpar2_error_msg ar[] = {
110         { PAZPAR2_NO_SESSION, "Session does not exist or it has expired"},
111         { PAZPAR2_MISSING_PARAMETER, "Missing parameter"},
112         { PAZPAR2_MALFORMED_PARAMETER_VALUE, "Malformed parameter value"},
113         { PAZPAR2_MALFORMED_PARAMETER_ENCODING, "Malformed parameter encoding"},
114         { PAZPAR2_MALFORMED_SETTING, "Malformed setting argument"},
115         { PAZPAR2_HITCOUNTS_FAILED, "Failed to retrieve hitcounts"},
116         { PAZPAR2_RECORD_MISSING, "Record missing"},
117         { PAZPAR2_NO_TARGETS, "No targets"},
118         { PAZPAR2_CONFIG_TARGET, "Target cannot be configured"},
119         { PAZPAR2_RECORD_FAIL, "Record command failed"},
120         { PAZPAR2_NOT_IMPLEMENTED, "Not implemented"},
121         { PAZPAR2_LAST_ERROR, "Last error"},
122         { 0, 0 }
123     };
124     int i = 0;
125     while (ar[i].msg)
126     {
127         if (code == ar[i].code)
128             return ar[i].msg;
129         i++;
130     }
131     return "No error";
132 }
133
134 static void error(struct http_response *rs, 
135                   enum pazpar2_error_code code,
136                   const char *addinfo)
137 {
138     struct http_channel *c = rs->channel;
139     WRBUF text = wrbuf_alloc();
140     const char *http_status = "417";
141     const char *msg = get_msg(code);
142     
143     rs->msg = nmem_strdup(c->nmem, msg);
144     strcpy(rs->code, http_status);
145
146     wrbuf_printf(text, "<error code=\"%d\" msg=\"%s\">", (int) code,
147                msg);
148     if (addinfo)
149         wrbuf_xmlputs(text, addinfo);
150     wrbuf_puts(text, "</error>");
151
152     yaz_log(YLOG_WARN, "HTTP %s %s%s%s", http_status,
153             msg, addinfo ? ": " : "" , addinfo ? addinfo : "");
154     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(text));
155     wrbuf_destroy(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
517 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
518 {
519     http_channel_observer_t obs = data;
520     struct http_channel *c = http_channel_observer_chan(obs);
521     struct http_response *rs = c->response;
522
523     http_remove_observer(obs);
524
525     wrbuf_write(c->wrbuf, buf, sz);
526     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
527
528     rs->content_type = "application/octet-stream";
529     http_send_response(c);
530 }
531
532
533 void show_raw_reset(void *data, struct http_channel *c, void *data2)
534 {
535     struct client *client = data;
536     client_show_raw_remove(client, data2);
537 }
538
539 static void cmd_record_ready(void *data);
540
541 static void cmd_record(struct http_channel *c)
542 {
543     struct http_response *rs = c->response;
544     struct http_request *rq = c->request;
545     struct http_session *s = locate_session(rq, rs);
546     struct record_cluster *rec;
547     struct record *r;
548     struct conf_service *service = global_parameters.server->service;
549     const char *idstr = http_argbyname(rq, "id");
550     const char *offsetstr = http_argbyname(rq, "offset");
551     const char *binarystr = http_argbyname(rq, "binary");
552     
553     if (!s)
554         return;
555     if (!idstr)
556     {
557         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
558         return;
559     }
560     wrbuf_rewind(c->wrbuf);
561     if (!(rec = show_single(s->psession, idstr)))
562     {
563         if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
564                               cmd_record_ready, c, c) != 0)
565         {
566             error(rs, PAZPAR2_RECORD_MISSING, idstr);
567         }
568         return;
569     }
570     if (offsetstr)
571     {
572         int offset = atoi(offsetstr);
573         const char *syntax = http_argbyname(rq, "syntax");
574         const char *esn = http_argbyname(rq, "esn");
575         int i;
576         struct record*r = rec->records;
577         int binary = 0;
578
579         if (binarystr && *binarystr != '0')
580             binary = 1;
581
582         for (i = 0; i < offset && r; r = r->next, i++)
583             ;
584         if (!r)
585         {
586             error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
587             return;
588         }
589         else
590         {
591             void *data2;
592             http_channel_observer_t obs =
593                 http_add_observer(c, r->client, show_raw_reset);
594             int ret = 
595                 client_show_raw_begin(r->client, r->position, syntax, esn, 
596                                       obs /* data */,
597                                       show_raw_record_error,
598                                       (binary ? 
599                                        show_raw_record_ok_binary : 
600                                        show_raw_record_ok),
601                                       &data2,
602                                       (binary ? 1 : 0));
603             if (ret == -1)
604             {
605                 http_remove_observer(obs);
606                 error(rs, PAZPAR2_NO_SESSION, 0);
607                 return;
608             }
609         }
610     }
611     else
612     {
613         wrbuf_puts(c->wrbuf, "<record>\n");
614         wrbuf_printf(c->wrbuf, "<recid>%s</recid>\n", rec->recid);
615         write_metadata(c->wrbuf, service, rec->metadata, 1);
616         for (r = rec->records; r; r = r->next)
617             write_subrecord(r, c->wrbuf, service, 1);
618         wrbuf_puts(c->wrbuf, "</record>\n");
619         rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
620         http_send_response(c);
621     }
622 }
623
624 static void cmd_record_ready(void *data)
625 {
626     struct http_channel *c = (struct http_channel *) data;
627
628     cmd_record(c);
629 }
630
631 static void show_records(struct http_channel *c, int active)
632 {
633     struct http_request *rq = c->request;
634     struct http_response *rs = c->response;
635     struct http_session *s = locate_session(rq, rs);
636     struct record_cluster **rl;
637     struct reclist_sortparms *sp;
638     char *start = http_argbyname(rq, "start");
639     char *num = http_argbyname(rq, "num");
640     char *sort = http_argbyname(rq, "sort");
641     int startn = 0;
642     int numn = 20;
643     int total;
644     int total_hits;
645     int i;
646
647     if (!s)
648         return;
649
650     // We haven't counted clients yet if we're called on a block release
651     if (active < 0)
652         active = session_active_clients(s->psession);
653
654     if (start)
655         startn = atoi(start);
656     if (num)
657         numn = atoi(num);
658     if (!sort)
659         sort = "relevance";
660     if (!(sp = reclist_parse_sortparms(c->nmem, sort)))
661     {
662         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
663         return;
664     }
665
666     rl = show(s->psession, sp, startn, &numn, &total, &total_hits, c->nmem);
667
668     wrbuf_rewind(c->wrbuf);
669     wrbuf_puts(c->wrbuf, "<show>\n<status>OK</status>\n");
670     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
671     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
672     wrbuf_printf(c->wrbuf, "<total>%d</total>\n", total_hits);
673     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
674     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
675
676     for (i = 0; i < numn; i++)
677     {
678         int ccount;
679         struct record *p;
680         struct record_cluster *rec = rl[i];
681         struct conf_service *service = global_parameters.server->service;
682
683         wrbuf_puts(c->wrbuf, "<hit>\n");
684         write_metadata(c->wrbuf, service, rec->metadata, 0);
685         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
686             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
687         if (ccount > 1)
688             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
689         wrbuf_printf(c->wrbuf, "<recid>%s</recid>\n", rec->recid);
690         wrbuf_puts(c->wrbuf, "</hit>\n");
691     }
692
693     wrbuf_puts(c->wrbuf, "</show>\n");
694     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
695     http_send_response(c);
696 }
697
698 static void show_records_ready(void *data)
699 {
700     struct http_channel *c = (struct http_channel *) data;
701
702     show_records(c, -1);
703 }
704
705 static void cmd_show(struct http_channel *c)
706 {
707     struct http_request *rq = c->request;
708     struct http_response *rs = c->response;
709     struct http_session *s = locate_session(rq, rs);
710     char *block = http_argbyname(rq, "block");
711     int status;
712
713     if (!s)
714         return;
715
716     status = session_active_clients(s->psession);
717
718     if (block)
719     {
720         if (status && (!s->psession->reclist || !s->psession->reclist->num_records))
721         {
722             // if there is already a watch/block. we do not block this one
723             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
724                                   show_records_ready, c, c) != 0)
725             {
726                 yaz_log(YLOG_DEBUG, "Blocking on cmd_show");
727             }
728             return;
729         }
730     }
731
732     show_records(c, status);
733 }
734
735 static void cmd_ping(struct http_channel *c)
736 {
737     struct http_request *rq = c->request;
738     struct http_response *rs = c->response;
739     struct http_session *s = locate_session(rq, rs);
740     if (!s)
741         return;
742     rs->payload = "<ping><status>OK</status></ping>";
743     http_send_response(c);
744 }
745
746 static int utf_8_valid(const char *str)
747 {
748     yaz_iconv_t cd = yaz_iconv_open("utf-8", "utf-8");
749     if (cd)
750     {
751         /* check that query is UTF-8 encoded */
752         char *inbuf = (char *) str; /* we know iconv does not alter this */
753         size_t inbytesleft = strlen(inbuf);
754
755         size_t outbytesleft = strlen(inbuf) + 10;
756         char *out = xmalloc(outbytesleft);
757         char *outbuf = out;
758         size_t r = yaz_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
759
760         /* if OK, try flushing the rest  */
761         if (r != (size_t) (-1))
762             r = yaz_iconv(cd, 0, 0, &outbuf, &outbytesleft);
763         yaz_iconv_close(cd);
764         xfree(out);
765         if (r == (size_t) (-1))
766             return 0;
767     }
768     return 1;
769 }
770
771 static void cmd_search(struct http_channel *c)
772 {
773     struct http_request *rq = c->request;
774     struct http_response *rs = c->response;
775     struct http_session *s = locate_session(rq, rs);
776     char *query = http_argbyname(rq, "query");
777     char *filter = http_argbyname(rq, "filter");
778     enum pazpar2_error_code code;
779     const char *addinfo = 0;
780
781     if (!s)
782         return;
783     if (!query)
784     {
785         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
786         return;
787     }
788     if (!utf_8_valid(query))
789     {
790         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
791         return;
792     }
793     code = search(s->psession, query, filter, &addinfo);
794     if (code)
795     {
796         error(rs, code, addinfo);
797         return;
798     }
799     rs->payload = "<search><status>OK</status></search>";
800     http_send_response(c);
801 }
802
803
804 static void cmd_stat(struct http_channel *c)
805 {
806     struct http_request *rq = c->request;
807     struct http_response *rs = c->response;
808     struct http_session *s = locate_session(rq, rs);
809     struct statistics stat;
810     int clients;
811
812     if (!s)
813         return;
814
815     clients = session_active_clients(s->psession);
816     statistics(s->psession, &stat);
817
818     wrbuf_rewind(c->wrbuf);
819     wrbuf_puts(c->wrbuf, "<stat>");
820     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
821     wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", stat.num_hits);
822     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
823     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
824     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
825     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
826     wrbuf_printf(c->wrbuf, "<initializing>%d</initializing>\n", stat.num_initializing);
827     wrbuf_printf(c->wrbuf, "<searching>%d</searching>\n", stat.num_searching);
828     wrbuf_printf(c->wrbuf, "<presenting>%d</presenting>\n", stat.num_presenting);
829     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
830     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
831     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
832     wrbuf_puts(c->wrbuf, "</stat>");
833     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
834     http_send_response(c);
835 }
836
837 static void cmd_info(struct http_channel *c)
838 {
839     char yaz_version_str[20];
840     struct http_response *rs = c->response;
841
842     wrbuf_rewind(c->wrbuf);
843     wrbuf_puts(c->wrbuf, "<info>\n");
844     wrbuf_puts(c->wrbuf, " <version>\n");
845     wrbuf_puts(c->wrbuf, "<pazpar2>");
846     wrbuf_xmlputs(c->wrbuf, VERSION);
847     wrbuf_puts(c->wrbuf, "</pazpar2>");
848
849
850     yaz_version(yaz_version_str, 0);
851     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
852     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
853     wrbuf_puts(c->wrbuf, "\">");
854     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
855     wrbuf_puts(c->wrbuf, "</yaz>\n");
856
857     wrbuf_puts(c->wrbuf, " </version>\n");
858     
859     wrbuf_puts(c->wrbuf, "</info>");
860     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
861     http_send_response(c);
862 }
863
864 struct {
865     char *name;
866     void (*fun)(struct http_channel *c);
867 } commands[] = {
868     { "init", cmd_init },
869     { "settings", cmd_settings },
870     { "stat", cmd_stat },
871     { "bytarget", cmd_bytarget },
872     { "show", cmd_show },
873     { "search", cmd_search },
874     { "termlist", cmd_termlist },
875     { "exit", cmd_exit },
876     { "ping", cmd_ping },
877     { "record", cmd_record },
878     { "info", cmd_info },
879     {0,0}
880 };
881
882 void http_command(struct http_channel *c)
883 {
884     char *command = http_argbyname(c->request, "command");
885     struct http_response *rs = http_create_response(c);
886     int i;
887
888     c->response = rs;
889
890     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
891     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
892
893     if (!command)
894     {
895         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
896         return;
897     }
898     for (i = 0; commands[i].name; i++)
899         if (!strcmp(commands[i].name, command))
900         {
901             (*commands[i].fun)(c);
902             break;
903         }
904     if (!commands[i].name)
905         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
906
907     return;
908 }
909
910 /*
911  * Local variables:
912  * c-basic-offset: 4
913  * indent-tabs-mode: nil
914  * End:
915  * vim: shiftwidth=4 tabstop=8 expandtab
916  */