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