Allows definition/override of pz:cclmap:* settings via settings ws.
[pazpar2-moved-to-github.git] / src / http_command.c
1 /* $Id: http_command.c,v 1.40 2007-04-19 16:07:20 adam Exp $
2    Copyright (c) 2006-2007, Index Data.
3
4 This file is part of Pazpar2.
5
6 Pazpar2 is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
9 version.
10
11 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Pazpar2; see the file LICENSE.  If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19 02111-1307, USA.
20  */
21
22 /*
23  * $Id: http_command.c,v 1.40 2007-04-19 16:07:20 adam Exp $
24  */
25
26 #include <stdio.h>
27 #include <sys/types.h>
28 #include <sys/uio.h>
29 #include <unistd.h>
30 #include <stdlib.h>
31 #include <strings.h>
32 #include <ctype.h>
33 #include <sys/time.h>
34
35 #if HAVE_CONFIG_H
36 #include <cconfig.h>
37 #endif
38
39 #include <yaz/yaz-util.h>
40
41 #include "config.h"
42 #include "util.h"
43 #include "eventl.h"
44 #include "pazpar2.h"
45 #include "http.h"
46 #include "http_command.h"
47 #include "settings.h"
48
49 // Update this when the protocol changes
50 #define PAZPAR2_PROTOCOL_VERSION "1"
51
52 struct http_session {
53     IOCHAN timeout_iochan;     // NOTE: This is NOT associated with a socket
54     struct session *psession;
55     unsigned int session_id;
56     int timestamp;
57     NMEM nmem;
58     struct http_session *next;
59 };
60
61 static struct http_session *session_list = 0;
62
63 void http_session_destroy(struct http_session *s);
64
65 static void session_timeout(IOCHAN i, int event)
66 {
67     struct http_session *s = iochan_getdata(i);
68     http_session_destroy(s);
69 }
70
71 struct http_session *http_session_create()
72 {
73     NMEM nmem = nmem_create();
74     struct http_session *r = nmem_malloc(nmem, sizeof(*r));
75
76     r->psession = new_session(nmem);
77     r->session_id = 0;
78     r->timestamp = 0;
79     r->nmem = nmem;
80     r->next = session_list;
81     session_list = r;
82     r->timeout_iochan = iochan_create(-1, session_timeout, 0);
83     iochan_setdata(r->timeout_iochan, r);
84     iochan_settimeout(r->timeout_iochan, global_parameters.session_timeout);
85
86     pazpar2_add_channel(r->timeout_iochan);
87     return r;
88 }
89
90 void http_session_destroy(struct http_session *s)
91 {
92     struct http_session **p;
93
94     for (p = &session_list; *p; p = &(*p)->next)
95         if (*p == s)
96         {
97             *p = (*p)->next;
98             break;
99         }
100     iochan_destroy(s->timeout_iochan);
101     destroy_session(s->psession);
102     nmem_destroy(s->nmem);
103 }
104
105 static void error(struct http_response *rs, char *code, char *msg, char *txt)
106 {
107     struct http_channel *c = rs->channel;
108     char tmp[1024];
109
110     if (!txt)
111         txt = msg;
112     rs->msg = nmem_strdup(c->nmem, msg);
113     strcpy(rs->code, code);
114     sprintf(tmp, "<error code=\"general\">%s</error>", txt);
115     rs->payload = nmem_strdup(c->nmem, tmp);
116     http_send_response(c);
117 }
118
119 unsigned int make_sessionid()
120 {
121     struct timeval t;
122     unsigned int res;
123     static int seq = 0;
124
125     seq++;
126     if (gettimeofday(&t, 0) < 0)
127         abort();
128     res = t.tv_sec;
129     res = ((res << 8) | (seq & 0xff)) & ((1U << 31) - 1);
130     return res;
131 }
132
133 static struct http_session *locate_session(struct http_request *rq, struct http_response *rs)
134 {
135     struct http_session *p;
136     char *session = http_argbyname(rq, "session");
137     unsigned int id;
138
139     if (!session)
140     {
141         error(rs, "417", "Must supply session", 0);
142         return 0;
143     }
144     id = atoi(session);
145     for (p = session_list; p; p = p->next)
146         if (id == p->session_id)
147         {
148             iochan_activity(p->timeout_iochan);
149             return p;
150         }
151     error(rs, "417", "Session does not exist, or it has expired", 0);
152     return 0;
153 }
154
155 // Decode settings parameters and apply to session
156 // Syntax: setting[target]=value
157 static int process_settings(struct session *se, struct http_request *rq,
158         struct http_response *rs)
159 {
160     struct http_argument *a;
161
162     for (a = rq->arguments; a; a = a->next)
163         if (strchr(a->name, '['))
164         {
165             char **res;
166             int num;
167             char *dbname;
168             char *setting;
169
170             // Nmem_strsplit *rules*!!!
171             nmem_strsplit(se->session_nmem, "[]", a->name, &res, &num);
172             if (num != 2)
173             {
174                 error(rs, "417", "Malformed setting argument", 0);
175                 yaz_log(YLOG_WARN, "Malformed setting: %s", a->name);
176                 return -1;
177             }
178             setting = res[0];
179             dbname = res[1];
180             session_apply_setting(se, dbname, setting,
181                     nmem_strdup(se->session_nmem, a->value));
182         }
183     return 0;
184 }
185
186 static void cmd_exit(struct http_channel *c)
187 {
188     yaz_log(YLOG_WARN, "exit");
189     exit(0);
190 }
191
192 static void cmd_init(struct http_channel *c)
193 {
194     unsigned int sesid;
195     char buf[1024];
196     struct http_session *s = http_session_create();
197     struct http_response *rs = c->response;
198
199     yaz_log(YLOG_DEBUG, "HTTP Session init");
200     sesid = make_sessionid();
201     s->session_id = sesid;
202     if (process_settings(s->psession, c->request, c->response) < 0)
203         return;
204     sprintf(buf, "<init><status>OK</status><session>%u</session>"
205             "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol></init>", sesid);
206     rs->payload = nmem_strdup(c->nmem, buf);
207     http_send_response(c);
208 }
209
210 static void cmd_settings(struct http_channel *c)
211 {
212     struct http_response *rs = c->response;
213     struct http_request *rq = c->request;
214     struct http_session *s = locate_session(rq, rs);
215
216     if (!s)
217         return;
218
219     if (process_settings(s->psession, rq, rs) < 0)
220         return;
221     rs->payload = "<settings><status>OK</status></settings>";
222     http_send_response(c);
223 }
224
225 // Compares two hitsbytarget nodes by hitcount
226 static int cmp_ht(const void *p1, const void *p2)
227 {
228     const struct hitsbytarget *h1 = p1;
229     const struct hitsbytarget *h2 = p2;
230     return h2->hits - h1->hits;
231 }
232
233 // This implements functionality somewhat similar to 'bytarget', but in a termlist form
234 static void targets_termlist(WRBUF wrbuf, struct session *se, int num)
235 {
236     struct hitsbytarget *ht;
237     int count, i;
238
239     if (!(ht = hitsbytarget(se, &count)))
240         return;
241     qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
242     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
243     {
244         wrbuf_puts(wrbuf, "\n<term>\n");
245         wrbuf_printf(wrbuf, "<id>%s</id>\n", ht[i].id);
246         wrbuf_printf(wrbuf, "<name>%s</name>\n", ht[i].name);
247         wrbuf_printf(wrbuf, "<frequency>%d</frequency>\n", ht[i].hits);
248         wrbuf_printf(wrbuf, "<state>%s</state>\n", ht[i].state);
249         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
250         wrbuf_puts(wrbuf, "\n</term>\n");
251     }
252 }
253
254 static void cmd_termlist(struct http_channel *c)
255 {
256     struct http_response *rs = c->response;
257     struct http_request *rq = c->request;
258     struct http_session *s = locate_session(rq, rs);
259     struct termlist_score **p;
260     int len;
261     int i;
262     char *name = http_argbyname(rq, "name");
263     char *nums = http_argbyname(rq, "num");
264     int num = 15;
265     int status;
266
267     if (!s)
268         return;
269
270     status = session_active_clients(s->psession);
271
272     if (!name)
273         name = "subject";
274     if (strlen(name) > 255)
275         return;
276     if (nums)
277         num = atoi(nums);
278
279     wrbuf_rewind(c->wrbuf);
280
281     wrbuf_puts(c->wrbuf, "<termlist>");
282     wrbuf_printf(c->wrbuf, "\n<activeclients>%d</activeclients>", status);
283     while (*name)
284     {
285         char tname[256];
286         char *tp;
287
288         if (!(tp = strchr(name, ',')))
289             tp = name + strlen(name);
290         strncpy(tname, name, tp - name);
291         tname[tp - name] = '\0';
292
293         wrbuf_printf(c->wrbuf, "\n<list name=\"%s\">\n", tname);
294         if (!strcmp(tname, "xtargets"))
295             targets_termlist(c->wrbuf, s->psession, num);
296         else
297         {
298             p = termlist(s->psession, tname, &len);
299             if (p)
300                 for (i = 0; i < len && i < num; i++)
301                 {
302                     wrbuf_puts(c->wrbuf, "\n<term>");
303                     wrbuf_printf(c->wrbuf, "<name>%s</name>", p[i]->term);
304                     wrbuf_printf(c->wrbuf, "<frequency>%d</frequency>", p[i]->frequency);
305                     wrbuf_puts(c->wrbuf, "</term>");
306                 }
307         }
308         wrbuf_puts(c->wrbuf, "\n</list>");
309         name = tp;
310         if (*name == ',')
311             name++;
312     }
313     wrbuf_puts(c->wrbuf, "</termlist>");
314     rs->payload = nmem_strdup(rq->channel->nmem, wrbuf_cstr(c->wrbuf));
315     http_send_response(c);
316 }
317
318
319 static void cmd_bytarget(struct http_channel *c)
320 {
321     struct http_response *rs = c->response;
322     struct http_request *rq = c->request;
323     struct http_session *s = locate_session(rq, rs);
324     struct hitsbytarget *ht;
325     int count, i;
326
327     if (!s)
328         return;
329     if (!(ht = hitsbytarget(s->psession, &count)))
330     {
331         error(rs, "500", "Failed to retrieve hitcounts", 0);
332         return;
333     }
334     wrbuf_rewind(c->wrbuf);
335     wrbuf_puts(c->wrbuf, "<bytarget><status>OK</status>");
336
337     for (i = 0; i < count; i++)
338     {
339         wrbuf_puts(c->wrbuf, "\n<target>");
340         wrbuf_printf(c->wrbuf, "<id>%s</id>\n", ht[i].id);
341         wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", ht[i].hits);
342         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
343         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
344         wrbuf_printf(c->wrbuf, "<state>%s</state>\n", ht[i].state);
345         wrbuf_puts(c->wrbuf, "</target>");
346     }
347
348     wrbuf_puts(c->wrbuf, "</bytarget>");
349     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
350     http_send_response(c);
351 }
352
353 static void write_metadata(WRBUF w, struct conf_service *service,
354         struct record_metadata **ml, int full)
355 {
356     int imeta;
357
358     for (imeta = 0; imeta < service->num_metadata; imeta++)
359     {
360         struct conf_metadata *cmd = &service->metadata[imeta];
361         struct record_metadata *md;
362         if (!cmd->brief && !full)
363             continue;
364         for (md = ml[imeta]; md; md = md->next)
365         {
366             wrbuf_printf(w, "\n<md-%s>", cmd->name);
367             switch (cmd->type)
368             {
369                 case Metadata_type_generic:
370                     wrbuf_puts(w, md->data.text);
371                     break;
372                 case Metadata_type_year:
373                     wrbuf_printf(w, "%d", md->data.number.min);
374                     if (md->data.number.min != md->data.number.max)
375                         wrbuf_printf(w, "-%d", md->data.number.max);
376                     break;
377                 default:
378                     wrbuf_puts(w, "[can't represent]");
379             }
380             wrbuf_printf(w, "</md-%s>", cmd->name);
381         }
382     }
383 }
384
385 static void write_subrecord(struct record *r, WRBUF w,
386         struct conf_service *service, int show_details)
387 {
388     char *name = session_setting_oneval(r->client->database, PZ_NAME);
389
390     wrbuf_printf(w, "<location id=\"%s\" name=\"%s\">",
391             r->client->database->database->url,
392             *name ? name : "Unknown");
393     if (show_details)
394         write_metadata(w, service, r->metadata, 1);
395     wrbuf_puts(w, "</location>\n");
396 }
397
398 static void cmd_record(struct http_channel *c)
399 {
400     struct http_response *rs = c->response;
401     struct http_request *rq = c->request;
402     struct http_session *s = locate_session(rq, rs);
403     struct record_cluster *rec;
404     struct record *r;
405     struct conf_service *service = global_parameters.server->service;
406     char *idstr = http_argbyname(rq, "id");
407     int id;
408
409     if (!s)
410         return;
411     if (!idstr)
412     {
413         error(rs, "417", "Must supply id", 0);
414         return;
415     }
416     wrbuf_rewind(c->wrbuf);
417     id = atoi(idstr);
418     if (!(rec = show_single(s->psession, id)))
419     {
420         error(rs, "500", "Record missing", 0);
421         return;
422     }
423     wrbuf_puts(c->wrbuf, "<record>\n");
424     wrbuf_printf(c->wrbuf, "<recid>%d</recid>", rec->recid);
425     write_metadata(c->wrbuf, service, rec->metadata, 1);
426     for (r = rec->records; r; r = r->next)
427         write_subrecord(r, c->wrbuf, service, 1);
428     wrbuf_puts(c->wrbuf, "</record>\n");
429     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
430     http_send_response(c);
431 }
432
433 static void show_records(struct http_channel *c, int active)
434 {
435     struct http_request *rq = c->request;
436     struct http_response *rs = c->response;
437     struct http_session *s = locate_session(rq, rs);
438     struct record_cluster **rl;
439     struct reclist_sortparms *sp;
440     char *start = http_argbyname(rq, "start");
441     char *num = http_argbyname(rq, "num");
442     char *sort = http_argbyname(rq, "sort");
443     int startn = 0;
444     int numn = 20;
445     int total;
446     int total_hits;
447     int i;
448
449     if (!s)
450         return;
451
452     // We haven't counted clients yet if we're called on a block release
453     if (active < 0)
454         active = session_active_clients(s->psession);
455
456     if (start)
457         startn = atoi(start);
458     if (num)
459         numn = atoi(num);
460     if (!sort)
461         sort = "relevance";
462     if (!(sp = reclist_parse_sortparms(c->nmem, sort)))
463     {
464         error(rs, "500", "Bad sort parameters", 0);
465         return;
466     }
467
468     rl = show(s->psession, sp, startn, &numn, &total, &total_hits, c->nmem);
469
470     wrbuf_rewind(c->wrbuf);
471     wrbuf_puts(c->wrbuf, "<show>\n<status>OK</status>\n");
472     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
473     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
474     wrbuf_printf(c->wrbuf, "<total>%d</total>\n", total_hits);
475     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
476     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
477
478     for (i = 0; i < numn; i++)
479     {
480         int ccount;
481         struct record *p;
482         struct record_cluster *rec = rl[i];
483         struct conf_service *service = global_parameters.server->service;
484
485         wrbuf_puts(c->wrbuf, "<hit>\n");
486         write_metadata(c->wrbuf, service, rec->metadata, 0);
487         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
488             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
489         if (ccount > 1)
490             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
491         wrbuf_printf(c->wrbuf, "<recid>%d</recid>\n", rec->recid);
492         wrbuf_puts(c->wrbuf, "</hit>\n");
493     }
494
495     wrbuf_puts(c->wrbuf, "</show>\n");
496     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
497     http_send_response(c);
498 }
499
500 static void show_records_ready(void *data)
501 {
502     struct http_channel *c = (struct http_channel *) data;
503
504     show_records(c, -1);
505 }
506
507 static void cmd_show(struct http_channel *c)
508 {
509     struct http_request *rq = c->request;
510     struct http_response *rs = c->response;
511     struct http_session *s = locate_session(rq, rs);
512     char *block = http_argbyname(rq, "block");
513     int status;
514
515     if (!s)
516         return;
517
518     status = session_active_clients(s->psession);
519
520     if (block)
521     {
522         if (status && (!s->psession->reclist || !s->psession->reclist->num_records))
523         {
524             session_set_watch(s->psession, SESSION_WATCH_RECORDS, show_records_ready, c);
525             yaz_log(YLOG_DEBUG, "Blocking on cmd_show");
526             return;
527         }
528     }
529
530     show_records(c, status);
531 }
532
533 static void cmd_ping(struct http_channel *c)
534 {
535     struct http_request *rq = c->request;
536     struct http_response *rs = c->response;
537     struct http_session *s = locate_session(rq, rs);
538     if (!s)
539         return;
540     rs->payload = "<ping><status>OK</status></ping>";
541     http_send_response(c);
542 }
543
544 static void cmd_search(struct http_channel *c)
545 {
546     struct http_request *rq = c->request;
547     struct http_response *rs = c->response;
548     struct http_session *s = locate_session(rq, rs);
549     char *query = http_argbyname(rq, "query");
550     char *filter = http_argbyname(rq, "filter");
551     char *res;
552
553     if (!s)
554         return;
555     if (!query)
556     {
557         error(rs, "417", "Must supply query", 0);
558         return;
559     }
560     res = search(s->psession, query, filter);
561     if (res)
562     {
563         error(rs, "417", res, res);
564         return;
565     }
566     rs->payload = "<search><status>OK</status></search>";
567     http_send_response(c);
568 }
569
570
571 static void cmd_stat(struct http_channel *c)
572 {
573     struct http_request *rq = c->request;
574     struct http_response *rs = c->response;
575     struct http_session *s = locate_session(rq, rs);
576     struct statistics stat;
577     int clients;
578
579     if (!s)
580         return;
581
582     clients = session_active_clients(s->psession);
583     statistics(s->psession, &stat);
584
585     wrbuf_rewind(c->wrbuf);
586     wrbuf_puts(c->wrbuf, "<stat>");
587     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
588     wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", stat.num_hits);
589     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
590     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
591     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
592     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
593     wrbuf_printf(c->wrbuf, "<initializing>%d</initializing>\n", stat.num_initializing);
594     wrbuf_printf(c->wrbuf, "<searching>%d</searching>\n", stat.num_searching);
595     wrbuf_printf(c->wrbuf, "<presenting>%d</presenting>\n", stat.num_presenting);
596     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
597     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
598     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
599     wrbuf_puts(c->wrbuf, "</stat>");
600     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
601     http_send_response(c);
602 }
603
604 static void cmd_info(struct http_channel *c)
605 {
606     char yaz_version_str[20];
607     struct http_response *rs = c->response;
608
609     wrbuf_rewind(c->wrbuf);
610     wrbuf_puts(c->wrbuf, "<info>\n");
611     wrbuf_printf(c->wrbuf, " <version>\n");
612     wrbuf_printf(c->wrbuf, "  <pazpar2>%s</pazpar2>\n", VERSION);
613
614     yaz_version(yaz_version_str, 0);
615     wrbuf_printf(c->wrbuf, "  <yaz compiled=\"%s\">%s</yaz>\n",
616                  YAZ_VERSION, yaz_version_str);
617     wrbuf_printf(c->wrbuf, " </version>\n");
618     
619     wrbuf_puts(c->wrbuf, "</info>");
620     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
621     http_send_response(c);
622 }
623
624 struct {
625     char *name;
626     void (*fun)(struct http_channel *c);
627 } commands[] = {
628     { "init", cmd_init },
629     { "settings", cmd_settings },
630     { "stat", cmd_stat },
631     { "bytarget", cmd_bytarget },
632     { "show", cmd_show },
633     { "search", cmd_search },
634     { "termlist", cmd_termlist },
635     { "exit", cmd_exit },
636     { "ping", cmd_ping },
637     { "record", cmd_record },
638     { "info", cmd_info },
639     {0,0}
640 };
641
642 void http_command(struct http_channel *c)
643 {
644     char *command = http_argbyname(c->request, "command");
645     struct http_response *rs = http_create_response(c);
646     int i;
647
648     c->response = rs;
649
650     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
651     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
652
653     if (!command)
654     {
655         error(rs, "417", "Must supply command", 0);
656         return;
657     }
658     for (i = 0; commands[i].name; i++)
659         if (!strcmp(commands[i].name, command))
660         {
661             (*commands[i].fun)(c);
662             break;
663         }
664     if (!commands[i].name)
665         error(rs, "417", "Unknown command", 0);
666
667     return;
668 }
669
670 /*
671  * Local variables:
672  * c-basic-offset: 4
673  * indent-tabs-mode: nil
674  * End:
675  * vim: shiftwidth=4 tabstop=8 expandtab
676  */