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