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