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