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