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