Use Odr_int type for hit counts
[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>" ODR_INT_PRINTF "</frequency>\n",
383                      ht[i].hits);
384         
385         wrbuf_puts(wrbuf, "<state>");
386         wrbuf_xmlputs(wrbuf, ht[i].state);
387         wrbuf_puts(wrbuf, "</state>\n");
388         
389         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
390                      ht[i].diagnostic);
391         wrbuf_puts(wrbuf, "</term>\n");
392     }
393 }
394
395 static void cmd_termlist(struct http_channel *c)
396 {
397     struct http_response *rs = c->response;
398     struct http_request *rq = c->request;
399     struct http_session *s = locate_session(rq, rs);
400     struct termlist_score **p;
401     int len;
402     int i;
403     const char *name = http_argbyname(rq, "name");
404     const char *nums = http_argbyname(rq, "num");
405     int num = 15;
406     int status;
407
408     if (!s)
409         return;
410
411     status = session_active_clients(s->psession);
412
413     if (!name)
414         name = "subject";
415     if (strlen(name) > 255)
416         return;
417     if (nums)
418         num = atoi(nums);
419
420     wrbuf_rewind(c->wrbuf);
421
422     wrbuf_puts(c->wrbuf, "<termlist>\n");
423     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", status);
424     while (*name)
425     {
426         char tname[256];
427         const char *tp;
428
429         if (!(tp = strchr(name, ',')))
430             tp = name + strlen(name);
431         strncpy(tname, name, tp - name);
432         tname[tp - name] = '\0';
433
434         wrbuf_puts(c->wrbuf, "<list name=\"");
435         wrbuf_xmlputs(c->wrbuf, tname);
436         wrbuf_puts(c->wrbuf, "\">\n");
437         if (!strcmp(tname, "xtargets"))
438             targets_termlist(c->wrbuf, s->psession, num, c->nmem);
439         else
440         {
441             p = termlist(s->psession, tname, &len);
442             if (p)
443                 for (i = 0; i < len && i < num; i++){
444                     // prevnt sending empty term elements
445                     if (!p[i]->term || !p[i]->term[0])
446                         continue;
447
448                     wrbuf_puts(c->wrbuf, "<term>");
449                     wrbuf_puts(c->wrbuf, "<name>");
450                     wrbuf_xmlputs(c->wrbuf, p[i]->term);
451                     wrbuf_puts(c->wrbuf, "</name>");
452                         
453                     wrbuf_printf(c->wrbuf, 
454                                  "<frequency>%d</frequency>", 
455                                  p[i]->frequency);
456                     wrbuf_puts(c->wrbuf, "</term>\n");
457                }
458         }
459         wrbuf_puts(c->wrbuf, "</list>\n");
460         name = tp;
461         if (*name == ',')
462             name++;
463     }
464     wrbuf_puts(c->wrbuf, "</termlist>\n");
465     rs->payload = nmem_strdup(rq->channel->nmem, wrbuf_cstr(c->wrbuf));
466     http_send_response(c);
467 }
468
469
470 static void cmd_bytarget(struct http_channel *c)
471 {
472     struct http_response *rs = c->response;
473     struct http_request *rq = c->request;
474     struct http_session *s = locate_session(rq, rs);
475     struct hitsbytarget *ht;
476     const char *settings = http_argbyname(rq, "settings");
477     int count, i;
478
479     if (!s)
480         return;
481     ht = hitsbytarget(s->psession, &count, c->nmem);
482     wrbuf_rewind(c->wrbuf);
483     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<bytarget><status>OK</status>");
484
485     for (i = 0; i < count; i++)
486     {
487         wrbuf_puts(c->wrbuf, "\n<target>");
488
489         wrbuf_puts(c->wrbuf, "<id>");
490         wrbuf_xmlputs(c->wrbuf, ht[i].id);
491         wrbuf_puts(c->wrbuf, "</id>\n");
492
493         if (ht[i].name && ht[i].name[0]) 
494         {
495             wrbuf_puts(c->wrbuf, "<name>");
496             wrbuf_xmlputs(c->wrbuf, ht[i].name);
497             wrbuf_puts(c->wrbuf, "</name>\n");
498         }
499
500         wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", ht[i].hits);
501         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
502         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
503
504         wrbuf_puts(c->wrbuf, "<state>");
505         wrbuf_xmlputs(c->wrbuf, ht[i].state);
506         wrbuf_puts(c->wrbuf, "</state>\n");
507         if (settings && *settings == '1')
508         {
509             wrbuf_puts(c->wrbuf, "<settings>\n");
510             wrbuf_puts(c->wrbuf, wrbuf_cstr(ht[i].settings_xml));
511             wrbuf_puts(c->wrbuf, "</settings>\n");
512         }
513         wrbuf_puts(c->wrbuf, "</target>");
514         wrbuf_destroy(ht[i].settings_xml);
515     }
516
517     wrbuf_puts(c->wrbuf, "</bytarget>");
518     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
519     http_send_response(c);
520 }
521
522 static void write_metadata(WRBUF w, struct conf_service *service,
523         struct record_metadata **ml, int full)
524 {
525     int imeta;
526
527     for (imeta = 0; imeta < service->num_metadata; imeta++)
528     {
529         struct conf_metadata *cmd = &service->metadata[imeta];
530         struct record_metadata *md;
531         if (!cmd->brief && !full)
532             continue;
533         for (md = ml[imeta]; md; md = md->next)
534         {
535             struct record_metadata_attr *attr = md->attributes;
536             wrbuf_printf(w, "\n<md-%s", cmd->name);
537
538             for (; attr; attr = attr->next)
539             {
540                 wrbuf_printf(w, " %s=\"", attr->name);
541                 wrbuf_xmlputs(w, attr->value);
542                 wrbuf_puts(w, "\"");
543             }
544             wrbuf_puts(w, ">");
545             switch (cmd->type)
546             {
547                 case Metadata_type_generic:
548                     wrbuf_xmlputs(w, md->data.text.disp);
549                     break;
550                 case Metadata_type_year:
551                     wrbuf_printf(w, "%d", md->data.number.min);
552                     if (md->data.number.min != md->data.number.max)
553                         wrbuf_printf(w, "-%d", md->data.number.max);
554                     break;
555                 default:
556                     wrbuf_puts(w, "[can't represent]");
557             }
558             wrbuf_printf(w, "</md-%s>", cmd->name);
559         }
560     }
561 }
562
563 static void write_subrecord(struct record *r, WRBUF w,
564         struct conf_service *service, int show_details)
565 {
566     const char *name = session_setting_oneval(
567         client_get_database(r->client), PZ_NAME);
568
569     wrbuf_puts(w, "<location id=\"");
570     wrbuf_xmlputs(w, client_get_database(r->client)->database->url);
571     wrbuf_puts(w, "\" ");
572
573     wrbuf_puts(w, "name=\"");
574     wrbuf_xmlputs(w,  *name ? name : "Unknown");
575     wrbuf_puts(w, "\">");
576
577     write_metadata(w, service, r->metadata, show_details);
578     wrbuf_puts(w, "</location>\n");
579 }
580
581 static void show_raw_record_error(void *data, const char *addinfo)
582 {
583     http_channel_observer_t obs = data;
584     struct http_channel *c = http_channel_observer_chan(obs);
585     struct http_response *rs = c->response;
586
587     http_remove_observer(obs);
588
589     error(rs, PAZPAR2_RECORD_FAIL, addinfo);
590 }
591
592 static void show_raw_record_ok(void *data, const char *buf, size_t sz)
593 {
594     http_channel_observer_t obs = data;
595     struct http_channel *c = http_channel_observer_chan(obs);
596     struct http_response *rs = c->response;
597
598     http_remove_observer(obs);
599
600     wrbuf_write(c->wrbuf, buf, sz);
601     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
602     http_send_response(c);
603 }
604
605
606 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
607 {
608     http_channel_observer_t obs = data;
609     struct http_channel *c = http_channel_observer_chan(obs);
610     struct http_response *rs = c->response;
611
612     http_remove_observer(obs);
613
614     wrbuf_write(c->wrbuf, buf, sz);
615     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
616
617     rs->content_type = "application/octet-stream";
618     http_send_response(c);
619 }
620
621
622 void show_raw_reset(void *data, struct http_channel *c, void *data2)
623 {
624     //struct client *client = data;
625     //client_show_raw_remove(client, data2);
626 }
627
628 static void cmd_record_ready(void *data);
629
630 static void cmd_record(struct http_channel *c)
631 {
632     struct http_response *rs = c->response;
633     struct http_request *rq = c->request;
634     struct http_session *s = locate_session(rq, rs);
635     struct record_cluster *rec, *prev_r, *next_r;
636     struct record *r;
637     struct conf_service *service;
638     const char *idstr = http_argbyname(rq, "id");
639     const char *offsetstr = http_argbyname(rq, "offset");
640     const char *binarystr = http_argbyname(rq, "binary");
641     
642     if (!s)
643         return;
644     service = s->psession->service;
645     if (!idstr)
646     {
647         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
648         return;
649     }
650     wrbuf_rewind(c->wrbuf);
651     if (!(rec = show_single(s->psession, idstr, &prev_r, &next_r)))
652     {
653         if (session_active_clients(s->psession) == 0)
654         {
655             error(rs, PAZPAR2_RECORD_MISSING, idstr);
656         }
657         else if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
658                               cmd_record_ready, c, c) != 0)
659         {
660             error(rs, PAZPAR2_RECORD_MISSING, idstr);
661         }
662         return;
663     }
664     if (offsetstr)
665     {
666         int offset = atoi(offsetstr);
667         const char *syntax = http_argbyname(rq, "syntax");
668         const char *esn = http_argbyname(rq, "esn");
669         int i;
670         struct record*r = rec->records;
671         int binary = 0;
672
673         if (binarystr && *binarystr != '0')
674             binary = 1;
675
676         for (i = 0; i < offset && r; r = r->next, i++)
677             ;
678         if (!r)
679         {
680             error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
681             return;
682         }
683         else
684         {
685             http_channel_observer_t obs =
686                 http_add_observer(c, r->client, show_raw_reset);
687             int ret = client_show_raw_begin(r->client, r->position,
688                                         syntax, esn, 
689                                         obs /* data */,
690                                         show_raw_record_error,
691                                         (binary ? 
692                                          show_raw_record_ok_binary : 
693                                          show_raw_record_ok),
694                                         (binary ? 1 : 0));
695             if (ret == -1)
696             {
697                 http_remove_observer(obs);
698                 error(rs, PAZPAR2_NO_SESSION, 0);
699             }
700         }
701     }
702     else
703     {
704         wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<record>\n");
705         wrbuf_puts(c->wrbuf, "<recid>");
706         wrbuf_xmlputs(c->wrbuf, rec->recid);
707         wrbuf_puts(c->wrbuf, "</recid>\n");
708         if (prev_r)
709         {
710             wrbuf_puts(c->wrbuf, "<prevrecid>");
711             wrbuf_xmlputs(c->wrbuf, prev_r->recid);
712             wrbuf_puts(c->wrbuf, "</prevrecid>\n");
713         }
714         if (next_r)
715         {
716             wrbuf_puts(c->wrbuf, "<nextrecid>");
717             wrbuf_xmlputs(c->wrbuf, next_r->recid);
718             wrbuf_puts(c->wrbuf, "</nextrecid>\n");
719         }
720         wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", 
721                      session_active_clients(s->psession));
722         write_metadata(c->wrbuf, service, rec->metadata, 1);
723         for (r = rec->records; r; r = r->next)
724             write_subrecord(r, c->wrbuf, service, 1);
725         wrbuf_puts(c->wrbuf, "</record>\n");
726         rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
727         http_send_response(c);
728     }
729 }
730
731 static void cmd_record_ready(void *data)
732 {
733     struct http_channel *c = (struct http_channel *) data;
734
735     cmd_record(c);
736 }
737
738 static void show_records(struct http_channel *c, int active)
739 {
740     struct http_request *rq = c->request;
741     struct http_response *rs = c->response;
742     struct http_session *s = locate_session(rq, rs);
743     struct record_cluster **rl;
744     struct reclist_sortparms *sp;
745     const char *start = http_argbyname(rq, "start");
746     const char *num = http_argbyname(rq, "num");
747     const char *sort = http_argbyname(rq, "sort");
748     int startn = 0;
749     int numn = 20;
750     int total;
751     Odr_int total_hits;
752     int i;
753
754     if (!s)
755         return;
756
757     // We haven't counted clients yet if we're called on a block release
758     if (active < 0)
759         active = session_active_clients(s->psession);
760
761     if (start)
762         startn = atoi(start);
763     if (num)
764         numn = atoi(num);
765     if (!sort)
766         sort = "relevance";
767     if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
768     {
769         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
770         return;
771     }
772
773     rl = show(s->psession, sp, startn, &numn, &total, &total_hits, c->nmem);
774
775     wrbuf_rewind(c->wrbuf);
776     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<show>\n<status>OK</status>\n");
777     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
778     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
779     wrbuf_printf(c->wrbuf, "<total>" ODR_INT_PRINTF "</total>\n", total_hits);
780     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
781     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
782
783     for (i = 0; i < numn; i++)
784     {
785         int ccount;
786         struct record *p;
787         struct record_cluster *rec = rl[i];
788         struct conf_service *service = s->psession->service;
789
790         wrbuf_puts(c->wrbuf, "<hit>\n");
791         write_metadata(c->wrbuf, service, rec->metadata, 0);
792         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
793             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
794         if (ccount > 1)
795             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
796         if (strstr(sort, "relevance"))
797             wrbuf_printf(c->wrbuf, "<relevance>%d</relevance>\n", rec->relevance);
798         wrbuf_puts(c->wrbuf, "<recid>");
799         wrbuf_xmlputs(c->wrbuf, rec->recid);
800         wrbuf_puts(c->wrbuf, "</recid>\n");
801         wrbuf_puts(c->wrbuf, "</hit>\n");
802     }
803
804     wrbuf_puts(c->wrbuf, "</show>\n");
805     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
806     http_send_response(c);
807 }
808
809 static void show_records_ready(void *data)
810 {
811     struct http_channel *c = (struct http_channel *) data;
812
813     show_records(c, -1);
814 }
815
816 static void cmd_show(struct http_channel *c)
817 {
818     struct http_request *rq = c->request;
819     struct http_response *rs = c->response;
820     struct http_session *s = locate_session(rq, rs);
821     const char *block = http_argbyname(rq, "block");
822     int status;
823
824     if (!s)
825         return;
826
827     status = session_active_clients(s->psession);
828
829     if (block)
830     {
831         if (status && reclist_get_num_records(s->psession->reclist) == 0)
832         {
833             // if there is already a watch/block. we do not block this one
834             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
835                                   show_records_ready, c, c) != 0)
836             {
837                 yaz_log(YLOG_DEBUG, "Blocking on cmd_show");
838             }
839             return;
840         }
841     }
842
843     show_records(c, status);
844 }
845
846 static void cmd_ping(struct http_channel *c)
847 {
848     struct http_request *rq = c->request;
849     struct http_response *rs = c->response;
850     struct http_session *s = locate_session(rq, rs);
851     if (!s)
852         return;
853     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<ping><status>OK</status></ping>";
854     http_send_response(c);
855 }
856
857 static int utf_8_valid(const char *str)
858 {
859     yaz_iconv_t cd = yaz_iconv_open("utf-8", "utf-8");
860     if (cd)
861     {
862         /* check that query is UTF-8 encoded */
863         char *inbuf = (char *) str; /* we know iconv does not alter this */
864         size_t inbytesleft = strlen(inbuf);
865
866         size_t outbytesleft = strlen(inbuf) + 10;
867         char *out = xmalloc(outbytesleft);
868         char *outbuf = out;
869         size_t r = yaz_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
870
871         /* if OK, try flushing the rest  */
872         if (r != (size_t) (-1))
873             r = yaz_iconv(cd, 0, 0, &outbuf, &outbytesleft);
874         yaz_iconv_close(cd);
875         xfree(out);
876         if (r == (size_t) (-1))
877             return 0;
878     }
879     return 1;
880 }
881
882 static void cmd_search(struct http_channel *c)
883 {
884     struct http_request *rq = c->request;
885     struct http_response *rs = c->response;
886     struct http_session *s = locate_session(rq, rs);
887     const char *query = http_argbyname(rq, "query");
888     const char *filter = http_argbyname(rq, "filter");
889     const char *maxrecs = http_argbyname(rq, "maxrecs");
890     const char *startrecs = http_argbyname(rq, "startrecs");
891     enum pazpar2_error_code code;
892     const char *addinfo = 0;
893
894     if (!s)
895         return;
896     if (!query)
897     {
898         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
899         return;
900     }
901     if (!utf_8_valid(query))
902     {
903         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
904         return;
905     }
906     code = search(s->psession, query, startrecs, maxrecs, filter, &addinfo);
907     if (code)
908     {
909         error(rs, code, addinfo);
910         return;
911     }
912     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<search><status>OK</status></search>";
913     http_send_response(c);
914 }
915
916
917 static void cmd_stat(struct http_channel *c)
918 {
919     struct http_request *rq = c->request;
920     struct http_response *rs = c->response;
921     struct http_session *s = locate_session(rq, rs);
922     struct statistics stat;
923     int clients;
924
925     float progress = 0;
926
927     if (!s)
928         return;
929
930     clients = session_active_clients(s->psession);
931     statistics(s->psession, &stat);
932
933     if (stat.num_clients > 0) {
934         progress = (stat.num_clients  - clients) / (float)stat.num_clients;
935     }
936
937     wrbuf_rewind(c->wrbuf);
938     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<stat>");
939     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
940     wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", stat.num_hits);
941     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
942     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
943     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
944     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
945     wrbuf_printf(c->wrbuf, "<working>%d</working>\n", stat.num_working);
946     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
947     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
948     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
949     wrbuf_printf(c->wrbuf, "<progress>%.2f</progress>\n", progress);
950     wrbuf_puts(c->wrbuf, "</stat>");
951     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
952     http_send_response(c);
953 }
954
955 static void cmd_info(struct http_channel *c)
956 {
957     char yaz_version_str[20];
958     struct http_response *rs = c->response;
959
960     wrbuf_rewind(c->wrbuf);
961     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<info>\n");
962     wrbuf_puts(c->wrbuf, " <version>\n");
963     wrbuf_puts(c->wrbuf, "<pazpar2");
964 #ifdef PAZPAR2_VERSION_SHA1
965     wrbuf_printf(c->wrbuf, " sha1=\"%s\"", PAZPAR2_VERSION_SHA1);
966 #endif
967     wrbuf_puts(c->wrbuf, ">");
968     wrbuf_xmlputs(c->wrbuf, VERSION);
969     wrbuf_puts(c->wrbuf, "</pazpar2>");
970
971
972     yaz_version(yaz_version_str, 0);
973     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
974     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
975     wrbuf_puts(c->wrbuf, "\">");
976     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
977     wrbuf_puts(c->wrbuf, "</yaz>\n");
978
979     wrbuf_puts(c->wrbuf, " </version>\n");
980     
981     wrbuf_puts(c->wrbuf, "</info>");
982     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
983     http_send_response(c);
984 }
985
986 struct {
987     char *name;
988     void (*fun)(struct http_channel *c);
989 } commands[] = {
990     { "init", cmd_init },
991     { "settings", cmd_settings },
992     { "stat", cmd_stat },
993     { "bytarget", cmd_bytarget },
994     { "show", cmd_show },
995     { "search", cmd_search },
996     { "termlist", cmd_termlist },
997     { "exit", cmd_exit },
998     { "ping", cmd_ping },
999     { "record", cmd_record },
1000     { "info", cmd_info },
1001     {0,0}
1002 };
1003
1004 void http_command(struct http_channel *c)
1005 {
1006     const char *command = http_argbyname(c->request, "command");
1007     struct http_response *rs = http_create_response(c);
1008     int i;
1009
1010     c->response = rs;
1011
1012     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
1013     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
1014
1015     if (!command)
1016     {
1017         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
1018         return;
1019     }
1020     for (i = 0; commands[i].name; i++)
1021         if (!strcmp(commands[i].name, command))
1022         {
1023             (*commands[i].fun)(c);
1024             break;
1025         }
1026     if (!commands[i].name)
1027         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
1028
1029     return;
1030 }
1031
1032 /*
1033  * Local variables:
1034  * c-basic-offset: 4
1035  * c-file-style: "Stroustrup"
1036  * indent-tabs-mode: nil
1037  * End:
1038  * vim: shiftwidth=4 tabstop=8 expandtab
1039  */
1040