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