Remove targets with hits < 1 or errors from target termlist
[pazpar2-moved-to-github.git] / src / http_command.c
1 /*
2  * $Id: http_command.c,v 1.24 2007-01-17 15:27:34 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, "<name>%s</name>\n", ht[i].id);
172         wrbuf_printf(wrbuf, "<frequency>%d</frequency>\n", ht[i].hits);
173         wrbuf_printf(wrbuf, "<state>%s</state>\n", ht[i].state);
174         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
175         wrbuf_puts(wrbuf, "\n</term>\n");
176     }
177 }
178
179 static void cmd_termlist(struct http_channel *c)
180 {
181     struct http_response *rs = c->response;
182     struct http_request *rq = c->request;
183     struct http_session *s = locate_session(rq, rs);
184     struct termlist_score **p;
185     int len;
186     int i;
187     char *name = http_argbyname(rq, "name");
188     char *nums = http_argbyname(rq, "num");
189     int num = 15;
190     int status;
191
192     if (!s)
193         return;
194
195     status = session_active_clients(s->psession);
196
197     if (!name)
198         name = "subject";
199     if (strlen(name) > 255)
200         return;
201     if (nums)
202         num = atoi(nums);
203
204     wrbuf_rewind(c->wrbuf);
205
206     wrbuf_puts(c->wrbuf, "<termlist>");
207     wrbuf_printf(c->wrbuf, "\n<activeclients>%d</activeclients>", status);
208     while (*name)
209     {
210         char tname[256];
211         char *tp;
212
213         if (!(tp = strchr(name, ',')))
214             tp = name + strlen(name);
215         strncpy(tname, name, tp - name);
216         tname[tp - name] = '\0';
217
218         wrbuf_printf(c->wrbuf, "\n<list name=\"%s\">\n", tname);
219         if (!strcmp(tname, "xtargets"))
220             targets_termlist(c->wrbuf, s->psession, num);
221         else
222         {
223             p = termlist(s->psession, tname, &len);
224             if (p)
225                 for (i = 0; i < len && i < num; i++)
226                 {
227                     wrbuf_puts(c->wrbuf, "\n<term>");
228                     wrbuf_printf(c->wrbuf, "<name>%s</name>", p[i]->term);
229                     wrbuf_printf(c->wrbuf, "<frequency>%d</frequency>", p[i]->frequency);
230                     wrbuf_puts(c->wrbuf, "</term>");
231                 }
232         }
233         wrbuf_puts(c->wrbuf, "\n</list>");
234         name = tp;
235         if (*name == ',')
236             name++;
237     }
238     wrbuf_puts(c->wrbuf, "</termlist>");
239     rs->payload = nmem_strdup(rq->channel->nmem, wrbuf_buf(c->wrbuf));
240     http_send_response(c);
241 }
242
243
244 static void cmd_bytarget(struct http_channel *c)
245 {
246     struct http_response *rs = c->response;
247     struct http_request *rq = c->request;
248     struct http_session *s = locate_session(rq, rs);
249     struct hitsbytarget *ht;
250     int count, i;
251
252     if (!s)
253         return;
254     if (!(ht = hitsbytarget(s->psession, &count)))
255     {
256         error(rs, "500", "Failed to retrieve hitcounts", 0);
257         return;
258     }
259     wrbuf_rewind(c->wrbuf);
260     wrbuf_puts(c->wrbuf, "<bytarget><status>OK</status>");
261
262     for (i = 0; i < count; i++)
263     {
264         wrbuf_puts(c->wrbuf, "\n<target>");
265         wrbuf_printf(c->wrbuf, "<id>%s</id>\n", ht[i].id);
266         wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", ht[i].hits);
267         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
268         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
269         wrbuf_printf(c->wrbuf, "<state>%s</state>\n", ht[i].state);
270         wrbuf_puts(c->wrbuf, "</target>");
271     }
272
273     wrbuf_puts(c->wrbuf, "</bytarget>");
274     rs->payload = nmem_strdup(c->nmem, wrbuf_buf(c->wrbuf));
275     http_send_response(c);
276 }
277
278 static void write_metadata(WRBUF w, struct conf_service *service,
279         struct record_metadata **ml, int full)
280 {
281     int imeta;
282
283     for (imeta = 0; imeta < service->num_metadata; imeta++)
284     {
285         struct conf_metadata *cmd = &service->metadata[imeta];
286         struct record_metadata *md;
287         if (!cmd->brief && !full)
288             continue;
289         for (md = ml[imeta]; md; md = md->next)
290         {
291             wrbuf_printf(w, "<md-%s>", cmd->name);
292             switch (cmd->type)
293             {
294                 case Metadata_type_generic:
295                     wrbuf_puts(w, md->data.text);
296                     break;
297                 case Metadata_type_year:
298                     wrbuf_printf(w, "%d", md->data.number.min);
299                     if (md->data.number.min != md->data.number.max)
300                         wrbuf_printf(w, "-%d", md->data.number.max);
301                     break;
302                 default:
303                     wrbuf_puts(w, "[can't represent]");
304             }
305             wrbuf_printf(w, "</md-%s>", cmd->name);
306         }
307     }
308 }
309
310 static void cmd_record(struct http_channel *c)
311 {
312     struct http_response *rs = c->response;
313     struct http_request *rq = c->request;
314     struct http_session *s = locate_session(rq, rs);
315     struct record_cluster *rec;
316     struct conf_service *service = global_parameters.server->service;
317     char *idstr = http_argbyname(rq, "id");
318     int id;
319
320     if (!s)
321         return;
322     if (!idstr)
323     {
324         error(rs, "417", "Must supply id", 0);
325         return;
326     }
327     wrbuf_rewind(c->wrbuf);
328     id = atoi(idstr);
329     if (!(rec = show_single(s->psession, id)))
330     {
331         error(rs, "500", "Record missing", 0);
332         return;
333     }
334     wrbuf_puts(c->wrbuf, "<record>\n");
335     wrbuf_printf(c->wrbuf, "<recid>%d</recid>", rec->recid);
336     write_metadata(c->wrbuf, service, rec->metadata, 1);
337     wrbuf_puts(c->wrbuf, "</record>\n");
338     rs->payload = nmem_strdup(c->nmem, wrbuf_buf(c->wrbuf));
339     http_send_response(c);
340 }
341
342 static void show_records(struct http_channel *c, int active)
343 {
344     struct http_request *rq = c->request;
345     struct http_response *rs = c->response;
346     struct http_session *s = locate_session(rq, rs);
347     struct record_cluster **rl;
348     struct reclist_sortparms *sp;
349     char *start = http_argbyname(rq, "start");
350     char *num = http_argbyname(rq, "num");
351     char *sort = http_argbyname(rq, "sort");
352     int startn = 0;
353     int numn = 20;
354     int total;
355     int total_hits;
356     int i;
357
358     if (!s)
359         return;
360
361     // We haven't counted clients yet if we're called on a block release
362     if (active < 0)
363         active = session_active_clients(s->psession);
364
365     if (start)
366         startn = atoi(start);
367     if (num)
368         numn = atoi(num);
369     if (!sort)
370         sort = "relevance";
371     if (!(sp = reclist_parse_sortparms(c->nmem, sort)))
372     {
373         error(rs, "500", "Bad sort parameters", 0);
374         return;
375     }
376
377     rl = show(s->psession, sp, startn, &numn, &total, &total_hits, c->nmem);
378
379     wrbuf_rewind(c->wrbuf);
380     wrbuf_puts(c->wrbuf, "<show>\n<status>OK</status>\n");
381     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
382     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
383     wrbuf_printf(c->wrbuf, "<total>%d</total>\n", total_hits);
384     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
385     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
386
387     for (i = 0; i < numn; i++)
388     {
389         int ccount;
390         struct record *p;
391         struct record_cluster *rec = rl[i];
392         struct conf_service *service = global_parameters.server->service;
393
394         wrbuf_puts(c->wrbuf, "<hit>\n");
395         write_metadata(c->wrbuf, service, rec->metadata, 0);
396         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
397             ;
398         if (ccount > 1)
399             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
400         wrbuf_printf(c->wrbuf, "<recid>%d</recid>\n", rec->recid);
401         wrbuf_puts(c->wrbuf, "</hit>\n");
402     }
403
404     wrbuf_puts(c->wrbuf, "</show>\n");
405     rs->payload = nmem_strdup(c->nmem, wrbuf_buf(c->wrbuf));
406     http_send_response(c);
407 }
408
409 static void show_records_ready(void *data)
410 {
411     struct http_channel *c = (struct http_channel *) data;
412
413     show_records(c, -1);
414 }
415
416 static void cmd_show(struct http_channel *c)
417 {
418     struct http_request *rq = c->request;
419     struct http_response *rs = c->response;
420     struct http_session *s = locate_session(rq, rs);
421     char *block = http_argbyname(rq, "block");
422     int status;
423
424     if (!s)
425         return;
426
427     status = session_active_clients(s->psession);
428
429     if (block)
430     {
431         if (status && (!s->psession->reclist || !s->psession->reclist->num_records))
432         {
433             session_set_watch(s->psession, SESSION_WATCH_RECORDS, show_records_ready, c);
434             yaz_log(YLOG_DEBUG, "Blocking on cmd_show");
435             return;
436         }
437     }
438
439     show_records(c, status);
440 }
441
442 static void cmd_ping(struct http_channel *c)
443 {
444     struct http_request *rq = c->request;
445     struct http_response *rs = c->response;
446     struct http_session *s = locate_session(rq, rs);
447     if (!s)
448         return;
449     rs->payload = "<ping><status>OK</status></ping>";
450     http_send_response(c);
451 }
452
453 static void cmd_search(struct http_channel *c)
454 {
455     struct http_request *rq = c->request;
456     struct http_response *rs = c->response;
457     struct http_session *s = locate_session(rq, rs);
458     char *query = http_argbyname(rq, "query");
459     char *res;
460
461     if (!s)
462         return;
463     if (!query)
464     {
465         error(rs, "417", "Must supply query", 0);
466         return;
467     }
468     res = search(s->psession, query);
469     if (res)
470     {
471         error(rs, "417", res, res);
472         return;
473     }
474     rs->payload = "<search><status>OK</status></search>";
475     http_send_response(c);
476 }
477
478
479 static void cmd_stat(struct http_channel *c)
480 {
481     struct http_request *rq = c->request;
482     struct http_response *rs = c->response;
483     struct http_session *s = locate_session(rq, rs);
484     struct statistics stat;
485     int clients;
486
487     if (!s)
488         return;
489
490     clients = session_active_clients(s->psession);
491     statistics(s->psession, &stat);
492
493     wrbuf_rewind(c->wrbuf);
494     wrbuf_puts(c->wrbuf, "<stat>");
495     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
496     wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", stat.num_hits);
497     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
498     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
499     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
500     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
501     wrbuf_printf(c->wrbuf, "<initializing>%d</initializing>\n", stat.num_initializing);
502     wrbuf_printf(c->wrbuf, "<searching>%d</searching>\n", stat.num_searching);
503     wrbuf_printf(c->wrbuf, "<presenting>%d</presenting>\n", stat.num_presenting);
504     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
505     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
506     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
507     wrbuf_puts(c->wrbuf, "</stat>");
508     rs->payload = nmem_strdup(c->nmem, wrbuf_buf(c->wrbuf));
509     http_send_response(c);
510 }
511
512 static void cmd_info(struct http_channel *c)
513 {
514     char yaz_version_str[20];
515     struct http_response *rs = c->response;
516
517     wrbuf_rewind(c->wrbuf);
518     wrbuf_puts(c->wrbuf, "<info>\n");
519     wrbuf_printf(c->wrbuf, " <version>\n");
520     wrbuf_printf(c->wrbuf, "  <pazpar2>%s</pazpar2>\n", VERSION);
521
522     yaz_version(yaz_version_str, 0);
523     wrbuf_printf(c->wrbuf, "  <yaz compiled=\"%s\">%s</yaz>\n",
524                  YAZ_VERSION, yaz_version_str);
525     wrbuf_printf(c->wrbuf, " </version>\n");
526     
527     wrbuf_puts(c->wrbuf, "</info>");
528     rs->payload = nmem_strdup(c->nmem, wrbuf_buf(c->wrbuf));
529     http_send_response(c);
530 }
531
532 struct {
533     char *name;
534     void (*fun)(struct http_channel *c);
535 } commands[] = {
536     { "init", cmd_init },
537     { "stat", cmd_stat },
538     { "bytarget", cmd_bytarget },
539     { "show", cmd_show },
540     { "search", cmd_search },
541     { "termlist", cmd_termlist },
542     { "exit", cmd_exit },
543     { "ping", cmd_ping },
544     { "record", cmd_record },
545     { "info", cmd_info },
546     {0,0}
547 };
548
549 void http_command(struct http_channel *c)
550 {
551     char *command = http_argbyname(c->request, "command");
552     struct http_response *rs = http_create_response(c);
553     int i;
554
555     c->response = rs;
556
557     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
558     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
559
560     if (!command)
561     {
562         error(rs, "417", "Must supply command", 0);
563         return;
564     }
565     for (i = 0; commands[i].name; i++)
566         if (!strcmp(commands[i].name, command))
567         {
568             (*commands[i].fun)(c);
569             break;
570         }
571     if (!commands[i].name)
572         error(rs, "417", "Unknown command", 0);
573
574     return;
575 }
576
577 /*
578  * Local variables:
579  * c-basic-offset: 4
580  * indent-tabs-mode: nil
581  * End:
582  * vim: shiftwidth=4 tabstop=8 expandtab
583  */