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