6a0a7b485efbbc9e068764f1a4dfae6e5a65c605
[pazpar2-moved-to-github.git] / src / http_command.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2010 Index Data
3
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 #if HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23 #include <stdio.h>
24 #include <sys/types.h>
25 #if HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #include <stdlib.h>
29 #include <string.h>
30 #if HAVE_SYS_TIME_H
31 #include <sys/time.h>
32 #endif
33 #include <yaz/snprintf.h>
34 #include <yaz/yaz-util.h>
35
36 #include "ppmutex.h"
37 #include "eventl.h"
38 #include "parameters.h"
39 #include "session.h"
40 #include "http.h"
41 #include "settings.h"
42 #include "client.h"
43
44 // Update this when the protocol changes
45 #define PAZPAR2_PROTOCOL_VERSION "1"
46
47 #define HTTP_COMMAND_RESPONSE_PREFIX "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
48
49 struct http_session {
50     IOCHAN timeout_iochan;     // NOTE: This is NOT associated with a socket
51     struct session *psession;
52     unsigned int session_id;
53     int timestamp;
54     int destroy_counter;
55     int activity_counter;
56     NMEM nmem;
57     http_sessions_t http_sessions;
58     struct http_session *next;
59 };
60
61 struct http_sessions {
62     struct http_session *session_list;
63     YAZ_MUTEX mutex;
64 };
65
66 http_sessions_t http_sessions_create(void)
67 {
68     http_sessions_t hs = xmalloc(sizeof(*hs));
69     hs->session_list = 0;
70     hs->mutex = 0;
71     pazpar2_mutex_create(&hs->mutex, "http_sessions");
72     return hs;
73 }
74
75 void http_sessions_destroy(http_sessions_t hs)
76 {
77     if (hs)
78     {
79         struct http_session *s = hs->session_list;
80         while (s)
81         {
82             struct http_session *s_next = s->next;
83             iochan_destroy(s->timeout_iochan);
84             destroy_session(s->psession);
85             nmem_destroy(s->nmem);
86             s = s_next;
87         }
88         yaz_mutex_destroy(&hs->mutex);
89         xfree(hs);
90     }
91 }
92
93 void http_session_destroy(struct http_session *s);
94
95 static void session_timeout(IOCHAN i, int event)
96 {
97     struct http_session *s = iochan_getdata(i);
98     http_session_destroy(s);
99 }
100
101 struct http_session *http_session_create(struct conf_service *service,
102                                          http_sessions_t http_sessions,
103                                          unsigned int sesid)
104 {
105     NMEM nmem = nmem_create();
106     struct http_session *r = nmem_malloc(nmem, sizeof(*r));
107     char tmp_str[50];
108
109     sprintf(tmp_str, "session#%u", sesid);
110     r->psession = new_session(nmem, service, tmp_str);
111     r->session_id = sesid;
112     r->timestamp = 0;
113     r->nmem = nmem;
114     r->destroy_counter = r->activity_counter = 0;
115     r->http_sessions = http_sessions;
116
117     yaz_mutex_enter(http_sessions->mutex);
118     r->next = http_sessions->session_list;
119     http_sessions->session_list = r;
120     yaz_mutex_leave(http_sessions->mutex);
121
122     r->timeout_iochan = iochan_create(-1, session_timeout, 0, "http_session_timeout");
123     iochan_setdata(r->timeout_iochan, r);
124     yaz_log(YLOG_LOG, "%p HTTP session %u created. timeout chan=%p timeout=%d", r, sesid, r->timeout_iochan, service->session_timeout);
125     iochan_settimeout(r->timeout_iochan, service->session_timeout);
126
127     iochan_add(service->server->iochan_man, r->timeout_iochan);
128     return r;
129 }
130
131 void http_session_destroy(struct http_session *s)
132 {
133     int must_destroy = 0;
134
135     http_sessions_t http_sessions = s->http_sessions;
136
137     yaz_log(YLOG_LOG, "%p HTTP session destroy %u", s, s->session_id);
138     yaz_mutex_enter(http_sessions->mutex);
139     /* only if http_session has no active http sessions on it can be destroyed */
140     if (s->destroy_counter == s->activity_counter) {
141         must_destroy = 1;
142         struct http_session **p = 0;
143         for (p = &http_sessions->session_list; *p; p = &(*p)->next)
144             if (*p == s)
145             {
146                 *p = (*p)->next;
147                 break;
148             }
149     }
150     yaz_mutex_leave(http_sessions->mutex);
151     if (must_destroy)
152     {   /* destroying for real */
153         yaz_log(YLOG_LOG, "Destroying session %u", s->session_id);
154         iochan_destroy(s->timeout_iochan);
155         destroy_session(s->psession);
156         nmem_destroy(s->nmem);
157     }
158     else {
159         yaz_log(YLOG_DEBUG, "%p HTTP Session %d. Active clients (%d-%d). Waiting for new timeout.", s, s->session_id, s->activity_counter, s->destroy_counter);
160     }
161
162 }
163
164 static const char *get_msg(enum pazpar2_error_code code)
165 {
166     struct pazpar2_error_msg {
167         enum pazpar2_error_code code;
168         const char *msg;
169     };
170     static const struct pazpar2_error_msg ar[] = {
171         { PAZPAR2_NO_SESSION, "Session does not exist or it has expired"},
172         { PAZPAR2_MISSING_PARAMETER, "Missing parameter"},
173         { PAZPAR2_MALFORMED_PARAMETER_VALUE, "Malformed parameter value"},
174         { PAZPAR2_MALFORMED_PARAMETER_ENCODING, "Malformed parameter encoding"},
175         { PAZPAR2_MALFORMED_SETTING, "Malformed setting argument"},
176         { PAZPAR2_HITCOUNTS_FAILED, "Failed to retrieve hitcounts"},
177         { PAZPAR2_RECORD_MISSING, "Record missing"},
178         { PAZPAR2_NO_TARGETS, "No targets"},
179         { PAZPAR2_CONFIG_TARGET, "Target cannot be configured"},
180         { PAZPAR2_RECORD_FAIL, "Record command failed"},
181         { PAZPAR2_NOT_IMPLEMENTED, "Not implemented"},
182         { PAZPAR2_NO_SERVICE, "No service"},
183         { PAZPAR2_LAST_ERROR, "Last error"},
184         { 0, 0 }
185     };
186     int i = 0;
187     while (ar[i].msg)
188     {
189         if (code == ar[i].code)
190             return ar[i].msg;
191         i++;
192     }
193     return "No error";
194 }
195
196 static void error(struct http_response *rs, 
197                   enum pazpar2_error_code code,
198                   const char *addinfo)
199 {
200     struct http_channel *c = rs->channel;
201     WRBUF text = wrbuf_alloc();
202     const char *http_status = "417";
203     const char *msg = get_msg(code);
204     
205     rs->msg = nmem_strdup(c->nmem, msg);
206     strcpy(rs->code, http_status);
207
208     wrbuf_printf(text, HTTP_COMMAND_RESPONSE_PREFIX "<error code=\"%d\" msg=\"%s\">", (int) code,
209                msg);
210     if (addinfo)
211         wrbuf_xmlputs(text, addinfo);
212     wrbuf_puts(text, "</error>");
213
214     yaz_log(YLOG_WARN, "HTTP %s %s%s%s", http_status,
215             msg, addinfo ? ": " : "" , addinfo ? addinfo : "");
216     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(text));
217     wrbuf_destroy(text);
218     http_send_response(c);
219 }
220
221 unsigned int make_sessionid(void)
222 {
223     static int seq = 0; /* thread pr */
224     unsigned int res;
225
226     seq++;
227     if (global_parameters.debug_mode)
228         res = seq;
229     else
230     {
231 #ifdef WIN32
232         res = seq;
233 #else
234         struct timeval t;
235
236         if (gettimeofday(&t, 0) < 0)
237         {
238             yaz_log(YLOG_WARN|YLOG_ERRNO, "gettimeofday");
239             exit(1);
240         }
241         /* at most 256 sessions per second .. 
242            (long long would be more appropriate)*/
243         res = t.tv_sec;
244         res = ((res << 8) | (seq & 0xff)) & ((1U << 31) - 1);
245 #endif
246     }
247     return res;
248 }
249
250 static struct http_session *locate_session(struct http_channel *c)
251 {
252     struct http_response *rs = c->response;
253     struct http_request *rq = c->request;
254     struct http_session *p;
255     const char *session = http_argbyname(rq, "session");
256     http_sessions_t http_sessions = c->http_sessions;
257     unsigned int id;
258
259     if (!session)
260     {
261         error(rs, PAZPAR2_MISSING_PARAMETER, "session");
262         return 0;
263     }
264     id = atoi(session);
265     yaz_mutex_enter(http_sessions->mutex);
266     for (p = http_sessions->session_list; p; p = p->next)
267         if (id == p->session_id)
268             break;
269     if (p)
270         p->activity_counter++;
271     yaz_mutex_leave(http_sessions->mutex);
272     if (p)
273         iochan_activity(p->timeout_iochan);
274     else
275         error(rs, PAZPAR2_NO_SESSION, session);
276     return p;
277 }
278
279 // Call after use of locate_session, in order to increment the destroy_counter
280 static struct http_session *release_session(struct http_channel *c, struct http_session *session) {
281     http_sessions_t http_sessions = c->http_sessions;
282     yaz_mutex_enter(http_sessions->mutex);
283     if (session)
284         session->destroy_counter++;
285     yaz_mutex_leave(http_sessions->mutex);
286 }
287
288 // Decode settings parameters and apply to session
289 // Syntax: setting[target]=value
290 static int process_settings(struct session *se, struct http_request *rq,
291                             struct http_response *rs)
292 {
293     struct http_argument *a;
294
295     for (a = rq->arguments; a; a = a->next)
296         if (strchr(a->name, '['))
297         {
298             char **res;
299             int num;
300             char *dbname;
301             char *setting;
302
303             // Nmem_strsplit *rules*!!!
304             nmem_strsplit(se->session_nmem, "[]", a->name, &res, &num);
305             if (num != 2)
306             {
307                 error(rs, PAZPAR2_MALFORMED_SETTING, a->name);
308                 return -1;
309             }
310             setting = res[0];
311             dbname = res[1];
312             session_apply_setting(se, dbname, setting,
313                     nmem_strdup(se->session_nmem, a->value));
314         }
315     return 0;
316 }
317
318 static void cmd_exit(struct http_channel *c)
319 {
320     yaz_log(YLOG_WARN, "exit");
321     http_close_server(c->server);
322 }
323
324 static void cmd_init(struct http_channel *c)
325 {
326     char buf[1024];
327     struct http_request *r = c->request;
328     const char *clear = http_argbyname(r, "clear");
329     const char *content_type = http_lookup_header(r->headers, "Content-Type");
330     unsigned int sesid;
331     struct http_session *s;
332     struct http_response *rs = c->response;
333     struct conf_service *service = 0; /* no service (yet) */
334     
335     if (r->content_len && content_type && 
336         !yaz_strcmp_del("text/xml", content_type, "; "))
337     {
338         xmlDoc *doc = xmlParseMemory(r->content_buf, r->content_len);
339         xmlNode *root_n;
340         if (!doc)
341         {
342             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
343             return;
344         }
345         root_n = xmlDocGetRootElement(doc);
346         service = service_create(c->server, root_n);
347         xmlFreeDoc(doc);
348         if (!service)
349         {
350             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
351             return;
352         }
353     }
354     
355     if (!service)
356     {
357         const char *service_name = http_argbyname(c->request, "service");
358         service = locate_service(c->server, service_name);
359         if (!service)
360         {
361             error(rs, PAZPAR2_NO_SERVICE, service_name ? service_name : "unnamed");
362             return;
363         }
364     }
365     sesid = make_sessionid();
366     s = http_session_create(service, c->http_sessions, sesid);
367     
368     yaz_log(YLOG_DEBUG, "HTTP Session init");
369     if (!clear || *clear == '0')
370         session_init_databases(s->psession);
371     else
372         yaz_log(YLOG_LOG, "No databases preloaded");
373     
374     if (process_settings(s->psession, c->request, c->response) < 0)
375         return;
376     
377     sprintf(buf, HTTP_COMMAND_RESPONSE_PREFIX 
378             "<init><status>OK</status><session>%d", sesid);
379     if (c->server->server_id)
380     {
381         strcat(buf, ".");
382         strcat(buf, c->server->server_id);
383     }
384     strcat(buf, "</session>"
385            "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol></init>");
386     rs->payload = nmem_strdup(c->nmem, buf);
387     http_send_response(c);
388 }
389
390 static void apply_local_setting(void *client_data,
391                                 struct setting *set)
392 {
393     struct session *se =  (struct session *) client_data;
394
395     session_apply_setting(se, nmem_strdup(se->session_nmem, set->target),
396                           nmem_strdup(se->session_nmem, set->name),
397                           nmem_strdup(se->session_nmem, set->value));
398 }
399
400 static void cmd_settings(struct http_channel *c)
401 {
402     struct http_response *rs = c->response;
403     struct http_request *rq = c->request;
404     struct http_session *s = locate_session(c);
405     const char *content_type = http_lookup_header(rq->headers, "Content-Type");
406
407     if (!s)
408         return;
409
410     if (rq->content_len && content_type && 
411         !yaz_strcmp_del("text/xml", content_type, "; "))
412     {
413         xmlDoc *doc = xmlParseMemory(rq->content_buf, rq->content_len);
414         xmlNode *root_n;
415         if (!doc)
416         {
417             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
418             return;
419         }
420         root_n = xmlDocGetRootElement(doc);
421
422         settings_read_node_x(root_n, s->psession, apply_local_setting);
423
424         xmlFreeDoc(doc);
425     }
426     if (process_settings(s->psession, rq, rs) < 0)
427         return;
428     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<settings><status>OK</status></settings>";
429     http_send_response(c);
430     release_session(c,s);
431 }
432
433 // Compares two hitsbytarget nodes by hitcount
434 static int cmp_ht(const void *p1, const void *p2)
435 {
436     const struct hitsbytarget *h1 = p1;
437     const struct hitsbytarget *h2 = p2;
438     return h2->hits - h1->hits;
439 }
440
441 // This implements functionality somewhat similar to 'bytarget', but in a termlist form
442 static void targets_termlist(WRBUF wrbuf, struct session *se, int num,
443                              NMEM nmem)
444 {
445     struct hitsbytarget *ht;
446     int count, i;
447
448     ht = hitsbytarget(se, &count, nmem);
449     qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
450     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
451     {
452
453         // do only print terms which have display names
454     
455         wrbuf_puts(wrbuf, "<term>\n");
456
457         wrbuf_puts(wrbuf, "<id>");
458         wrbuf_xmlputs(wrbuf, ht[i].id);
459         wrbuf_puts(wrbuf, "</id>\n");
460         
461         wrbuf_puts(wrbuf, "<name>");
462         if (!ht[i].name || !ht[i].name[0])
463             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
464         else
465             wrbuf_xmlputs(wrbuf, ht[i].name);
466         wrbuf_puts(wrbuf, "</name>\n");
467         
468         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
469                      ht[i].hits);
470         
471         wrbuf_puts(wrbuf, "<state>");
472         wrbuf_xmlputs(wrbuf, ht[i].state);
473         wrbuf_puts(wrbuf, "</state>\n");
474         
475         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
476                      ht[i].diagnostic);
477         wrbuf_puts(wrbuf, "</term>\n");
478     }
479 }
480
481 static void cmd_termlist(struct http_channel *c)
482 {
483     struct http_response *rs = c->response;
484     struct http_request *rq = c->request;
485     struct http_session *s = locate_session(c);
486     struct termlist_score **p;
487     int len;
488     int i;
489     const char *name = http_argbyname(rq, "name");
490     const char *nums = http_argbyname(rq, "num");
491     int num = 15;
492     int status;
493
494     if (!s)
495         return;
496
497     status = session_active_clients(s->psession);
498
499     if (!name)
500         name = "subject";
501     if (strlen(name) > 255)
502         return;
503     if (nums)
504         num = atoi(nums);
505
506     wrbuf_rewind(c->wrbuf);
507
508     wrbuf_puts(c->wrbuf, "<termlist>\n");
509     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", status);
510     while (*name)
511     {
512         char tname[256];
513         const char *tp;
514
515         if (!(tp = strchr(name, ',')))
516             tp = name + strlen(name);
517         strncpy(tname, name, tp - name);
518         tname[tp - name] = '\0';
519
520         wrbuf_puts(c->wrbuf, "<list name=\"");
521         wrbuf_xmlputs(c->wrbuf, tname);
522         wrbuf_puts(c->wrbuf, "\">\n");
523         if (!strcmp(tname, "xtargets"))
524             targets_termlist(c->wrbuf, s->psession, num, c->nmem);
525         else
526         {
527             p = termlist(s->psession, tname, &len);
528             if (p)
529                 for (i = 0; i < len && i < num; i++){
530                     // prevnt sending empty term elements
531                     if (!p[i]->term || !p[i]->term[0])
532                         continue;
533
534                     wrbuf_puts(c->wrbuf, "<term>");
535                     wrbuf_puts(c->wrbuf, "<name>");
536                     wrbuf_xmlputs(c->wrbuf, p[i]->term);
537                     wrbuf_puts(c->wrbuf, "</name>");
538                         
539                     wrbuf_printf(c->wrbuf, 
540                                  "<frequency>%d</frequency>", 
541                                  p[i]->frequency);
542                     wrbuf_puts(c->wrbuf, "</term>\n");
543                }
544         }
545         wrbuf_puts(c->wrbuf, "</list>\n");
546         name = tp;
547         if (*name == ',')
548             name++;
549     }
550     wrbuf_puts(c->wrbuf, "</termlist>\n");
551     rs->payload = nmem_strdup(rq->channel->nmem, wrbuf_cstr(c->wrbuf));
552     http_send_response(c);
553     release_session(c,s);
554 }
555
556
557 static void cmd_bytarget(struct http_channel *c)
558 {
559     struct http_response *rs = c->response;
560     struct http_request *rq = c->request;
561     struct http_session *s = locate_session(c);
562     struct hitsbytarget *ht;
563     const char *settings = http_argbyname(rq, "settings");
564     int count, i;
565
566     if (!s)
567         return;
568     ht = hitsbytarget(s->psession, &count, c->nmem);
569     wrbuf_rewind(c->wrbuf);
570     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<bytarget><status>OK</status>");
571
572     for (i = 0; i < count; i++)
573     {
574         wrbuf_puts(c->wrbuf, "\n<target>");
575
576         wrbuf_puts(c->wrbuf, "<id>");
577         wrbuf_xmlputs(c->wrbuf, ht[i].id);
578         wrbuf_puts(c->wrbuf, "</id>\n");
579
580         if (ht[i].name && ht[i].name[0]) 
581         {
582             wrbuf_puts(c->wrbuf, "<name>");
583             wrbuf_xmlputs(c->wrbuf, ht[i].name);
584             wrbuf_puts(c->wrbuf, "</name>\n");
585         }
586
587         wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", ht[i].hits);
588         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
589         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
590
591         wrbuf_puts(c->wrbuf, "<state>");
592         wrbuf_xmlputs(c->wrbuf, ht[i].state);
593         wrbuf_puts(c->wrbuf, "</state>\n");
594         if (settings && *settings == '1')
595         {
596             wrbuf_puts(c->wrbuf, "<settings>\n");
597             wrbuf_puts(c->wrbuf, wrbuf_cstr(ht[i].settings_xml));
598             wrbuf_puts(c->wrbuf, "</settings>\n");
599         }
600         wrbuf_puts(c->wrbuf, "</target>");
601         wrbuf_destroy(ht[i].settings_xml);
602     }
603
604     wrbuf_puts(c->wrbuf, "</bytarget>");
605     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
606     http_send_response(c);
607     release_session(c,s);
608 }
609
610 static void write_metadata(WRBUF w, struct conf_service *service,
611         struct record_metadata **ml, int full)
612 {
613     int imeta;
614
615     for (imeta = 0; imeta < service->num_metadata; imeta++)
616     {
617         struct conf_metadata *cmd = &service->metadata[imeta];
618         struct record_metadata *md;
619         if (!cmd->brief && !full)
620             continue;
621         for (md = ml[imeta]; md; md = md->next)
622         {
623             struct record_metadata_attr *attr = md->attributes;
624             wrbuf_printf(w, "\n<md-%s", cmd->name);
625
626             for (; attr; attr = attr->next)
627             {
628                 wrbuf_printf(w, " %s=\"", attr->name);
629                 wrbuf_xmlputs(w, attr->value);
630                 wrbuf_puts(w, "\"");
631             }
632             wrbuf_puts(w, ">");
633             switch (cmd->type)
634             {
635                 case Metadata_type_generic:
636                     wrbuf_xmlputs(w, md->data.text.disp);
637                     break;
638                 case Metadata_type_year:
639                     wrbuf_printf(w, "%d", md->data.number.min);
640                     if (md->data.number.min != md->data.number.max)
641                         wrbuf_printf(w, "-%d", md->data.number.max);
642                     break;
643                 default:
644                     wrbuf_puts(w, "[can't represent]");
645             }
646             wrbuf_printf(w, "</md-%s>", cmd->name);
647         }
648     }
649 }
650
651 static void write_subrecord(struct record *r, WRBUF w,
652         struct conf_service *service, int show_details)
653 {
654     const char *name = session_setting_oneval(
655         client_get_database(r->client), PZ_NAME);
656
657     wrbuf_puts(w, "<location id=\"");
658     wrbuf_xmlputs(w, client_get_database(r->client)->database->url);
659     wrbuf_puts(w, "\" ");
660
661     wrbuf_puts(w, "name=\"");
662     wrbuf_xmlputs(w,  *name ? name : "Unknown");
663     wrbuf_puts(w, "\">");
664
665     write_metadata(w, service, r->metadata, show_details);
666     wrbuf_puts(w, "</location>\n");
667 }
668
669 static void show_raw_record_error(void *data, const char *addinfo)
670 {
671     http_channel_observer_t obs = data;
672     struct http_channel *c = http_channel_observer_chan(obs);
673     struct http_response *rs = c->response;
674
675     http_remove_observer(obs);
676
677     error(rs, PAZPAR2_RECORD_FAIL, addinfo);
678 }
679
680 static void show_raw_record_ok(void *data, const char *buf, size_t sz)
681 {
682     http_channel_observer_t obs = data;
683     struct http_channel *c = http_channel_observer_chan(obs);
684     struct http_response *rs = c->response;
685
686     http_remove_observer(obs);
687
688     wrbuf_write(c->wrbuf, buf, sz);
689     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
690     http_send_response(c);
691 }
692
693
694 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
695 {
696     http_channel_observer_t obs = data;
697     struct http_channel *c = http_channel_observer_chan(obs);
698     struct http_response *rs = c->response;
699
700     http_remove_observer(obs);
701
702     wrbuf_write(c->wrbuf, buf, sz);
703     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
704
705     rs->content_type = "application/octet-stream";
706     http_send_response(c);
707 }
708
709
710 void show_raw_reset(void *data, struct http_channel *c, void *data2)
711 {
712     //struct client *client = data;
713     //client_show_raw_remove(client, data2);
714 }
715
716 static void cmd_record_ready(void *data);
717
718 static void cmd_record(struct http_channel *c)
719 {
720     struct http_response *rs = c->response;
721     struct http_request *rq = c->request;
722     struct http_session *s = locate_session(c);
723     struct record_cluster *rec, *prev_r, *next_r;
724     struct record *r;
725     struct conf_service *service;
726     const char *idstr = http_argbyname(rq, "id");
727     const char *offsetstr = http_argbyname(rq, "offset");
728     const char *binarystr = http_argbyname(rq, "binary");
729     
730     if (!s)
731         return;
732     service = s->psession->service;
733     if (!idstr)
734     {
735         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
736         return;
737     }
738     wrbuf_rewind(c->wrbuf);
739     if (!(rec = show_single_start(s->psession, idstr, &prev_r, &next_r)))
740     {
741         if (session_active_clients(s->psession) == 0)
742         {
743             error(rs, PAZPAR2_RECORD_MISSING, idstr);
744         }
745         else if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
746                               cmd_record_ready, c, c) != 0)
747         {
748             error(rs, PAZPAR2_RECORD_MISSING, idstr);
749         }
750         release_session(c, s);
751         return;
752     }
753     if (offsetstr)
754     {
755         int offset = atoi(offsetstr);
756         const char *syntax = http_argbyname(rq, "syntax");
757         const char *esn = http_argbyname(rq, "esn");
758         int i;
759         struct record*r = rec->records;
760         int binary = 0;
761
762         if (binarystr && *binarystr != '0')
763             binary = 1;
764
765         for (i = 0; i < offset && r; r = r->next, i++)
766             ;
767         if (!r)
768         {
769             error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
770         }
771         else
772         {
773             http_channel_observer_t obs =
774                 http_add_observer(c, r->client, show_raw_reset);
775             int ret = client_show_raw_begin(r->client, r->position,
776                                         syntax, esn, 
777                                         obs /* data */,
778                                         show_raw_record_error,
779                                         (binary ? 
780                                          show_raw_record_ok_binary : 
781                                          show_raw_record_ok),
782                                         (binary ? 1 : 0));
783             if (ret == -1)
784             {
785                 http_remove_observer(obs);
786                 error(rs, PAZPAR2_NO_SESSION, 0);
787             }
788         }
789     }
790     else
791     {
792         wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<record>\n");
793         wrbuf_puts(c->wrbuf, "<recid>");
794         wrbuf_xmlputs(c->wrbuf, rec->recid);
795         wrbuf_puts(c->wrbuf, "</recid>\n");
796         if (prev_r)
797         {
798             wrbuf_puts(c->wrbuf, "<prevrecid>");
799             wrbuf_xmlputs(c->wrbuf, prev_r->recid);
800             wrbuf_puts(c->wrbuf, "</prevrecid>\n");
801         }
802         if (next_r)
803         {
804             wrbuf_puts(c->wrbuf, "<nextrecid>");
805             wrbuf_xmlputs(c->wrbuf, next_r->recid);
806             wrbuf_puts(c->wrbuf, "</nextrecid>\n");
807         }
808         wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", 
809                      session_active_clients(s->psession));
810         write_metadata(c->wrbuf, service, rec->metadata, 1);
811         for (r = rec->records; r; r = r->next)
812             write_subrecord(r, c->wrbuf, service, 1);
813         wrbuf_puts(c->wrbuf, "</record>\n");
814         rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
815         http_send_response(c);
816     }
817     show_single_stop(s->psession, rec);
818     release_session(c, s);
819 }
820
821 static void cmd_record_ready(void *data)
822 {
823     struct http_channel *c = (struct http_channel *) data;
824
825     cmd_record(c);
826 }
827
828 static void show_records(struct http_channel *c, int active)
829 {
830     struct http_request *rq = c->request;
831     struct http_response *rs = c->response;
832     struct http_session *s = locate_session(c);
833     struct record_cluster **rl;
834     struct reclist_sortparms *sp;
835     const char *start = http_argbyname(rq, "start");
836     const char *num = http_argbyname(rq, "num");
837     const char *sort = http_argbyname(rq, "sort");
838     int startn = 0;
839     int numn = 20;
840     int total;
841     Odr_int total_hits;
842     int i;
843
844     if (!s)
845         return;
846
847     // We haven't counted clients yet if we're called on a block release
848     if (active < 0)
849         active = session_active_clients(s->psession);
850
851     if (start)
852         startn = atoi(start);
853     if (num)
854         numn = atoi(num);
855     if (!sort)
856         sort = "relevance";
857     if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
858     {
859         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
860         release_session(c, s);
861         return;
862     }
863
864     
865     rl = show_range_start(s->psession, sp, startn, &numn, &total, &total_hits);
866
867     wrbuf_rewind(c->wrbuf);
868     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<show>\n<status>OK</status>\n");
869     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
870     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
871     wrbuf_printf(c->wrbuf, "<total>" ODR_INT_PRINTF "</total>\n", total_hits);
872     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
873     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
874
875     for (i = 0; i < numn; i++)
876     {
877         int ccount;
878         struct record *p;
879         struct record_cluster *rec = rl[i];
880         struct conf_service *service = s->psession->service;
881
882         wrbuf_puts(c->wrbuf, "<hit>\n");
883         write_metadata(c->wrbuf, service, rec->metadata, 0);
884         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
885             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
886         if (ccount > 1)
887             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
888         if (strstr(sort, "relevance"))
889             wrbuf_printf(c->wrbuf, "<relevance>%d</relevance>\n",
890                          rec->relevance_score);
891         wrbuf_puts(c->wrbuf, "<recid>");
892         wrbuf_xmlputs(c->wrbuf, rec->recid);
893         wrbuf_puts(c->wrbuf, "</recid>\n");
894         wrbuf_puts(c->wrbuf, "</hit>\n");
895     }
896
897     show_range_stop(s->psession, rl);
898
899     wrbuf_puts(c->wrbuf, "</show>\n");
900     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
901     http_send_response(c);
902     release_session(c, s);
903 }
904
905 static void show_records_ready(void *data)
906 {
907     struct http_channel *c = (struct http_channel *) data;
908
909     show_records(c, -1);
910 }
911
912 static void cmd_show(struct http_channel *c)
913 {
914     struct http_request *rq = c->request;
915     struct http_session *s = locate_session(c);
916     const char *block = http_argbyname(rq, "block");
917     int status;
918
919     if (!s)
920         return;
921
922     status = session_active_clients(s->psession);
923
924     if (block)
925     {
926         if (status && reclist_get_num_records(s->psession->reclist) == 0)
927         {
928             // if there is already a watch/block. we do not block this one
929             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
930                                   show_records_ready, c, c) != 0)
931             {
932                 yaz_log(YLOG_DEBUG, "Blocking on cmd_show");
933             }
934             return;
935         }
936     }
937
938     show_records(c, status);
939     release_session(c,s);
940 }
941
942 static void cmd_ping(struct http_channel *c)
943 {
944     struct http_response *rs = c->response;
945     struct http_session *s = locate_session(c);
946     if (!s)
947         return;
948     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<ping><status>OK</status></ping>";
949     http_send_response(c);
950     release_session(c, s);
951 }
952
953 static int utf_8_valid(const char *str)
954 {
955     yaz_iconv_t cd = yaz_iconv_open("utf-8", "utf-8");
956     if (cd)
957     {
958         /* check that query is UTF-8 encoded */
959         char *inbuf = (char *) str; /* we know iconv does not alter this */
960         size_t inbytesleft = strlen(inbuf);
961
962         size_t outbytesleft = strlen(inbuf) + 10;
963         char *out = xmalloc(outbytesleft);
964         char *outbuf = out;
965         size_t r = yaz_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
966
967         /* if OK, try flushing the rest  */
968         if (r != (size_t) (-1))
969             r = yaz_iconv(cd, 0, 0, &outbuf, &outbytesleft);
970         yaz_iconv_close(cd);
971         xfree(out);
972         if (r == (size_t) (-1))
973             return 0;
974     }
975     return 1;
976 }
977
978 static void cmd_search(struct http_channel *c)
979 {
980     struct http_request *rq = c->request;
981     struct http_response *rs = c->response;
982     struct http_session *s = locate_session(c);
983     const char *query = http_argbyname(rq, "query");
984     const char *filter = http_argbyname(rq, "filter");
985     const char *maxrecs = http_argbyname(rq, "maxrecs");
986     const char *startrecs = http_argbyname(rq, "startrecs");
987     enum pazpar2_error_code code;
988     const char *addinfo = 0;
989
990     if (!s)
991         return;
992     if (!query)
993     {
994         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
995         release_session(c,s);
996         return;
997     }
998     if (!utf_8_valid(query))
999     {
1000         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
1001         release_session(c,s);
1002         return;
1003     }
1004     code = search(s->psession, query, startrecs, maxrecs, filter, &addinfo);
1005     if (code)
1006     {
1007         error(rs, code, addinfo);
1008         release_session(c,s);
1009         return;
1010     }
1011     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<search><status>OK</status></search>";
1012     http_send_response(c);
1013     release_session(c,s);
1014 }
1015
1016
1017 static void cmd_stat(struct http_channel *c)
1018 {
1019     struct http_response *rs = c->response;
1020     struct http_session *s = locate_session(c);
1021     struct statistics stat;
1022     int clients;
1023
1024     float progress = 0;
1025
1026     if (!s)
1027         return;
1028
1029     clients = session_active_clients(s->psession);
1030     statistics(s->psession, &stat);
1031
1032     if (stat.num_clients > 0) {
1033         progress = (stat.num_clients  - clients) / (float)stat.num_clients;
1034     }
1035
1036     wrbuf_rewind(c->wrbuf);
1037     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<stat>");
1038     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
1039     wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", stat.num_hits);
1040     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
1041     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
1042     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
1043     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
1044     wrbuf_printf(c->wrbuf, "<working>%d</working>\n", stat.num_working);
1045     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
1046     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
1047     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
1048     wrbuf_printf(c->wrbuf, "<progress>%.2f</progress>\n", progress);
1049     wrbuf_puts(c->wrbuf, "</stat>");
1050     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1051     http_send_response(c);
1052     release_session(c,s);
1053 }
1054
1055 static void cmd_info(struct http_channel *c)
1056 {
1057     char yaz_version_str[20];
1058     struct http_response *rs = c->response;
1059
1060     wrbuf_rewind(c->wrbuf);
1061     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<info>\n");
1062     wrbuf_puts(c->wrbuf, " <version>\n");
1063     wrbuf_puts(c->wrbuf, "<pazpar2");
1064 #ifdef PAZPAR2_VERSION_SHA1
1065     wrbuf_printf(c->wrbuf, " sha1=\"%s\"", PAZPAR2_VERSION_SHA1);
1066 #endif
1067     wrbuf_puts(c->wrbuf, ">");
1068     wrbuf_xmlputs(c->wrbuf, VERSION);
1069     wrbuf_puts(c->wrbuf, "</pazpar2>");
1070
1071
1072     yaz_version(yaz_version_str, 0);
1073     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
1074     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
1075     wrbuf_puts(c->wrbuf, "\">");
1076     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
1077     wrbuf_puts(c->wrbuf, "</yaz>\n");
1078
1079     wrbuf_puts(c->wrbuf, " </version>\n");
1080     
1081     wrbuf_puts(c->wrbuf, "</info>");
1082     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1083     http_send_response(c);
1084 }
1085
1086 struct {
1087     char *name;
1088     void (*fun)(struct http_channel *c);
1089 } commands[] = {
1090     { "init", cmd_init },
1091     { "settings", cmd_settings },
1092     { "stat", cmd_stat },
1093     { "bytarget", cmd_bytarget },
1094     { "show", cmd_show },
1095     { "search", cmd_search },
1096     { "termlist", cmd_termlist },
1097     { "exit", cmd_exit },
1098     { "ping", cmd_ping },
1099     { "record", cmd_record },
1100     { "info", cmd_info },
1101     {0,0}
1102 };
1103
1104 void http_command(struct http_channel *c)
1105 {
1106     const char *command = http_argbyname(c->request, "command");
1107     struct http_response *rs = http_create_response(c);
1108     int i;
1109
1110     c->response = rs;
1111
1112     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
1113     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
1114
1115     if (!command)
1116     {
1117         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
1118         return;
1119     }
1120     for (i = 0; commands[i].name; i++)
1121         if (!strcmp(commands[i].name, command))
1122         {
1123             (*commands[i].fun)(c);
1124             break;
1125         }
1126     if (!commands[i].name)
1127         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
1128
1129     return;
1130 }
1131
1132 /*
1133  * Local variables:
1134  * c-basic-offset: 4
1135  * c-file-style: "Stroustrup"
1136  * indent-tabs-mode: nil
1137  * End:
1138  * vim: shiftwidth=4 tabstop=8 expandtab
1139  */
1140