Add <progress /> tag to support a progress bar. The value is between 0 ... 1
[pazpar2-moved-to-github.git] / src / http_command.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2009 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(void)
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(void)
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         if (ht[i].name && ht[i].name[0]) 
426         {
427             wrbuf_puts(c->wrbuf, "<name>");
428             wrbuf_xmlputs(c->wrbuf, ht[i].name);
429             wrbuf_puts(c->wrbuf, "</name>\n");
430         }
431
432         wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", ht[i].hits);
433         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
434         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
435
436         wrbuf_puts(c->wrbuf, "<state>");
437         wrbuf_xmlputs(c->wrbuf, ht[i].state);
438         wrbuf_puts(c->wrbuf, "</state>\n");
439
440         wrbuf_puts(c->wrbuf, "</target>");
441     }
442
443     wrbuf_puts(c->wrbuf, "</bytarget>");
444     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
445     http_send_response(c);
446 }
447
448 static void write_metadata(WRBUF w, struct conf_service *service,
449         struct record_metadata **ml, int full)
450 {
451     int imeta;
452
453     for (imeta = 0; imeta < service->num_metadata; imeta++)
454     {
455         struct conf_metadata *cmd = &service->metadata[imeta];
456         struct record_metadata *md;
457         if (!cmd->brief && !full)
458             continue;
459         for (md = ml[imeta]; md; md = md->next)
460         {
461             wrbuf_printf(w, "\n<md-%s>", cmd->name);
462
463             switch (cmd->type)
464             {
465                 case Metadata_type_generic:
466                     wrbuf_xmlputs(w, md->data.text.disp);
467                     break;
468                 case Metadata_type_year:
469                     wrbuf_printf(w, "%d", md->data.number.min);
470                     if (md->data.number.min != md->data.number.max)
471                         wrbuf_printf(w, "-%d", md->data.number.max);
472                     break;
473                 default:
474                     wrbuf_puts(w, "[can't represent]");
475             }
476             wrbuf_printf(w, "</md-%s>", cmd->name);
477         }
478     }
479 }
480
481 static void write_subrecord(struct record *r, WRBUF w,
482         struct conf_service *service, int show_details)
483 {
484     const char *name = session_setting_oneval(
485         client_get_database(r->client), PZ_NAME);
486
487     wrbuf_puts(w, "<location id=\"");
488     wrbuf_xmlputs(w, client_get_database(r->client)->database->url);
489     wrbuf_puts(w, "\" ");
490
491     wrbuf_puts(w, "name=\"");
492     wrbuf_xmlputs(w,  *name ? name : "Unknown");
493     wrbuf_puts(w, "\">");
494
495     write_metadata(w, service, r->metadata, show_details);
496     wrbuf_puts(w, "</location>\n");
497 }
498
499 static void show_raw_record_error(void *data, const char *addinfo)
500 {
501     http_channel_observer_t obs = data;
502     struct http_channel *c = http_channel_observer_chan(obs);
503     struct http_response *rs = c->response;
504
505     http_remove_observer(obs);
506
507     error(rs, PAZPAR2_RECORD_FAIL, addinfo);
508 }
509
510 static void show_raw_record_ok(void *data, const char *buf, size_t sz)
511 {
512     http_channel_observer_t obs = data;
513     struct http_channel *c = http_channel_observer_chan(obs);
514     struct http_response *rs = c->response;
515
516     http_remove_observer(obs);
517
518     wrbuf_write(c->wrbuf, buf, sz);
519     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
520     http_send_response(c);
521 }
522
523
524 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
525 {
526     http_channel_observer_t obs = data;
527     struct http_channel *c = http_channel_observer_chan(obs);
528     struct http_response *rs = c->response;
529
530     http_remove_observer(obs);
531
532     wrbuf_write(c->wrbuf, buf, sz);
533     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
534
535     rs->content_type = "application/octet-stream";
536     http_send_response(c);
537 }
538
539
540 void show_raw_reset(void *data, struct http_channel *c, void *data2)
541 {
542     //struct client *client = data;
543     //client_show_raw_remove(client, data2);
544 }
545
546 static void cmd_record_ready(void *data);
547
548 static void cmd_record(struct http_channel *c)
549 {
550     struct http_response *rs = c->response;
551     struct http_request *rq = c->request;
552     struct http_session *s = locate_session(rq, rs);
553     struct record_cluster *rec;
554     struct record *r;
555     struct conf_service *service = global_parameters.server->service;
556     const char *idstr = http_argbyname(rq, "id");
557     const char *offsetstr = http_argbyname(rq, "offset");
558     const char *binarystr = http_argbyname(rq, "binary");
559     
560     if (!s)
561         return;
562     if (!idstr)
563     {
564         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
565         return;
566     }
567     wrbuf_rewind(c->wrbuf);
568     if (!(rec = show_single(s->psession, idstr)))
569     {
570         if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
571                               cmd_record_ready, c, c) != 0)
572         {
573             error(rs, PAZPAR2_RECORD_MISSING, idstr);
574         }
575         return;
576     }
577     if (offsetstr)
578     {
579         int offset = atoi(offsetstr);
580         const char *syntax = http_argbyname(rq, "syntax");
581         const char *esn = http_argbyname(rq, "esn");
582         int i;
583         struct record*r = rec->records;
584         int binary = 0;
585
586         if (binarystr && *binarystr != '0')
587             binary = 1;
588
589         for (i = 0; i < offset && r; r = r->next, i++)
590             ;
591         if (!r)
592         {
593             error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
594             return;
595         }
596         else
597         {
598             void *data2;
599             http_channel_observer_t obs =
600                 http_add_observer(c, r->client, show_raw_reset);
601             int ret = 
602                 client_show_raw_begin(r->client, r->position, syntax, esn, 
603                                       obs /* data */,
604                                       show_raw_record_error,
605                                       (binary ? 
606                                        show_raw_record_ok_binary : 
607                                        show_raw_record_ok),
608                                       &data2,
609                                       (binary ? 1 : 0));
610             if (ret == -1)
611             {
612                 http_remove_observer(obs);
613                 error(rs, PAZPAR2_NO_SESSION, 0);
614                 return;
615             }
616         }
617     }
618     else
619     {
620         wrbuf_puts(c->wrbuf, "<record>\n");
621         wrbuf_puts(c->wrbuf, "<recid>");
622         wrbuf_xmlputs(c->wrbuf, rec->recid);
623         wrbuf_puts(c->wrbuf, "</recid>\n");
624         write_metadata(c->wrbuf, service, rec->metadata, 1);
625         for (r = rec->records; r; r = r->next)
626             write_subrecord(r, c->wrbuf, service, 1);
627         wrbuf_puts(c->wrbuf, "</record>\n");
628         rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
629         http_send_response(c);
630     }
631 }
632
633 static void cmd_record_ready(void *data)
634 {
635     struct http_channel *c = (struct http_channel *) data;
636
637     cmd_record(c);
638 }
639
640 static void show_records(struct http_channel *c, int active)
641 {
642     struct http_request *rq = c->request;
643     struct http_response *rs = c->response;
644     struct http_session *s = locate_session(rq, rs);
645     struct record_cluster **rl;
646     struct reclist_sortparms *sp;
647     char *start = http_argbyname(rq, "start");
648     char *num = http_argbyname(rq, "num");
649     char *sort = http_argbyname(rq, "sort");
650     int startn = 0;
651     int numn = 20;
652     int total;
653     int total_hits;
654     int i;
655
656     if (!s)
657         return;
658
659     // We haven't counted clients yet if we're called on a block release
660     if (active < 0)
661         active = session_active_clients(s->psession);
662
663     if (start)
664         startn = atoi(start);
665     if (num)
666         numn = atoi(num);
667     if (!sort)
668         sort = "relevance";
669     if (!(sp = reclist_parse_sortparms(c->nmem, sort)))
670     {
671         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
672         return;
673     }
674
675     rl = show(s->psession, sp, startn, &numn, &total, &total_hits, c->nmem);
676
677     wrbuf_rewind(c->wrbuf);
678     wrbuf_puts(c->wrbuf, "<show>\n<status>OK</status>\n");
679     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
680     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
681     wrbuf_printf(c->wrbuf, "<total>%d</total>\n", total_hits);
682     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
683     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
684
685     for (i = 0; i < numn; i++)
686     {
687         int ccount;
688         struct record *p;
689         struct record_cluster *rec = rl[i];
690         struct conf_service *service = global_parameters.server->service;
691
692         wrbuf_puts(c->wrbuf, "<hit>\n");
693         write_metadata(c->wrbuf, service, rec->metadata, 0);
694         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
695             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
696         if (ccount > 1)
697             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
698         wrbuf_puts(c->wrbuf, "<recid>");
699         wrbuf_xmlputs(c->wrbuf, rec->recid);
700         wrbuf_puts(c->wrbuf, "</recid>\n");
701         wrbuf_puts(c->wrbuf, "</hit>\n");
702     }
703
704     wrbuf_puts(c->wrbuf, "</show>\n");
705     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
706     http_send_response(c);
707 }
708
709 static void show_records_ready(void *data)
710 {
711     struct http_channel *c = (struct http_channel *) data;
712
713     show_records(c, -1);
714 }
715
716 static void cmd_show(struct http_channel *c)
717 {
718     struct http_request *rq = c->request;
719     struct http_response *rs = c->response;
720     struct http_session *s = locate_session(rq, rs);
721     char *block = http_argbyname(rq, "block");
722     int status;
723
724     if (!s)
725         return;
726
727     status = session_active_clients(s->psession);
728
729     if (block)
730     {
731         if (status && (!s->psession->reclist || !s->psession->reclist->num_records))
732         {
733             // if there is already a watch/block. we do not block this one
734             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
735                                   show_records_ready, c, c) != 0)
736             {
737                 yaz_log(YLOG_DEBUG, "Blocking on cmd_show");
738             }
739             return;
740         }
741     }
742
743     show_records(c, status);
744 }
745
746 static void cmd_ping(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     if (!s)
752         return;
753     rs->payload = "<ping><status>OK</status></ping>";
754     http_send_response(c);
755 }
756
757 static int utf_8_valid(const char *str)
758 {
759     yaz_iconv_t cd = yaz_iconv_open("utf-8", "utf-8");
760     if (cd)
761     {
762         /* check that query is UTF-8 encoded */
763         char *inbuf = (char *) str; /* we know iconv does not alter this */
764         size_t inbytesleft = strlen(inbuf);
765
766         size_t outbytesleft = strlen(inbuf) + 10;
767         char *out = xmalloc(outbytesleft);
768         char *outbuf = out;
769         size_t r = yaz_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
770
771         /* if OK, try flushing the rest  */
772         if (r != (size_t) (-1))
773             r = yaz_iconv(cd, 0, 0, &outbuf, &outbytesleft);
774         yaz_iconv_close(cd);
775         xfree(out);
776         if (r == (size_t) (-1))
777             return 0;
778     }
779     return 1;
780 }
781
782 static void cmd_search(struct http_channel *c)
783 {
784     struct http_request *rq = c->request;
785     struct http_response *rs = c->response;
786     struct http_session *s = locate_session(rq, rs);
787     char *query = http_argbyname(rq, "query");
788     char *filter = http_argbyname(rq, "filter");
789     enum pazpar2_error_code code;
790     const char *addinfo = 0;
791
792     if (!s)
793         return;
794     if (!query)
795     {
796         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
797         return;
798     }
799     if (!utf_8_valid(query))
800     {
801         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
802         return;
803     }
804     code = search(s->psession, query, filter, &addinfo);
805     if (code)
806     {
807         error(rs, code, addinfo);
808         return;
809     }
810     rs->payload = "<search><status>OK</status></search>";
811     http_send_response(c);
812 }
813
814
815 static void cmd_stat(struct http_channel *c)
816 {
817     struct http_request *rq = c->request;
818     struct http_response *rs = c->response;
819     struct http_session *s = locate_session(rq, rs);
820     struct statistics stat;
821     int clients;
822
823     float progress = 0;
824
825     if (!s)
826         return;
827
828     clients = session_active_clients(s->psession);
829     statistics(s->psession, &stat);
830
831     if (stat.num_clients > 0) {
832         progress = (stat.num_clients  - clients) / (float)stat.num_clients;
833     }
834
835     wrbuf_rewind(c->wrbuf);
836     wrbuf_puts(c->wrbuf, "<stat>");
837     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
838     wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", stat.num_hits);
839     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
840     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
841     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
842     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
843     wrbuf_printf(c->wrbuf, "<working>%d</working>\n", stat.num_working);
844     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
845     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
846     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
847     wrbuf_printf(c->wrbuf, "<progress>%.2f</progress>\n", progress);
848     wrbuf_puts(c->wrbuf, "</stat>");
849     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
850     http_send_response(c);
851 }
852
853 static void cmd_info(struct http_channel *c)
854 {
855     char yaz_version_str[20];
856     struct http_response *rs = c->response;
857
858     wrbuf_rewind(c->wrbuf);
859     wrbuf_puts(c->wrbuf, "<info>\n");
860     wrbuf_puts(c->wrbuf, " <version>\n");
861     wrbuf_puts(c->wrbuf, "<pazpar2>");
862     wrbuf_xmlputs(c->wrbuf, VERSION);
863     wrbuf_puts(c->wrbuf, "</pazpar2>");
864
865
866     yaz_version(yaz_version_str, 0);
867     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
868     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
869     wrbuf_puts(c->wrbuf, "\">");
870     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
871     wrbuf_puts(c->wrbuf, "</yaz>\n");
872
873     wrbuf_puts(c->wrbuf, " </version>\n");
874     
875     wrbuf_puts(c->wrbuf, "</info>");
876     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
877     http_send_response(c);
878 }
879
880 struct {
881     char *name;
882     void (*fun)(struct http_channel *c);
883 } commands[] = {
884     { "init", cmd_init },
885     { "settings", cmd_settings },
886     { "stat", cmd_stat },
887     { "bytarget", cmd_bytarget },
888     { "show", cmd_show },
889     { "search", cmd_search },
890     { "termlist", cmd_termlist },
891     { "exit", cmd_exit },
892     { "ping", cmd_ping },
893     { "record", cmd_record },
894     { "info", cmd_info },
895     {0,0}
896 };
897
898 void http_command(struct http_channel *c)
899 {
900     char *command = http_argbyname(c->request, "command");
901     struct http_response *rs = http_create_response(c);
902     int i;
903
904     c->response = rs;
905
906     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
907     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
908
909     if (!command)
910     {
911         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
912         return;
913     }
914     for (i = 0; commands[i].name; i++)
915         if (!strcmp(commands[i].name, command))
916         {
917             (*commands[i].fun)(c);
918             break;
919         }
920     if (!commands[i].name)
921         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
922
923     return;
924 }
925
926 /*
927  * Local variables:
928  * c-basic-offset: 4
929  * c-file-style: "Stroustrup"
930  * indent-tabs-mode: nil
931  * End:
932  * vim: shiftwidth=4 tabstop=8 expandtab
933  */
934