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