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