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