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