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