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