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