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