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