Fix memory leak in service command
[pazpar2-moved-to-github.git] / src / http_command.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2013 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 static void show_records_ready(void *data);
97
98 int get_version(struct http_request *rq) {
99     const char *version = http_argbyname(rq, "version");
100     int version_no = 0;
101     if (version && strcmp(version, "")) {
102         version_no = atoi(version);
103     }
104     return version_no;
105 }
106
107
108 int http_session_use(int delta)
109 {
110     int sessions;
111     if (!g_http_session_mutex)
112         yaz_mutex_create(&g_http_session_mutex);
113     yaz_mutex_enter(g_http_session_mutex);
114     g_http_sessions += delta;
115     sessions = g_http_sessions;
116     yaz_mutex_leave(g_http_session_mutex);
117     yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), sessions);
118     return sessions;
119
120 }
121
122 http_sessions_t http_sessions_create(void)
123 {
124     http_sessions_t hs = xmalloc(sizeof(*hs));
125     hs->session_list = 0;
126     hs->mutex = 0;
127     pazpar2_mutex_create(&hs->mutex, "http_sessions");
128     hs->log_level = yaz_log_module_level("HTTP");
129     return hs;
130 }
131
132 void http_sessions_destroy(http_sessions_t hs)
133 {
134     if (hs)
135     {
136         struct http_session *s = hs->session_list;
137         while (s)
138         {
139             struct http_session *s_next = s->next;
140             iochan_destroy(s->timeout_iochan);
141             session_destroy(s->psession);
142             nmem_destroy(s->nmem);
143             s = s_next;
144         }
145         yaz_mutex_destroy(&hs->mutex);
146         xfree(hs);
147     }
148 }
149
150 void http_session_destroy(struct http_session *s);
151
152 static void session_timeout(IOCHAN i, int event)
153 {
154     struct http_session *s = iochan_getdata(i);
155     http_session_destroy(s);
156 }
157
158 struct http_session *http_session_create(struct conf_service *service,
159                                          http_sessions_t http_sessions,
160                                          unsigned int sesid)
161 {
162     NMEM nmem = nmem_create();
163     struct http_session *r = nmem_malloc(nmem, sizeof(*r));
164     char tmp_str[50];
165
166     sprintf(tmp_str, "session#%u", sesid);
167     r->psession = new_session(nmem, service, sesid);
168     r->session_id = sesid;
169     r->timestamp = 0;
170     r->nmem = nmem;
171     r->destroy_counter = r->activity_counter = 0;
172     r->http_sessions = http_sessions;
173
174     yaz_mutex_enter(http_sessions->mutex);
175     r->next = http_sessions->session_list;
176     http_sessions->session_list = r;
177     yaz_mutex_leave(http_sessions->mutex);
178
179     r->timeout_iochan = iochan_create(-1, session_timeout, 0,
180                                       "http_session_timeout");
181     iochan_setdata(r->timeout_iochan, r);
182
183     session_log(r->psession, http_sessions->log_level,
184                 "HTTP session create. timeout chan=%p ses=%d",
185                 r->timeout_iochan, service->session_timeout);
186     iochan_settimeout(r->timeout_iochan, service->session_timeout);
187
188     iochan_add(service->server->iochan_man, r->timeout_iochan);
189     http_session_use(1);
190     return r;
191 }
192
193 void http_session_destroy(struct http_session *s)
194 {
195     int must_destroy = 0;
196
197     http_sessions_t http_sessions = s->http_sessions;
198
199     session_log(s->psession, http_sessions->log_level,
200                 "HTTP session destroy");
201     yaz_mutex_enter(http_sessions->mutex);
202     /* only if http_session has no active http sessions on it can be destroyed */
203     if (s->destroy_counter == s->activity_counter)
204     {
205         struct http_session **p = 0;
206         must_destroy = 1;
207         for (p = &http_sessions->session_list; *p; p = &(*p)->next)
208             if (*p == s)
209             {
210                 *p = (*p)->next;
211                 break;
212             }
213     }
214     yaz_mutex_leave(http_sessions->mutex);
215     if (must_destroy)
216     {   /* destroying for real */
217         session_log(s->psession, http_sessions->log_level, "About to destroyd");
218         iochan_destroy(s->timeout_iochan);
219         session_destroy(s->psession);
220         http_session_use(-1);
221         nmem_destroy(s->nmem);
222     }
223     else
224     {
225         session_log(s->psession, http_sessions->log_level,
226                     "Destroy delayed. Active clients (%d-%d)",
227                     s->activity_counter, s->destroy_counter);
228     }
229
230 }
231
232 static const char *get_msg(enum pazpar2_error_code code)
233 {
234     struct pazpar2_error_msg {
235         enum pazpar2_error_code code;
236         const char *msg;
237     };
238     static const struct pazpar2_error_msg ar[] = {
239         { PAZPAR2_NO_SESSION, "Session does not exist or it has expired"},
240         { PAZPAR2_MISSING_PARAMETER, "Missing parameter"},
241         { PAZPAR2_MALFORMED_PARAMETER_VALUE, "Malformed parameter value"},
242         { PAZPAR2_MALFORMED_PARAMETER_ENCODING, "Malformed parameter encoding"},
243         { PAZPAR2_MALFORMED_SETTING, "Malformed setting argument"},
244         { PAZPAR2_HITCOUNTS_FAILED, "Failed to retrieve hitcounts"},
245         { PAZPAR2_RECORD_MISSING, "Record missing"},
246         { PAZPAR2_NO_TARGETS, "No targets"},
247         { PAZPAR2_CONFIG_TARGET, "Target cannot be configured"},
248         { PAZPAR2_RECORD_FAIL, "Record command failed"},
249         { PAZPAR2_NOT_IMPLEMENTED, "Not implemented"},
250         { PAZPAR2_NO_SERVICE, "No service"},
251         { PAZPAR2_ALREADY_BLOCKED, "Already blocked in session on: "},
252         { PAZPAR2_LAST_ERROR, "Last error"},
253         { 0, 0 }
254     };
255     int i = 0;
256     while (ar[i].msg)
257     {
258         if (code == ar[i].code)
259             return ar[i].msg;
260         i++;
261     }
262     return "No error";
263 }
264
265 static void error(struct http_response *rs,
266                   enum pazpar2_error_code code,
267                   const char *addinfo)
268 {
269     struct http_channel *c = rs->channel;
270     WRBUF text = wrbuf_alloc();
271     const char *http_status = "417";
272     const char *msg = get_msg(code);
273
274     rs->msg = nmem_strdup(c->nmem, msg);
275     strcpy(rs->code, http_status);
276
277     wrbuf_printf(text, HTTP_COMMAND_RESPONSE_PREFIX "<error code=\"%d\" msg=\"%s\">", (int) code,
278                msg);
279     if (addinfo)
280         wrbuf_xmlputs(text, addinfo);
281     wrbuf_puts(text, "</error>");
282
283     yaz_log(YLOG_WARN, "HTTP %s %s%s%s", http_status,
284             msg, addinfo ? ": " : "" , addinfo ? addinfo : "");
285     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(text));
286     wrbuf_destroy(text);
287     http_send_response(c);
288 }
289
290 static void response_open_command(struct http_channel *c, const char *command)
291 {
292     wrbuf_rewind(c->wrbuf);
293     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX);
294     if (command)
295         wrbuf_printf(c->wrbuf, "<%s>", command);
296 }
297
298 static void response_open_ok(struct http_channel *c, const char *command)
299 {
300     response_open_command(c, command);
301     wrbuf_puts(c->wrbuf, "<status>OK</status>");
302 }
303
304 static void response_close(struct http_channel *c, const char *command)
305 {
306     struct http_response *rs = c->response;
307
308     if (command)
309         wrbuf_printf(c->wrbuf, "</%s>", command);
310     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
311     http_send_response(c);
312 }
313
314 unsigned int make_sessionid(void)
315 {
316     static int seq = 0; /* thread pr */
317     unsigned int res;
318
319     seq++;
320     if (global_parameters.predictable_sessions)
321         res = seq;
322     else
323     {
324 #ifdef WIN32
325         res = seq;
326 #else
327         struct timeval t;
328
329         if (gettimeofday(&t, 0) < 0)
330         {
331             yaz_log(YLOG_WARN|YLOG_ERRNO, "gettimeofday");
332             exit(1);
333         }
334         /* at most 256 sessions per second ..
335            (long long would be more appropriate)*/
336         res = t.tv_sec;
337         res = ((res << 8) | (seq & 0xff)) & ((1U << 31) - 1);
338 #endif
339     }
340     return res;
341 }
342
343 static struct http_session *locate_session(struct http_channel *c)
344 {
345     struct http_request *rq = c->request;
346     struct http_response *rs = c->response;
347     struct http_session *p;
348     const char *session = http_argbyname(rq, "session");
349     http_sessions_t http_sessions = c->http_sessions;
350     unsigned int id;
351
352     if (!session)
353     {
354         error(rs, PAZPAR2_MISSING_PARAMETER, "session");
355         return 0;
356     }
357     id = atoi(session);
358     yaz_mutex_enter(http_sessions->mutex);
359     for (p = http_sessions->session_list; p; p = p->next)
360         if (id == p->session_id)
361             break;
362     if (p)
363         p->activity_counter++;
364     yaz_mutex_leave(http_sessions->mutex);
365     if (p)
366         iochan_activity(p->timeout_iochan);
367     else
368         error(rs, PAZPAR2_NO_SESSION, session);
369     return p;
370 }
371
372 // Call after use of locate_session, in order to increment the destroy_counter
373 static void release_session(struct http_channel *c,
374                             struct http_session *session)
375 {
376     http_sessions_t http_sessions = c->http_sessions;
377     yaz_mutex_enter(http_sessions->mutex);
378     if (session)
379         session->destroy_counter++;
380     yaz_mutex_leave(http_sessions->mutex);
381 }
382
383 // Decode settings parameters and apply to session
384 // Syntax: setting[target]=value
385 static int process_settings(struct session *se, struct http_request *rq,
386                             struct http_response *rs)
387 {
388     struct http_argument *a;
389
390     for (a = rq->arguments; a; a = a->next)
391         if (strchr(a->name, '['))
392         {
393             char **res;
394             int num;
395             char *dbname;
396             char *setting;
397
398             // Nmem_strsplit *rules*!!!
399             nmem_strsplit(se->session_nmem, "[]", a->name, &res, &num);
400             if (num != 2)
401             {
402                 error(rs, PAZPAR2_MALFORMED_SETTING, a->name);
403                 return -1;
404             }
405             setting = res[0];
406             dbname = res[1];
407             session_apply_setting(se, dbname, setting,
408                     nmem_strdup(se->session_nmem, a->value));
409         }
410     return 0;
411 }
412
413 static void cmd_exit(struct http_channel *c)
414 {
415     yaz_log(YLOG_WARN, "exit");
416
417     response_open_ok(c, "exit");
418     response_close(c, "exit");
419     if (global_parameters.debug_mode)
420         http_close_server(c->server);
421 }
422
423 static void cmd_init(struct http_channel *c)
424 {
425     struct http_request *r = c->request;
426     const char *clear = http_argbyname(r, "clear");
427     const char *content_type = http_lookup_header(r->headers, "Content-Type");
428     unsigned int sesid;
429     struct http_session *s;
430     struct http_response *rs = c->response;
431     struct conf_service *service = 0; /* no service (yet) */
432
433     if (r->content_len && content_type &&
434         !yaz_strcmp_del("text/xml", content_type, "; "))
435     {
436         xmlDoc *doc = xmlParseMemory(r->content_buf, r->content_len);
437         xmlNode *root_n;
438         if (!doc)
439         {
440             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
441             return;
442         }
443         root_n = xmlDocGetRootElement(doc);
444         service = service_create(c->server, root_n);
445         xmlFreeDoc(doc);
446         if (!service)
447         {
448             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
449             return;
450         }
451     }
452
453     if (!service)
454     {
455         const char *service_name = http_argbyname(c->request, "service");
456         service = locate_service(c->server, service_name);
457         if (!service)
458         {
459             error(rs, PAZPAR2_NO_SERVICE, service_name ? service_name : "unnamed");
460             return;
461         }
462     }
463     sesid = make_sessionid();
464     s = http_session_create(service, c->http_sessions, sesid);
465
466     if (!clear || *clear == '0')
467         session_init_databases(s->psession);
468     else
469         session_log(s->psession, YLOG_LOG, "No databases preloaded");
470
471     if (process_settings(s->psession, c->request, c->response) < 0)
472         return;
473
474     response_open_ok(c, "init");
475     wrbuf_printf(c->wrbuf, "<session>%d", sesid);
476     if (c->server->server_id)
477     {
478         wrbuf_puts(c->wrbuf, ".");
479         wrbuf_puts(c->wrbuf, c->server->server_id);
480     }
481     wrbuf_puts(c->wrbuf, "</session>"
482                "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol>");
483
484     wrbuf_printf(c->wrbuf, "<keepAlive>%d</keepAlive>\n", 1000 * ((s->psession->service->session_timeout >= 20) ?
485                                                                   (s->psession->service->session_timeout - 10) : 50));
486     response_close(c, "init");
487 }
488
489 static void apply_local_setting(void *client_data,
490                                 struct setting *set)
491 {
492     struct session *se =  (struct session *) client_data;
493
494     session_apply_setting(se, nmem_strdup(se->session_nmem, set->target),
495                           nmem_strdup(se->session_nmem, set->name),
496                           nmem_strdup(se->session_nmem, set->value));
497 }
498
499 static void cmd_settings(struct http_channel *c)
500 {
501     struct http_response *rs = c->response;
502     struct http_request *rq = c->request;
503     struct http_session *s = locate_session(c);
504     const char *content_type = http_lookup_header(rq->headers, "Content-Type");
505
506     if (!s)
507         return;
508
509     if (rq->content_len && content_type &&
510         !yaz_strcmp_del("text/xml", content_type, "; "))
511     {
512         xmlDoc *doc = xmlParseMemory(rq->content_buf, rq->content_len);
513         xmlNode *root_n;
514         int ret;
515         if (!doc)
516         {
517             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
518             release_session(c,s);
519             return;
520         }
521         root_n = xmlDocGetRootElement(doc);
522         ret = settings_read_node_x(root_n, s->psession, apply_local_setting);
523         xmlFreeDoc(doc);
524         if (ret)
525         {
526             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
527             release_session(c,s);
528             return;
529         }
530     }
531     if (process_settings(s->psession, rq, rs) < 0)
532     {
533         release_session(c, s);
534         return;
535     }
536     response_open_ok(c, "settings");
537     response_close(c, "settings");
538     release_session(c, s);
539 }
540
541 static void termlist_response(struct http_channel *c, struct http_session *s, const char *cmd_status)
542 {
543     struct http_request *rq = c->request;
544     const char *name    = http_argbyname(rq, "name");
545     const char *nums    = http_argbyname(rq, "num");
546     int version = get_version(rq);
547     int num = 15;
548     int status;
549
550     if (nums)
551         num = atoi(nums);
552
553     status = session_active_clients(s->psession);
554
555     response_open_command(c, "termlist");
556     /* new protocol add a status to response. Triggered by a status parameter */
557     if (cmd_status != 0)
558         wrbuf_printf(c->wrbuf, "<status>%s</status>\n", cmd_status);
559     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", status);
560
561     perform_termlist(c, s->psession, name, num, version);
562
563     response_close(c, "termlist");
564 }
565
566 static void termlist_result_ready(void *data)
567 {
568     struct http_channel *c = (struct http_channel *) data;
569     struct http_request *rq = c->request;
570     const char *report = http_argbyname(rq, "report");
571     const char *status = 0;
572     struct http_session *s = locate_session(c);
573     if (report && !strcmp("status", report))
574         status = "OK";
575     if (s)
576     {
577         session_log(s->psession, c->http_sessions->log_level,
578                     "termlist watch released");
579         termlist_response(c, s, status);
580         release_session(c,s);
581     }
582 }
583
584 static void cmd_termlist(struct http_channel *c)
585 {
586     struct http_request *rq = c->request;
587     struct http_response *rs = c->response;
588     struct http_session *s = locate_session(c);
589     const char *block = http_argbyname(rq, "block");
590     const char *report = http_argbyname(rq, "report");
591     int report_status = 0;
592     int report_error = 0;
593     const char *status_message = 0;
594     int active_clients;
595
596     if (report && !strcmp("error", report))
597     {
598         report_error = 1;
599         status_message = "OK";
600     }
601     if (report && !strcmp("status", report))
602     {
603         report_status = 1;
604         status_message = "OK";
605     }
606     if (!s)
607         return;
608
609     active_clients = session_active_clients(s->psession);
610     if (block && !strcmp("1", block) && active_clients)
611     {
612         // if there is already a watch/block. we do not block this one
613         if (session_set_watch(s->psession, SESSION_WATCH_TERMLIST,
614                               termlist_result_ready, c, c) != 0)
615         {
616             session_log(s->psession, YLOG_WARN, "Attempt to block "
617                         "multiple times on termlist block. Not supported!");
618             if (report_error) {
619                 error(rs, PAZPAR2_ALREADY_BLOCKED, "termlist");
620                 release_session(c, s);
621                 return;
622             }
623             else if (report_status)
624                 status_message = "WARNING (Already blocked on termlist)";
625             else
626                 session_log(s->psession, YLOG_WARN,
627                             "Ignoring termlist block. Return current result");
628         }
629         else
630         {
631             session_log(s->psession, c->http_sessions->log_level,
632                         "Blocking on command termlist");
633             release_session(c, s);
634             return;
635         }
636     }
637
638     termlist_response(c, s, status_message);
639     release_session(c, s);
640 }
641
642 size_t session_get_memory_status(struct session *session);
643
644 static void session_status(struct http_channel *c, struct http_session *s)
645 {
646     size_t session_nmem;
647     wrbuf_printf(c->wrbuf, "<http_count>%u</http_count>\n", s->activity_counter);
648     wrbuf_printf(c->wrbuf, "<http_nmem>%zu</http_nmem>\n", nmem_total(s->nmem) );
649     session_nmem = session_get_memory_status(s->psession);
650     wrbuf_printf(c->wrbuf, "<session_nmem>%zu</session_nmem>\n", session_nmem);
651 }
652
653 static void cmd_service(struct http_channel *c)
654 {
655     struct http_session *s = locate_session(c);
656     xmlNode *xml_node;
657     if (!s)
658         return;
659
660     response_open_command(c, 0);
661     xml_node = s->psession->service->xml_node;
662     if (xml_node)
663     {
664         xmlNode *tmp = xmlCopyNode(xml_node, 1);
665         xmlBufferPtr buf = xmlBufferCreate();
666
667         xmlNodeDump(buf, tmp->doc, tmp, 0, 0);
668
669         wrbuf_write(c->wrbuf, (const char *) buf->content, buf->use);
670         xmlBufferFree(buf);
671         xmlFreeNode(tmp);
672     }
673
674     response_close(c, 0);
675     release_session(c, s);
676 }
677
678 static void cmd_session_status(struct http_channel *c)
679 {
680     struct http_session *s = locate_session(c);
681     if (!s)
682         return;
683
684     response_open_ok(c, "session-status");
685     session_status(c, s);
686     response_close(c, "session-status");
687     release_session(c, s);
688 }
689
690 int sessions_count(void);
691 int clients_count(void);
692 #ifdef HAVE_RESULTSETS_COUNT
693 int resultsets_count(void);
694 #else
695 #define resultsets_count()      0
696 #endif
697
698 static void cmd_server_status(struct http_channel *c)
699 {
700     int sessions   = sessions_count();
701     int clients    = clients_count();
702     int resultsets = resultsets_count();
703
704     response_open_ok(c, "server-status");
705     wrbuf_printf(c->wrbuf, "\n  <sessions>%u</sessions>\n", sessions);
706     wrbuf_printf(c->wrbuf, "  <clients>%u</clients>\n",   clients);
707     /* Only works if yaz has been compiled with enabling of this */
708     wrbuf_printf(c->wrbuf, "  <resultsets>%u</resultsets>\n",resultsets);
709     print_meminfo(c->wrbuf);
710
711 /* TODO add all sessions status                         */
712 /*    http_sessions_t http_sessions = c->http_sessions; */
713 /*    struct http_session *p;                           */
714 /*
715     yaz_mutex_enter(http_sessions->mutex);
716     for (p = http_sessions->session_list; p; p = p->next)
717     {
718         p->activity_counter++;
719         wrbuf_puts(c->wrbuf, "<session-status>\n");
720         wrbuf_printf(c->wrbuf, "<id>%s</id>\n", p->session_id);
721         yaz_mutex_leave(http_sessions->mutex);
722         session_status(c, p);
723         wrbuf_puts(c->wrbuf, "</session-status>\n");
724         yaz_mutex_enter(http_sessions->mutex);
725         p->activity_counter--;
726     }
727     yaz_mutex_leave(http_sessions->mutex);
728 */
729     response_close(c, "server-status");
730     xmalloc_trav(0);
731 }
732
733 static void bytarget_response(struct http_channel *c, struct http_session *s, const char *cmd_status) {
734     int count, i;
735     struct hitsbytarget *ht;
736     struct http_request *rq = c->request;
737     const char *settings = http_argbyname(rq, "settings");
738     int version = get_version(rq);
739     ht = get_hitsbytarget(s->psession, &count, c->nmem);
740     if (!cmd_status)
741         /* Old protocol, always ok */
742         response_open_ok(c, "bytarget");
743     else {
744         /* New protocol, OK or WARNING (...)*/
745         response_open_command(c, "bytarget");
746         wrbuf_printf(c->wrbuf, "<status>%s</status>", cmd_status);
747     }
748
749     if (count == 0)
750         session_log(s->psession, YLOG_WARN,
751                     "Empty bytarget Response. No targets found!");
752     for (i = 0; i < count; i++)
753     {
754         wrbuf_puts(c->wrbuf, "\n<target>");
755
756         wrbuf_puts(c->wrbuf, "<id>");
757         wrbuf_xmlputs(c->wrbuf, ht[i].id);
758         wrbuf_puts(c->wrbuf, "</id>\n");
759
760         if (ht[i].name && ht[i].name[0])
761         {
762             wrbuf_puts(c->wrbuf, "<name>");
763             wrbuf_xmlputs(c->wrbuf, ht[i].name);
764             wrbuf_puts(c->wrbuf, "</name>\n");
765         }
766
767         wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", ht[i].hits);
768         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
769         if (ht[i].diagnostic)
770         {
771             wrbuf_puts(c->wrbuf, "<message>");
772             wrbuf_xmlputs(c->wrbuf, ht[i].message);
773             wrbuf_puts(c->wrbuf, "</message>\n");
774             wrbuf_puts(c->wrbuf, "<addinfo>");
775             if (ht[i].addinfo)
776                 wrbuf_xmlputs(c->wrbuf, ht[i].addinfo);
777             wrbuf_puts(c->wrbuf, "</addinfo>\n");
778         }
779
780         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records - ht[i].filtered);
781         if (version >= 2) {
782             wrbuf_printf(c->wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
783             wrbuf_printf(c->wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", ht[i].approximation);
784         }
785         wrbuf_puts(c->wrbuf, "<state>");
786         wrbuf_xmlputs(c->wrbuf, ht[i].state);
787         wrbuf_puts(c->wrbuf, "</state>\n");
788         if (settings && *settings == '1')
789         {
790             wrbuf_puts(c->wrbuf, "<settings>\n");
791             wrbuf_puts(c->wrbuf, ht[i].settings_xml);
792             wrbuf_puts(c->wrbuf, "</settings>\n");
793         }
794         if (ht[i].suggestions_xml && ht[i].suggestions_xml[0]) {
795             wrbuf_puts(c->wrbuf, "<suggestions>");
796             wrbuf_puts(c->wrbuf, ht[i].suggestions_xml);
797             wrbuf_puts(c->wrbuf, "</suggestions>");
798         }
799         wrbuf_puts(c->wrbuf, "</target>");
800     }
801     response_close(c, "bytarget");
802 }
803
804 static void bytarget_result_ready(void *data)
805 {
806     struct http_channel *c = (struct http_channel *) data;
807     struct http_session *s = locate_session(c);
808     const char *status_message = "OK";
809     if (s)
810     {
811         session_log(s->psession, c->http_sessions->log_level,
812                     "bytarget watch released");
813         bytarget_response(c, s, status_message);
814         release_session(c, s);
815     }
816     else
817         yaz_log(c->http_sessions->log_level,
818                 "No Session found for released bytarget watch");
819 }
820
821
822 static void cmd_bytarget(struct http_channel *c)
823 {
824     struct http_request *rq = c->request;
825     struct http_response *rs = c->response;
826     struct http_session *s = locate_session(c);
827     const char *block = http_argbyname(rq, "block");
828     const char *report = http_argbyname(rq, "report");
829     int report_error = 0;
830     int report_status = 0;
831     const char *status_message = "OK";
832     int no_active;
833
834     if (report && !strcmp("error", report))
835         report_error = 1;
836     if (report && !strcmp("status", report))
837         report_status = 1;
838
839     if (!s)
840         return;
841
842     no_active = session_active_clients(s->psession);
843     if (block && !strcmp("1", block) && no_active)
844     {
845         // if there is already a watch/block. we do not block this one
846         if (session_set_watch(s->psession, SESSION_WATCH_BYTARGET,
847                               bytarget_result_ready, c, c) != 0)
848         {
849             session_log(s->psession, YLOG_WARN, "Attempt to block "
850                         "multiple times on bytarget block. Not supported!");
851             if (report_error)
852             {
853                 error(rs, PAZPAR2_ALREADY_BLOCKED, "bytarget");
854                 release_session(c, s);
855                 return;
856             }
857             else if (report_status)
858                 status_message = "WARNING (Already blocked on bytarget)";
859             else {
860                 session_log(s->psession, YLOG_WARN, "Ignoring bytarget block."
861                             " Return current result.");
862             }
863         }
864         else
865         {
866             session_log(s->psession, c->http_sessions->log_level,
867                         "Blocking on command bytarget");
868             release_session(c, s);
869             return;
870         }
871     }
872     bytarget_response(c, s, status_message);
873     release_session(c, s);
874 }
875
876 static void write_metadata(WRBUF w, struct conf_service *service,
877                            struct record_metadata **ml, int full, int indent)
878 {
879     int imeta;
880
881     for (imeta = 0; imeta < service->num_metadata; imeta++)
882     {
883         struct conf_metadata *cmd = &service->metadata[imeta];
884         struct record_metadata *md;
885         if (!cmd->brief && !full)
886             continue;
887         for (md = ml[imeta]; md; md = md->next)
888         {
889             struct record_metadata_attr *attr = md->attributes;
890             int i;
891             for (i = 0; i < indent; i++)
892                 wrbuf_putc(w, ' ');
893             wrbuf_printf(w, "<md-%s", cmd->name);
894
895             for (; attr; attr = attr->next)
896             {
897                 wrbuf_printf(w, " %s=\"", attr->name);
898                 wrbuf_xmlputs(w, attr->value);
899                 wrbuf_puts(w, "\"");
900             }
901             wrbuf_puts(w, ">");
902             switch (cmd->type)
903             {
904                 case Metadata_type_generic:
905                     wrbuf_xmlputs(w, md->data.text.disp);
906                     break;
907                 case Metadata_type_year:
908                     wrbuf_printf(w, "%d", md->data.number.min);
909                     if (md->data.number.min != md->data.number.max)
910                         wrbuf_printf(w, "-%d", md->data.number.max);
911                     break;
912                 default:
913                     wrbuf_puts(w, "[can't represent]");
914                     break;
915             }
916             wrbuf_printf(w, "</md-%s>\n", cmd->name);
917         }
918     }
919 }
920
921 static void write_subrecord(struct record *r, WRBUF w,
922         struct conf_service *service, int show_details)
923 {
924     const char *name = session_setting_oneval(
925         client_get_database(r->client), PZ_NAME);
926
927     wrbuf_puts(w, " <location id=\"");
928     wrbuf_xmlputs(w, client_get_id(r->client));
929     wrbuf_puts(w, "\"\n");
930
931     wrbuf_puts(w, "    name=\"");
932     wrbuf_xmlputs(w,  *name ? name : "Unknown");
933     wrbuf_puts(w, "\" ");
934
935     wrbuf_puts(w, "checksum=\"");
936     wrbuf_printf(w,  "%u", r->checksum);
937     wrbuf_puts(w, "\">\n");
938
939     write_metadata(w, service, r->metadata, show_details, 2);
940     wrbuf_puts(w, " </location>\n");
941 }
942
943 static void show_raw_record_error(void *data, const char *addinfo)
944 {
945     http_channel_observer_t obs = data;
946     struct http_channel *c = http_channel_observer_chan(obs);
947     struct http_response *rs = c->response;
948
949     http_remove_observer(obs);
950
951     error(rs, PAZPAR2_RECORD_FAIL, addinfo);
952 }
953
954 static void show_raw_record_ok(void *data, const char *buf, size_t sz)
955 {
956     http_channel_observer_t obs = data;
957     struct http_channel *c = http_channel_observer_chan(obs);
958     struct http_response *rs = c->response;
959
960     http_remove_observer(obs);
961
962     wrbuf_write(c->wrbuf, buf, sz);
963     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
964     http_send_response(c);
965 }
966
967
968 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
969 {
970     http_channel_observer_t obs = data;
971     struct http_channel *c = http_channel_observer_chan(obs);
972     struct http_response *rs = c->response;
973
974     http_remove_observer(obs);
975
976     wrbuf_write(c->wrbuf, buf, sz);
977     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
978
979     rs->content_type = "application/octet-stream";
980     http_send_response(c);
981 }
982
983
984 void show_raw_reset(void *data, struct http_channel *c, void *data2)
985 {
986     //struct client *client = data;
987     //client_show_raw_remove(client, data2);
988 }
989
990 static void cmd_record_ready(void *data);
991
992 static void show_record(struct http_channel *c, struct http_session *s)
993 {
994     struct http_response *rs = c->response;
995     struct http_request *rq = c->request;
996     struct record_cluster *rec, *prev_r, *next_r;
997     struct conf_service *service;
998     const char *idstr = http_argbyname(rq, "id");
999     const char *offsetstr = http_argbyname(rq, "offset");
1000     const char *binarystr = http_argbyname(rq, "binary");
1001     const char *checksumstr = http_argbyname(rq, "checksum");
1002
1003     if (!s)
1004         return;
1005     service = s->psession->service;
1006     if (!idstr)
1007     {
1008         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
1009         return;
1010     }
1011     wrbuf_rewind(c->wrbuf);
1012     if (!(rec = show_single_start(s->psession, idstr, &prev_r, &next_r)))
1013     {
1014         if (session_active_clients(s->psession) == 0)
1015         {
1016             error(rs, PAZPAR2_RECORD_MISSING, idstr);
1017         }
1018         else if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
1019                               cmd_record_ready, c, c) != 0)
1020         {
1021             error(rs, PAZPAR2_RECORD_MISSING, idstr);
1022         }
1023         return;
1024     }
1025     if (offsetstr || checksumstr)
1026     {
1027         const char *syntax = http_argbyname(rq, "syntax");
1028         const char *esn = http_argbyname(rq, "esn");
1029         int i;
1030         struct record*r = rec->records;
1031         int binary = 0;
1032         const char *nativesyntax = http_argbyname(rq, "nativesyntax");
1033
1034         if (binarystr && *binarystr != '0')
1035             binary = 1;
1036
1037         if (checksumstr)
1038         {
1039             unsigned v = strtoul(checksumstr, 0, 10);
1040             for (i = 0; r; r = r->next)
1041                 if (v == r->checksum)
1042                     break;
1043             if (!r)
1044                 error(rs, PAZPAR2_RECORD_FAIL, "no record");
1045         }
1046         else
1047         {
1048             int offset = atoi(offsetstr);
1049             for (i = 0; i < offset && r; r = r->next, i++)
1050                 ;
1051             if (!r)
1052                 error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
1053         }
1054         if (r)
1055         {
1056             http_channel_observer_t obs =
1057                 http_add_observer(c, r->client, show_raw_reset);
1058             int ret = client_show_raw_begin(r->client, r->position,
1059                                             syntax, esn,
1060                                             obs /* data */,
1061                                             show_raw_record_error,
1062                                             (binary ?
1063                                              show_raw_record_ok_binary :
1064                                              show_raw_record_ok),
1065                                             (binary ? 1 : 0),
1066                                             nativesyntax);
1067             if (ret == -1)
1068             {
1069                 http_remove_observer(obs);
1070                 error(rs, PAZPAR2_NO_SESSION, 0);
1071             }
1072         }
1073     }
1074     else
1075     {
1076         struct record *r;
1077         response_open_command(c, "record");
1078         wrbuf_puts(c->wrbuf, "\n <recid>");
1079         wrbuf_xmlputs(c->wrbuf, rec->recid);
1080         wrbuf_puts(c->wrbuf, "</recid>\n");
1081         if (prev_r)
1082         {
1083             wrbuf_puts(c->wrbuf, " <prevrecid>");
1084             wrbuf_xmlputs(c->wrbuf, prev_r->recid);
1085             wrbuf_puts(c->wrbuf, "</prevrecid>\n");
1086         }
1087         if (next_r)
1088         {
1089             wrbuf_puts(c->wrbuf, " <nextrecid>");
1090             wrbuf_xmlputs(c->wrbuf, next_r->recid);
1091             wrbuf_puts(c->wrbuf, "</nextrecid>\n");
1092         }
1093         wrbuf_printf(c->wrbuf, " <activeclients>%d</activeclients>\n",
1094                      session_active_clients(s->psession));
1095         write_metadata(c->wrbuf, service, rec->metadata, 1, 1);
1096         for (r = rec->records; r; r = r->next)
1097             write_subrecord(r, c->wrbuf, service, 2);
1098         response_close(c, "record");
1099     }
1100     show_single_stop(s->psession, rec);
1101 }
1102
1103 static void cmd_record_ready(void *data)
1104 {
1105     struct http_channel *c = (struct http_channel *) data;
1106     struct http_session *s = locate_session(c);
1107     if (s)
1108     {
1109         session_log(s->psession, c->http_sessions->log_level,
1110                     "record watch released");
1111         show_record(c, s);
1112         release_session(c,s);
1113     }
1114 }
1115
1116 static void cmd_record(struct http_channel *c)
1117 {
1118     struct http_session *s = locate_session(c);
1119     if (s) {
1120         show_record(c, s);
1121         release_session(c,s);
1122     }
1123 }
1124
1125
1126 static void show_records(struct http_channel *c, struct http_session *s, int active)
1127 {
1128     struct http_request *rq = c->request;
1129     struct http_response *rs = c->response;
1130     struct record_cluster **rl;
1131     struct reclist_sortparms *sp;
1132     const char *start = http_argbyname(rq, "start");
1133     const char *num = http_argbyname(rq, "num");
1134     const char *sort = http_argbyname(rq, "sort");
1135     int version = get_version(rq);
1136
1137     int startn = 0;
1138     int numn = 20;
1139     int total;
1140     Odr_int total_hits;
1141     Odr_int approx_hits;
1142     int i;
1143     struct conf_service *service = 0;
1144     if (!s)
1145         return;
1146
1147     // We haven't counted clients yet if we're called on a block release
1148     if (active < 0)
1149         active = session_active_clients(s->psession);
1150
1151     if (start)
1152         startn = atoi(start);
1153     if (num)
1154         numn = atoi(num);
1155
1156     service = s->psession->service;
1157     if (!sort) {
1158         sort = service->default_sort;
1159     }
1160     if (!(sp = reclist_parse_sortparms(c->nmem, sort, service)))
1161     {
1162         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
1163         return;
1164
1165     }
1166
1167     rl = show_range_start(s->psession, sp, startn, &numn, &total,
1168                           &total_hits, &approx_hits, show_records_ready, c);
1169     if (!rl)
1170         return;
1171
1172     response_open_ok(c, "show");
1173     wrbuf_printf(c->wrbuf, "\n<activeclients>%d</activeclients>\n", active);
1174     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
1175     wrbuf_printf(c->wrbuf, "<total>" ODR_INT_PRINTF "</total>\n", total_hits);
1176     if (version >= 2) {
1177         wrbuf_printf(c->wrbuf, "<approximation>" ODR_INT_PRINTF "</approximation>\n", approx_hits);
1178     }
1179     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
1180     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
1181
1182     for (i = 0; i < numn; i++)
1183     {
1184         int ccount;
1185         struct record *p;
1186         struct record_cluster *rec = rl[i];
1187         struct conf_service *service = s->psession->service;
1188
1189         wrbuf_puts(c->wrbuf, "<hit>\n");
1190         write_metadata(c->wrbuf, service, rec->metadata, 0, 1);
1191         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
1192             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
1193         wrbuf_printf(c->wrbuf, " <count>%d</count>\n", ccount);
1194         if (strstr(sort, "relevance"))
1195         {
1196             wrbuf_printf(c->wrbuf, " <relevance>%d</relevance>\n",
1197                          rec->relevance_score);
1198             if (service->rank_debug)
1199             {
1200                 wrbuf_printf(c->wrbuf, " <relevance_info>\n");
1201                 wrbuf_xmlputs(c->wrbuf, wrbuf_cstr(rec->relevance_explain1));
1202                 wrbuf_xmlputs(c->wrbuf, wrbuf_cstr(rec->relevance_explain2));
1203                 wrbuf_printf(c->wrbuf, " </relevance_info>\n");
1204             }
1205         }
1206         wrbuf_puts(c->wrbuf, " <recid>");
1207         wrbuf_xmlputs(c->wrbuf, rec->recid);
1208         wrbuf_puts(c->wrbuf, "</recid>\n");
1209         wrbuf_puts(c->wrbuf, "</hit>\n");
1210     }
1211
1212     show_range_stop(s->psession, rl);
1213
1214     response_close(c, "show");
1215 }
1216
1217 static void show_records_ready(void *data)
1218 {
1219     struct http_channel *c = (struct http_channel *) data;
1220     struct http_session *s = locate_session(c);
1221     if (s)
1222     {
1223         session_log(s->psession, c->http_sessions->log_level,
1224                     "show watch released");
1225         show_records(c, s, -1);
1226     }
1227     else {
1228         /* some error message  */
1229     }
1230     release_session(c,s);
1231 }
1232
1233 static void cmd_show(struct http_channel *c)
1234 {
1235     struct http_request  *rq = c->request;
1236     struct http_response *rs = c->response;
1237     struct http_session *s = locate_session(c);
1238     const char *block = http_argbyname(rq, "block");
1239     const char *sort = http_argbyname(rq, "sort");
1240     const char *block_error = http_argbyname(rq, "report");
1241     const char *mergekey = http_argbyname(rq, "mergekey");
1242     const char *rank = http_argbyname(rq, "rank");
1243     struct conf_service *service = 0;
1244
1245     struct reclist_sortparms *sp;
1246     int status;
1247     int report_error = 0;
1248     if (block_error && !strcmp("1", block_error)) {
1249         report_error = 1;
1250     }
1251     if (!s)
1252         return;
1253
1254     service = s->psession->service;
1255     if (!sort) {
1256         sort = service->default_sort;
1257     }
1258
1259     if (!(sp = reclist_parse_sortparms(c->nmem, sort, service)))
1260     {
1261         error(c->response, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
1262         release_session(c, s);
1263         return;
1264     }
1265     session_sort(s->psession, sp, mergekey, rank);
1266
1267     status = session_active_clients(s->psession);
1268
1269     if (block)
1270     {
1271         if (!strcmp(block, "preferred") && !session_is_preferred_clients_ready(s->psession) && reclist_get_num_records(s->psession->reclist) == 0)
1272         {
1273             // if there is already a watch/block. we do not block this one
1274             if (session_set_watch(s->psession, SESSION_WATCH_SHOW_PREF,
1275                                   show_records_ready, c, c) == 0)
1276             {
1277                 session_log(s->psession, c->http_sessions->log_level,
1278                             "Blocking on command show (preferred targets)");
1279                 release_session(c, s);
1280                 return;
1281             }
1282             else
1283             {
1284                 session_log(s->psession, YLOG_WARN, "Attempt to block"
1285                             " multiple times on show (preferred targets) block."
1286                             " Not supported!");
1287                 if (report_error)
1288                 {
1289                     error(rs, PAZPAR2_ALREADY_BLOCKED,
1290                           "show (preferred targets)");
1291                     release_session(c, s);
1292                     return;
1293                 }
1294                 else
1295                     session_log(s->psession, YLOG_WARN,
1296                                 "Ignoring show(preferred) block."
1297                                 " Returning current result");
1298             }
1299
1300         }
1301         else if (status)
1302         {
1303             // if there is already a watch/block. we do not block this one
1304             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
1305                                   show_records_ready, c, c) != 0)
1306             {
1307                 session_log(s->psession, YLOG_WARN, "Attempt to block"
1308                             " multiple times on show block. Not supported!");
1309                 if (report_error)
1310                 {
1311                     error(rs, PAZPAR2_ALREADY_BLOCKED, "show");
1312                     release_session(c, s);
1313                     return;
1314                 }
1315                 else
1316                     session_log(s->psession, YLOG_WARN, "Ignoring show block."
1317                                 " Returning current result");
1318             }
1319             else
1320             {
1321                 session_log(s->psession, c->http_sessions->log_level,
1322                             "Blocking on command show");
1323                 release_session(c, s);
1324                 return;
1325             }
1326         }
1327     }
1328     show_records(c, s, status);
1329     release_session(c, s);
1330 }
1331
1332 static void cmd_ping(struct http_channel *c)
1333 {
1334     struct http_session *s = locate_session(c);
1335     if (!s)
1336         return;
1337     response_open_ok(c, "ping");
1338     response_close(c, "ping");
1339     release_session(c, s);
1340 }
1341
1342 static void cmd_search(struct http_channel *c)
1343 {
1344     struct http_request *rq = c->request;
1345     struct http_response *rs = c->response;
1346     struct http_session *s = locate_session(c);
1347     const char *query = http_argbyname(rq, "query");
1348     const char *filter = http_argbyname(rq, "filter");
1349     const char *maxrecs = http_argbyname(rq, "maxrecs");
1350     const char *startrecs = http_argbyname(rq, "startrecs");
1351     const char *limit = http_argbyname(rq, "limit");
1352     const char *sort = http_argbyname(rq, "sort");
1353     const char *mergekey = http_argbyname(rq, "mergekey");
1354     const char *rank = http_argbyname(rq, "rank");
1355     enum pazpar2_error_code code;
1356     const char *addinfo = 0;
1357     struct reclist_sortparms *sp;
1358     struct conf_service *service = 0;
1359
1360     if (!s)
1361         return;
1362
1363     if (!query)
1364     {
1365         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
1366         release_session(c, s);
1367         return;
1368     }
1369     if (!yaz_utf8_check(query))
1370     {
1371         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
1372         release_session(c, s);
1373         return;
1374     }
1375     service = s->psession->service;
1376     if (!sort) {
1377         sort = service->default_sort;
1378     }
1379     if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
1380     {
1381         error(c->response, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
1382         release_session(c, s);
1383         return;
1384     }
1385
1386     code = session_search(s->psession, query, startrecs, maxrecs, filter, limit,
1387                           &addinfo, sp, mergekey, rank);
1388     if (code)
1389     {
1390         error(rs, code, addinfo);
1391         release_session(c, s);
1392         return;
1393     }
1394     response_open_ok(c, "search");
1395     response_close(c, "search");
1396     release_session(c, s);
1397 }
1398
1399
1400 static void cmd_stat(struct http_channel *c)
1401 {
1402     struct http_session *s = locate_session(c);
1403     struct statistics stat;
1404     int clients;
1405
1406     float progress = 0;
1407
1408     if (!s)
1409         return;
1410
1411     clients = session_active_clients(s->psession);
1412     statistics(s->psession, &stat);
1413
1414     if (stat.num_clients > 0)
1415     {
1416         progress = (stat.num_clients  - clients) / (float)stat.num_clients;
1417     }
1418
1419     response_open_command(c, "stat");
1420     wrbuf_printf(c->wrbuf, "\n <activeclients>%d</activeclients>\n", clients);
1421     wrbuf_printf(c->wrbuf, " <hits>" ODR_INT_PRINTF "</hits>\n", stat.num_hits);
1422     wrbuf_printf(c->wrbuf, " <records>%d</records>\n", stat.num_records);
1423     wrbuf_printf(c->wrbuf, " <clients>%d</clients>\n", stat.num_clients);
1424     wrbuf_printf(c->wrbuf, " <unconnected>%d</unconnected>\n", stat.num_no_connection);
1425     wrbuf_printf(c->wrbuf, " <connecting>%d</connecting>\n", stat.num_connecting);
1426     wrbuf_printf(c->wrbuf, " <working>%d</working>\n", stat.num_working);
1427     wrbuf_printf(c->wrbuf, " <idle>%d</idle>\n", stat.num_idle);
1428     wrbuf_printf(c->wrbuf, " <failed>%d</failed>\n", stat.num_failed);
1429     wrbuf_printf(c->wrbuf, " <error>%d</error>\n", stat.num_error);
1430     wrbuf_printf(c->wrbuf, " <progress>%.2f</progress>\n", progress);
1431     response_close(c, "stat");
1432     release_session(c, s);
1433 }
1434
1435 static void cmd_info(struct http_channel *c)
1436 {
1437     char yaz_version_str[20];
1438     char yaz_sha1_str[42];
1439
1440     response_open_command(c, "info");
1441     wrbuf_puts(c->wrbuf, "\n <version>\n");
1442     wrbuf_puts(c->wrbuf, "  <pazpar2");
1443 #ifdef PAZPAR2_VERSION_SHA1
1444     wrbuf_printf(c->wrbuf, " sha1=\"%s\"", PAZPAR2_VERSION_SHA1);
1445 #endif
1446     wrbuf_puts(c->wrbuf, ">");
1447     wrbuf_xmlputs(c->wrbuf, VERSION);
1448     wrbuf_puts(c->wrbuf, "</pazpar2>\n");
1449
1450     yaz_version(yaz_version_str, yaz_sha1_str);
1451     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
1452     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
1453     wrbuf_puts(c->wrbuf, "\" sha1=\"");
1454     wrbuf_xmlputs(c->wrbuf, yaz_sha1_str);
1455     wrbuf_puts(c->wrbuf, "\">");
1456     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
1457     wrbuf_puts(c->wrbuf, "</yaz>\n");
1458
1459     wrbuf_puts(c->wrbuf, " </version>\n");
1460 #if HAVE_UNISTD_H
1461     {
1462         char hostname_str[64];
1463         if (gethostname(hostname_str, sizeof(hostname_str)) == 0)
1464         {
1465             wrbuf_puts(c->wrbuf, " <host>");
1466             wrbuf_xmlputs(c->wrbuf, hostname_str);
1467             wrbuf_puts(c->wrbuf, "</host>\n");
1468         }
1469     }
1470 #endif
1471     info_services(c->server, c->wrbuf);
1472
1473     response_close(c, "info");
1474 }
1475
1476 struct {
1477     char *name;
1478     void (*fun)(struct http_channel *c);
1479 } commands[] = {
1480     { "init", cmd_init },
1481     { "settings", cmd_settings },
1482     { "stat", cmd_stat },
1483     { "bytarget", cmd_bytarget },
1484     { "show", cmd_show },
1485     { "search", cmd_search },
1486     { "termlist", cmd_termlist },
1487     { "exit", cmd_exit },
1488     { "session-status", cmd_session_status },
1489     { "server-status", cmd_server_status },
1490     { "service", cmd_service },
1491     { "ping", cmd_ping },
1492     { "record", cmd_record },
1493     { "info", cmd_info },
1494     {0,0}
1495 };
1496
1497 void http_command(struct http_channel *c)
1498 {
1499     const char *command = http_argbyname(c->request, "command");
1500     struct http_response *rs = http_create_response(c);
1501     int i;
1502
1503     c->response = rs;
1504
1505     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
1506     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
1507
1508     if (!command)
1509     {
1510         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
1511         return;
1512     }
1513     for (i = 0; commands[i].name; i++)
1514         if (!strcmp(commands[i].name, command))
1515         {
1516             (*commands[i].fun)(c);
1517             break;
1518         }
1519     if (!commands[i].name)
1520         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
1521
1522     return;
1523 }
1524
1525 /*
1526  * Local variables:
1527  * c-basic-offset: 4
1528  * c-file-style: "Stroustrup"
1529  * indent-tabs-mode: nil
1530  * End:
1531  * vim: shiftwidth=4 tabstop=8 expandtab
1532  */
1533