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