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