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