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