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