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