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