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