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