Remove unused code in server-status
[pazpar2-moved-to-github.git] / src / http_command.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 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 = session_create(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     NMEM nmem = nmem_create();
405
406     for (a = rq->arguments; a; a = a->next)
407         if (strchr(a->name, '['))
408         {
409             char **res;
410             int num;
411             char *dbname;
412             char *setting;
413
414             // Nmem_strsplit *rules*!!!
415             nmem_strsplit(nmem, "[]", a->name, &res, &num);
416             if (num != 2)
417             {
418                 error(rs, PAZPAR2_MALFORMED_SETTING, a->name);
419                 nmem_destroy(nmem);
420                 return -1;
421             }
422             setting = res[0];
423             dbname = res[1];
424             session_apply_setting(se, dbname, setting, a->value);
425         }
426     nmem_destroy(nmem);
427     return 0;
428 }
429
430 static void cmd_exit(struct http_channel *c)
431 {
432     yaz_log(YLOG_WARN, "exit");
433
434     response_open_ok(c, "exit");
435     response_close(c, "exit");
436     if (global_parameters.debug_mode)
437         http_close_server(c->server);
438 }
439
440 static void cmd_init(struct http_channel *c)
441 {
442     struct http_request *r = c->request;
443     const char *clear = http_argbyname(r, "clear");
444     const char *content_type = http_lookup_header(r->headers, "Content-Type");
445     unsigned int sesid;
446     struct http_session *s;
447     struct http_response *rs = c->response;
448     struct conf_service *service = 0; /* no service (yet) */
449
450     if (r->content_len && content_type &&
451         !yaz_strcmp_del("text/xml", content_type, "; "))
452     {
453         xmlDoc *doc = xmlParseMemory(r->content_buf, r->content_len);
454         xmlNode *root_n;
455         if (!doc)
456         {
457             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
458             return;
459         }
460         root_n = xmlDocGetRootElement(doc);
461         service = service_create(c->server, root_n);
462         xmlFreeDoc(doc);
463         if (!service)
464         {
465             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
466             return;
467         }
468     }
469
470     if (!service)
471     {
472         const char *service_name = http_argbyname(c->request, "service");
473         service = locate_service(c->server, service_name);
474         if (!service)
475         {
476             error(rs, PAZPAR2_NO_SERVICE, service_name ? service_name : "unnamed");
477             return;
478         }
479     }
480     sesid = make_sessionid();
481     s = http_session_create(service, c->http_sessions, sesid);
482
483     if (!clear || *clear == '0')
484         session_init_databases(s->psession);
485     else
486         session_log(s->psession, YLOG_LOG, "No databases preloaded");
487
488     if (process_settings(s->psession, c->request, c->response) < 0)
489         return;
490
491     response_open_ok(c, "init");
492     wrbuf_printf(c->wrbuf, "<session>%d", sesid);
493     if (c->server->server_id)
494     {
495         wrbuf_puts(c->wrbuf, ".");
496         wrbuf_puts(c->wrbuf, c->server->server_id);
497     }
498     wrbuf_puts(c->wrbuf, "</session>"
499                "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol>");
500
501     wrbuf_printf(c->wrbuf, "<keepAlive>%d</keepAlive>\n",
502                  1000 * ((s->psession->service->session_timeout >= 20) ?
503                          (s->psession->service->session_timeout - 10) : 50));
504     response_close(c, "init");
505 }
506
507 static void apply_local_setting(void *client_data,
508                                 struct setting *set)
509 {
510     struct session *se =  (struct session *) client_data;
511
512     session_apply_setting(se, set->target, set->name, 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 static void cmd_server_status(struct http_channel *c)
698 {
699     int sessions   = sessions_count();
700     int clients    = clients_count();
701
702     response_open_ok(c, "server-status");
703
704     wrbuf_printf(c->wrbuf, "\n  <sessions>%d</sessions>\n", sessions);
705     wrbuf_printf(c->wrbuf, "  <clients>%d</clients>\n",   clients);
706     print_meminfo(c->wrbuf);
707
708     response_close(c, "server-status");
709     xmalloc_trav(0);
710 }
711
712 static void bytarget_response(struct http_channel *c, struct http_session *s,
713                               const char *cmd_status)
714 {
715     int count, i;
716     struct http_request *rq = c->request;
717     const char *settings = http_argbyname(rq, "settings");
718     int version = get_version(rq);
719     struct hitsbytarget *ht = get_hitsbytarget(s->psession, &count, c->nmem);
720
721     if (!cmd_status)
722         /* Old protocol, always ok */
723         response_open_ok(c, "bytarget");
724     else
725     {
726         /* New protocol, OK or WARNING (...)*/
727         response_open_command(c, "bytarget");
728         wrbuf_printf(c->wrbuf, "<status>%s</status>", cmd_status);
729     }
730
731     if (count == 0)
732         session_log(s->psession, YLOG_WARN,
733                     "Empty bytarget Response. No targets found!");
734     for (i = 0; i < count; i++)
735     {
736         wrbuf_puts(c->wrbuf, "\n<target>");
737
738         wrbuf_puts(c->wrbuf, "<id>");
739         wrbuf_xmlputs(c->wrbuf, ht[i].id);
740         wrbuf_puts(c->wrbuf, "</id>\n");
741
742         if (ht[i].name && ht[i].name[0])
743         {
744             wrbuf_puts(c->wrbuf, "<name>");
745             wrbuf_xmlputs(c->wrbuf, ht[i].name);
746             wrbuf_puts(c->wrbuf, "</name>\n");
747         }
748
749         wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", ht[i].hits);
750         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n",
751                      ht[i].diagnostic);
752         if (ht[i].diagnostic)
753         {
754             wrbuf_puts(c->wrbuf, "<message>");
755             wrbuf_xmlputs(c->wrbuf, ht[i].message);
756             wrbuf_puts(c->wrbuf, "</message>\n");
757             wrbuf_puts(c->wrbuf, "<addinfo>");
758             if (ht[i].addinfo)
759                 wrbuf_xmlputs(c->wrbuf, ht[i].addinfo);
760             wrbuf_puts(c->wrbuf, "</addinfo>\n");
761         }
762
763         wrbuf_printf(c->wrbuf, "<records>%d</records>\n",
764                      ht[i].records - ht[i].filtered);
765         wrbuf_printf(c->wrbuf, "<filtered>%d</filtered>\n", ht[i].filtered);
766         if (version >= 2)
767         {
768             wrbuf_printf(c->wrbuf, "<approximation>" ODR_INT_PRINTF
769                          "</approximation>\n", ht[i].approximation);
770         }
771         wrbuf_puts(c->wrbuf, "<state>");
772         wrbuf_xmlputs(c->wrbuf, ht[i].state);
773         wrbuf_puts(c->wrbuf, "</state>\n");
774         if (settings && *settings == '1')
775         {
776             wrbuf_puts(c->wrbuf, "<settings>\n");
777             wrbuf_puts(c->wrbuf, ht[i].settings_xml);
778             wrbuf_puts(c->wrbuf, "</settings>\n");
779         }
780         if (ht[i].suggestions_xml && ht[i].suggestions_xml[0])
781         {
782             wrbuf_puts(c->wrbuf, "<suggestions>");
783             wrbuf_puts(c->wrbuf, ht[i].suggestions_xml);
784             wrbuf_puts(c->wrbuf, "</suggestions>");
785         }
786         if (ht[i].query_data)
787         {
788             wrbuf_puts(c->wrbuf, "<query_type>");
789             wrbuf_xmlputs(c->wrbuf, ht[i].query_type);
790             wrbuf_puts(c->wrbuf, "</query_type>\n");
791             wrbuf_puts(c->wrbuf, "<query_data>");
792             wrbuf_xmlputs(c->wrbuf, ht[i].query_data);
793             wrbuf_puts(c->wrbuf, "</query_data>\n");
794         }
795         wrbuf_puts(c->wrbuf, "</target>");
796     }
797     response_close(c, "bytarget");
798 }
799
800 static void bytarget_result_ready(void *data)
801 {
802     struct http_channel *c = (struct http_channel *) data;
803     struct http_session *s = locate_session(c);
804     const char *status_message = "OK";
805     if (s)
806     {
807         session_log(s->psession, c->http_sessions->log_level,
808                     "bytarget watch released");
809         bytarget_response(c, s, status_message);
810         release_session(c, s);
811     }
812     else
813         yaz_log(c->http_sessions->log_level,
814                 "No Session found for released bytarget watch");
815 }
816
817
818 static void cmd_bytarget(struct http_channel *c)
819 {
820     struct http_request *rq = c->request;
821     struct http_response *rs = c->response;
822     struct http_session *s = locate_session(c);
823     const char *block = http_argbyname(rq, "block");
824     const char *report = http_argbyname(rq, "report");
825     int report_error = 0;
826     int report_status = 0;
827     const char *status_message = "OK";
828     int no_active;
829
830     if (report && !strcmp("error", report))
831         report_error = 1;
832     if (report && !strcmp("status", report))
833         report_status = 1;
834
835     if (!s)
836         return;
837
838     no_active = session_active_clients(s->psession);
839     if (block && !strcmp("1", block) && no_active)
840     {
841         // if there is already a watch/block. we do not block this one
842         if (session_set_watch(s->psession, SESSION_WATCH_BYTARGET,
843                               bytarget_result_ready, c, c) != 0)
844         {
845             session_log(s->psession, YLOG_WARN, "Attempt to block "
846                         "multiple times on bytarget block. Not supported!");
847             if (report_error)
848             {
849                 error(rs, PAZPAR2_ALREADY_BLOCKED, "bytarget");
850                 release_session(c, s);
851                 return;
852             }
853             else if (report_status)
854                 status_message = "WARNING (Already blocked on bytarget)";
855             else
856                 session_log(s->psession, YLOG_WARN, "Ignoring bytarget block."
857                             " Return current result.");
858         }
859         else
860         {
861             session_log(s->psession, c->http_sessions->log_level,
862                         "Blocking on command bytarget");
863             release_session(c, s);
864             return;
865         }
866     }
867     bytarget_response(c, s, status_message);
868     release_session(c, s);
869 }
870
871 static void write_metadata(WRBUF w, struct conf_service *service,
872                            struct record_metadata **ml, unsigned flags,
873                            int indent)
874 {
875     int imeta;
876
877     for (imeta = 0; imeta < service->num_metadata; imeta++)
878     {
879         struct conf_metadata *cmd = &service->metadata[imeta];
880         struct record_metadata *md;
881         if (!cmd->brief && !(flags & 1))
882             continue;
883         for (md = ml[imeta]; md; md = md->next)
884         {
885             struct record_metadata_attr *attr = md->attributes;
886             int i;
887             for (i = 0; i < indent; i++)
888                 wrbuf_putc(w, ' ');
889             wrbuf_printf(w, "<md-%s", cmd->name);
890
891             for (; attr; attr = attr->next)
892             {
893                 wrbuf_printf(w, " %s=\"", attr->name);
894                 wrbuf_xmlputs(w, attr->value);
895                 wrbuf_puts(w, "\"");
896             }
897             wrbuf_puts(w, ">");
898             switch (cmd->type)
899             {
900                 case Metadata_type_generic:
901                     if (md->data.text.snippet && (flags & 2))
902                         wrbuf_puts(w, md->data.text.snippet);
903                     else
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                 case Metadata_type_float:
912                     wrbuf_printf(w, "%f", md->data.fnumber);
913                     break;
914                 default:
915                     wrbuf_puts(w, "[can't represent]");
916                     break;
917             }
918             wrbuf_printf(w, "</md-%s>\n", cmd->name);
919         }
920     }
921 }
922
923 static void write_subrecord(struct record *r, WRBUF w,
924                             struct conf_service *service, unsigned flags,
925                             int indent)
926 {
927     const char *name = session_setting_oneval(
928         client_get_database(r->client), PZ_NAME);
929
930     wrbuf_puts(w, " <location id=\"");
931     wrbuf_xmlputs(w, client_get_id(r->client));
932     wrbuf_puts(w, "\"\n");
933
934     wrbuf_puts(w, "    name=\"");
935     wrbuf_xmlputs(w,  *name ? name : "Unknown");
936     wrbuf_puts(w, "\" ");
937
938     wrbuf_puts(w, "checksum=\"");
939     wrbuf_printf(w,  "%u", r->checksum);
940     wrbuf_puts(w, "\">\n");
941
942     write_metadata(w, service, r->metadata, flags, indent);
943     wrbuf_puts(w, " </location>\n");
944 }
945
946 static void show_raw_record_error(void *data, const char *addinfo)
947 {
948     http_channel_observer_t obs = data;
949     struct http_channel *c = http_channel_observer_chan(obs);
950     struct http_response *rs = c->response;
951
952     http_remove_observer(obs);
953
954     error(rs, PAZPAR2_RECORD_FAIL, addinfo);
955 }
956
957 static void show_raw_record_ok(void *data, const char *buf, size_t sz)
958 {
959     http_channel_observer_t obs = data;
960     struct http_channel *c = http_channel_observer_chan(obs);
961     struct http_response *rs = c->response;
962
963     http_remove_observer(obs);
964
965     wrbuf_write(c->wrbuf, buf, sz);
966     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
967     http_send_response(c);
968 }
969
970
971 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
972 {
973     http_channel_observer_t obs = data;
974     struct http_channel *c = http_channel_observer_chan(obs);
975     struct http_response *rs = c->response;
976
977     http_remove_observer(obs);
978
979     wrbuf_write(c->wrbuf, buf, sz);
980     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
981
982     rs->content_type = "application/octet-stream";
983     http_send_response(c);
984 }
985
986
987 void show_raw_reset(void *data, struct http_channel *c, void *data2)
988 {
989     //struct client *client = data;
990     //client_show_raw_remove(client, data2);
991 }
992
993 static void cmd_record_ready(void *data);
994
995 static void show_record(struct http_channel *c, struct http_session *s)
996 {
997     struct http_response *rs = c->response;
998     struct http_request *rq = c->request;
999     struct record_cluster *rec, *prev_r, *next_r;
1000     struct conf_service *service;
1001     const char *idstr = http_argbyname(rq, "id");
1002     const char *offsetstr = http_argbyname(rq, "offset");
1003     const char *binarystr = http_argbyname(rq, "binary");
1004     const char *checksumstr = http_argbyname(rq, "checksum");
1005     const char *snippets = http_argbyname(rq, "snippets");
1006     unsigned flags = (snippets && *snippets == '1') ? 3 : 1;
1007
1008     if (!s)
1009         return;
1010     service = s->psession->service;
1011     if (!idstr)
1012     {
1013         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
1014         return;
1015     }
1016     wrbuf_rewind(c->wrbuf);
1017     if (!(rec = show_single_start(s->psession, idstr, &prev_r, &next_r)))
1018     {
1019         if (session_active_clients(s->psession) == 0)
1020         {
1021             error(rs, PAZPAR2_RECORD_MISSING, idstr);
1022         }
1023         else if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
1024                               cmd_record_ready, c, c) != 0)
1025         {
1026             error(rs, PAZPAR2_RECORD_MISSING, idstr);
1027         }
1028         return;
1029     }
1030     if (offsetstr || checksumstr)
1031     {
1032         const char *syntax = http_argbyname(rq, "syntax");
1033         const char *esn = http_argbyname(rq, "esn");
1034         int i;
1035         struct record*r = rec->records;
1036         int binary = 0;
1037         const char *nativesyntax = http_argbyname(rq, "nativesyntax");
1038
1039         if (binarystr && *binarystr != '0')
1040             binary = 1;
1041
1042         if (checksumstr)
1043         {
1044             unsigned v = strtoul(checksumstr, 0, 10);
1045             for (i = 0; r; r = r->next)
1046                 if (v == r->checksum)
1047                     break;
1048             if (!r)
1049                 error(rs, PAZPAR2_RECORD_FAIL, "no record");
1050         }
1051         else
1052         {
1053             int offset = atoi(offsetstr);
1054             for (i = 0; i < offset && r; r = r->next, i++)
1055                 ;
1056             if (!r)
1057                 error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
1058         }
1059         if (r)
1060         {
1061             http_channel_observer_t obs =
1062                 http_add_observer(c, r->client, show_raw_reset);
1063             int ret = client_show_raw_begin(r->client, r->position,
1064                                             syntax, esn,
1065                                             obs /* data */,
1066                                             show_raw_record_error,
1067                                             (binary ?
1068                                              show_raw_record_ok_binary :
1069                                              show_raw_record_ok),
1070                                             (binary ? 1 : 0),
1071                                             nativesyntax);
1072             if (ret == -1)
1073             {
1074                 http_remove_observer(obs);
1075                 error(rs, PAZPAR2_NO_SESSION, 0);
1076             }
1077         }
1078     }
1079     else
1080     {
1081         struct record *r;
1082         response_open_command(c, "record");
1083         wrbuf_puts(c->wrbuf, "\n <recid>");
1084         wrbuf_xmlputs(c->wrbuf, rec->recid);
1085         wrbuf_puts(c->wrbuf, "</recid>\n");
1086         if (prev_r)
1087         {
1088             wrbuf_puts(c->wrbuf, " <prevrecid>");
1089             wrbuf_xmlputs(c->wrbuf, prev_r->recid);
1090             wrbuf_puts(c->wrbuf, "</prevrecid>\n");
1091         }
1092         if (next_r)
1093         {
1094             wrbuf_puts(c->wrbuf, " <nextrecid>");
1095             wrbuf_xmlputs(c->wrbuf, next_r->recid);
1096             wrbuf_puts(c->wrbuf, "</nextrecid>\n");
1097         }
1098         wrbuf_printf(c->wrbuf, " <activeclients>%d</activeclients>\n",
1099                      session_active_clients(s->psession));
1100         write_metadata(c->wrbuf, service, rec->metadata, flags, 1);
1101         for (r = rec->records; r; r = r->next)
1102             write_subrecord(r, c->wrbuf, service, flags, 2);
1103         response_close(c, "record");
1104     }
1105     show_single_stop(s->psession, rec);
1106 }
1107
1108 static void cmd_record_ready(void *data)
1109 {
1110     struct http_channel *c = (struct http_channel *) data;
1111     struct http_session *s = locate_session(c);
1112     if (s)
1113     {
1114         session_log(s->psession, c->http_sessions->log_level,
1115                     "record watch released");
1116         show_record(c, s);
1117         release_session(c, s);
1118     }
1119 }
1120
1121 static void cmd_record(struct http_channel *c)
1122 {
1123     struct http_session *s = locate_session(c);
1124     if (s)
1125     {
1126         show_record(c, s);
1127         release_session(c, s);
1128     }
1129 }
1130
1131
1132 static void show_records(struct http_channel *c, struct http_session *s,
1133                          int active)
1134 {
1135     struct http_request *rq = c->request;
1136     struct http_response *rs = c->response;
1137     struct record_cluster **rl;
1138     struct reclist_sortparms *sp;
1139     const char *start = http_argbyname(rq, "start");
1140     const char *num = http_argbyname(rq, "num");
1141     const char *sort = http_argbyname(rq, "sort");
1142     int version = get_version(rq);
1143     const char *snippets = http_argbyname(rq, "snippets");
1144     unsigned flags = (snippets && *snippets == '1') ? 2 : 0;
1145
1146     int startn = 0;
1147     int numn = 20;
1148     int total;
1149     Odr_int total_hits;
1150     Odr_int approx_hits;
1151     int i;
1152     struct conf_service *service = 0;
1153     if (!s)
1154         return;
1155
1156     // We haven't counted clients yet if we're called on a block release
1157     if (active < 0)
1158         active = session_active_clients(s->psession);
1159
1160     if (start)
1161         startn = atoi(start);
1162     if (num)
1163         numn = atoi(num);
1164
1165     service = s->psession->service;
1166     if (!sort)
1167         sort = service->default_sort;
1168     if (!(sp = reclist_parse_sortparms(c->nmem, sort, service)))
1169     {
1170         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
1171         return;
1172
1173     }
1174
1175     rl = show_range_start(s->psession, sp, startn, &numn, &total,
1176                           &total_hits, &approx_hits, show_records_ready, c);
1177     if (!rl)
1178         return;
1179
1180     response_open_ok(c, "show");
1181     wrbuf_printf(c->wrbuf, "\n<activeclients>%d</activeclients>\n", active);
1182     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
1183     wrbuf_printf(c->wrbuf, "<total>" ODR_INT_PRINTF "</total>\n", total_hits);
1184     if (version >= 2)
1185         wrbuf_printf(c->wrbuf, "<approximation>" ODR_INT_PRINTF
1186                      "</approximation>\n", approx_hits);
1187
1188     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
1189     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
1190
1191     for (i = 0; i < numn; i++)
1192     {
1193         int ccount;
1194         struct record *p;
1195         struct record_cluster *rec = rl[i];
1196         struct conf_service *service = s->psession->service;
1197
1198         wrbuf_puts(c->wrbuf, "<hit>\n");
1199         write_metadata(c->wrbuf, service, rec->metadata, flags, 1);
1200         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
1201             write_subrecord(p, c->wrbuf, service, flags, 2);
1202         wrbuf_printf(c->wrbuf, " <count>%d</count>\n", ccount);
1203         if (strstr(sort, "relevance"))
1204         {
1205             wrbuf_printf(c->wrbuf, " <relevance>%d</relevance>\n",
1206                          rec->relevance_score);
1207             if (service->rank_debug)
1208             {
1209                 wrbuf_printf(c->wrbuf, " <relevance_info>\n");
1210                 wrbuf_xmlputs(c->wrbuf, wrbuf_cstr(rec->relevance_explain1));
1211                 wrbuf_xmlputs(c->wrbuf, wrbuf_cstr(rec->relevance_explain2));
1212                 wrbuf_printf(c->wrbuf, " </relevance_info>\n");
1213             }
1214         }
1215         wrbuf_puts(c->wrbuf, " <recid>");
1216         wrbuf_xmlputs(c->wrbuf, rec->recid);
1217         wrbuf_puts(c->wrbuf, "</recid>\n");
1218         wrbuf_puts(c->wrbuf, "</hit>\n");
1219     }
1220
1221     show_range_stop(s->psession, rl);
1222
1223     response_close(c, "show");
1224 }
1225
1226 static void show_records_ready(void *data)
1227 {
1228     struct http_channel *c = (struct http_channel *) data;
1229     struct http_session *s = locate_session(c);
1230     if (s)
1231     {
1232         session_log(s->psession, c->http_sessions->log_level,
1233                     "show watch released");
1234         show_records(c, s, -1);
1235     }
1236     else {
1237         /* some error message  */
1238     }
1239     release_session(c, s);
1240 }
1241
1242 static void cmd_show(struct http_channel *c)
1243 {
1244     struct http_request  *rq = c->request;
1245     struct http_response *rs = c->response;
1246     struct http_session *s = locate_session(c);
1247     const char *block = http_argbyname(rq, "block");
1248     const char *sort = http_argbyname(rq, "sort");
1249     const char *block_error = http_argbyname(rq, "report");
1250     const char *mergekey = http_argbyname(rq, "mergekey");
1251     const char *rank = http_argbyname(rq, "rank");
1252     struct conf_service *service = 0;
1253     struct reclist_sortparms *sp;
1254     int status;
1255     int report_error = 0;
1256
1257     if (block_error && !strcmp("1", block_error))
1258         report_error = 1;
1259     if (!s)
1260         return;
1261     service = s->psession->service;
1262     if (!sort)
1263         sort = service->default_sort;
1264     if (!(sp = reclist_parse_sortparms(c->nmem, sort, service)))
1265     {
1266         error(c->response, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
1267         release_session(c, s);
1268         return;
1269     }
1270     session_sort(s->psession, sp, mergekey, rank);
1271
1272     status = session_active_clients(s->psession);
1273
1274     if (block && reclist_get_num_records(s->psession->reclist) == 0)
1275     {
1276         if (!strcmp(block, "preferred")
1277             && !session_is_preferred_clients_ready(s->psession)
1278             && reclist_get_num_records(s->psession->reclist) == 0)
1279         {
1280             // if there is already a watch/block. we do not block this one
1281             if (session_set_watch(s->psession, SESSION_WATCH_SHOW_PREF,
1282                                   show_records_ready, c, c) == 0)
1283             {
1284                 session_log(s->psession, c->http_sessions->log_level,
1285                             "Blocking on command show (preferred targets)");
1286                 release_session(c, s);
1287                 return;
1288             }
1289             else
1290             {
1291                 session_log(s->psession, YLOG_WARN, "Attempt to block"
1292                             " multiple times on show (preferred targets) block."
1293                             " Not supported!");
1294                 if (report_error)
1295                 {
1296                     error(rs, PAZPAR2_ALREADY_BLOCKED,
1297                           "show (preferred targets)");
1298                     release_session(c, s);
1299                     return;
1300                 }
1301                 else
1302                     session_log(s->psession, YLOG_WARN,
1303                                 "Ignoring show(preferred) block."
1304                                 " Returning current result");
1305             }
1306
1307         }
1308         else if (status)
1309         {
1310             // if there is already a watch/block. we do not block this one
1311             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
1312                                   show_records_ready, c, c) != 0)
1313             {
1314                 session_log(s->psession, YLOG_WARN, "Attempt to block"
1315                             " multiple times on show block. Not supported!");
1316                 if (report_error)
1317                 {
1318                     error(rs, PAZPAR2_ALREADY_BLOCKED, "show");
1319                     release_session(c, s);
1320                     return;
1321                 }
1322                 else
1323                     session_log(s->psession, YLOG_WARN, "Ignoring show block."
1324                                 " Returning current result");
1325             }
1326             else
1327             {
1328                 session_log(s->psession, c->http_sessions->log_level,
1329                             "Blocking on command show");
1330                 release_session(c, s);
1331                 return;
1332             }
1333         }
1334     }
1335     show_records(c, s, status);
1336     release_session(c, s);
1337 }
1338
1339 static void cmd_ping(struct http_channel *c)
1340 {
1341     struct http_session *s = locate_session(c);
1342     if (!s)
1343         return;
1344     response_open_ok(c, "ping");
1345     response_close(c, "ping");
1346     release_session(c, s);
1347 }
1348
1349 static void cmd_search(struct http_channel *c)
1350 {
1351     struct http_request *rq = c->request;
1352     struct http_response *rs = c->response;
1353     struct http_session *s = locate_session(c);
1354     const char *query = http_argbyname(rq, "query");
1355     const char *filter = http_argbyname(rq, "filter");
1356     const char *maxrecs = http_argbyname(rq, "maxrecs");
1357     const char *startrecs = http_argbyname(rq, "startrecs");
1358     const char *limit = http_argbyname(rq, "limit");
1359     const char *sort = http_argbyname(rq, "sort");
1360     const char *mergekey = http_argbyname(rq, "mergekey");
1361     const char *rank = http_argbyname(rq, "rank");
1362     enum pazpar2_error_code code;
1363     const char *addinfo = 0;
1364     const char *addinfo2 = 0;
1365     struct reclist_sortparms *sp;
1366     struct conf_service *service = 0;
1367
1368     if (!s)
1369         return;
1370
1371     if (!query)
1372     {
1373         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
1374         release_session(c, s);
1375         return;
1376     }
1377     if (!yaz_utf8_check(query))
1378     {
1379         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
1380         release_session(c, s);
1381         return;
1382     }
1383     service = s->psession->service;
1384     if (!sort)
1385         sort = service->default_sort;
1386
1387     if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
1388     {
1389         error(c->response, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
1390         release_session(c, s);
1391         return;
1392     }
1393
1394     code = session_search(s->psession, query, startrecs, maxrecs, filter, limit,
1395                           &addinfo, &addinfo2, sp, mergekey, rank);
1396     if (code)
1397     {
1398         error2(rs, code, addinfo, addinfo2);
1399         release_session(c, s);
1400         return;
1401     }
1402     response_open_ok(c, "search");
1403     response_close(c, "search");
1404     release_session(c, s);
1405 }
1406
1407
1408 static void cmd_stat(struct http_channel *c)
1409 {
1410     struct http_session *s = locate_session(c);
1411     struct statistics stat;
1412     int clients;
1413
1414     float progress = 0;
1415
1416     if (!s)
1417         return;
1418
1419     clients = session_active_clients(s->psession);
1420     statistics(s->psession, &stat);
1421
1422     if (stat.num_clients > 0)
1423     {
1424         progress = (stat.num_clients  - clients) / (float)stat.num_clients;
1425     }
1426
1427     response_open_command(c, "stat");
1428     wrbuf_printf(c->wrbuf, "\n <activeclients>%d</activeclients>\n", clients);
1429     wrbuf_printf(c->wrbuf, " <hits>" ODR_INT_PRINTF "</hits>\n", stat.num_hits);
1430     wrbuf_printf(c->wrbuf, " <records>%d</records>\n", stat.num_records);
1431     wrbuf_printf(c->wrbuf, " <clients>%d</clients>\n", stat.num_clients);
1432     wrbuf_printf(c->wrbuf, " <unconnected>%d</unconnected>\n", stat.num_no_connection);
1433     wrbuf_printf(c->wrbuf, " <connecting>%d</connecting>\n", stat.num_connecting);
1434     wrbuf_printf(c->wrbuf, " <working>%d</working>\n", stat.num_working);
1435     wrbuf_printf(c->wrbuf, " <idle>%d</idle>\n", stat.num_idle);
1436     wrbuf_printf(c->wrbuf, " <failed>%d</failed>\n", stat.num_failed);
1437     wrbuf_printf(c->wrbuf, " <error>%d</error>\n", stat.num_error);
1438     wrbuf_printf(c->wrbuf, " <progress>%.2f</progress>\n", progress);
1439     response_close(c, "stat");
1440     release_session(c, s);
1441 }
1442
1443 static void cmd_stop(struct http_channel *c)
1444 {
1445     struct http_session *s = locate_session(c);
1446     if (!s)
1447         return;
1448     response_open_ok(c, "stop");
1449     session_stop(s->psession);
1450     response_close(c, "stop");
1451     release_session(c, s);
1452 }
1453
1454 static void cmd_info(struct http_channel *c)
1455 {
1456     char yaz_version_str[20];
1457     char yaz_sha1_str[42];
1458
1459     response_open_command(c, "info");
1460     wrbuf_puts(c->wrbuf, "\n <version>\n");
1461     wrbuf_puts(c->wrbuf, "  <pazpar2");
1462 #ifdef PAZPAR2_VERSION_SHA1
1463     wrbuf_printf(c->wrbuf, " sha1=\"%s\"", PAZPAR2_VERSION_SHA1);
1464 #endif
1465     wrbuf_puts(c->wrbuf, ">");
1466     wrbuf_xmlputs(c->wrbuf, VERSION);
1467     wrbuf_puts(c->wrbuf, "</pazpar2>\n");
1468
1469     yaz_version(yaz_version_str, yaz_sha1_str);
1470     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
1471     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
1472     wrbuf_puts(c->wrbuf, "\" sha1=\"");
1473     wrbuf_xmlputs(c->wrbuf, yaz_sha1_str);
1474     wrbuf_puts(c->wrbuf, "\">");
1475     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
1476     wrbuf_puts(c->wrbuf, "</yaz>\n");
1477
1478     wrbuf_puts(c->wrbuf, " </version>\n");
1479 #if HAVE_UNISTD_H
1480     {
1481         char hostname_str[64];
1482         if (gethostname(hostname_str, sizeof(hostname_str)) == 0)
1483         {
1484             wrbuf_puts(c->wrbuf, " <host>");
1485             wrbuf_xmlputs(c->wrbuf, hostname_str);
1486             wrbuf_puts(c->wrbuf, "</host>\n");
1487         }
1488     }
1489 #endif
1490     info_services(c->server, c->wrbuf);
1491
1492     response_close(c, "info");
1493 }
1494
1495 struct {
1496     char *name;
1497     void (*fun)(struct http_channel *c);
1498 } commands[] = {
1499     { "init", cmd_init },
1500     { "settings", cmd_settings },
1501     { "stat", cmd_stat },
1502     { "bytarget", cmd_bytarget },
1503     { "show", cmd_show },
1504     { "search", cmd_search },
1505     { "termlist", cmd_termlist },
1506     { "exit", cmd_exit },
1507     { "session-status", cmd_session_status },
1508     { "server-status", cmd_server_status },
1509     { "service", cmd_service },
1510     { "ping", cmd_ping },
1511     { "record", cmd_record },
1512     { "info", cmd_info },
1513     { "stop", cmd_stop },
1514     {0,0}
1515 };
1516
1517 void http_command(struct http_channel *c)
1518 {
1519     const char *command = http_argbyname(c->request, "command");
1520     struct http_response *rs = http_create_response(c);
1521     int i;
1522
1523     c->response = rs;
1524
1525     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
1526     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
1527
1528     if (!command)
1529     {
1530         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
1531         return;
1532     }
1533     for (i = 0; commands[i].name; i++)
1534         if (!strcmp(commands[i].name, command))
1535         {
1536             (*commands[i].fun)(c);
1537             break;
1538         }
1539     if (!commands[i].name)
1540         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
1541
1542     return;
1543 }
1544
1545 /*
1546  * Local variables:
1547  * c-basic-offset: 4
1548  * c-file-style: "Stroustrup"
1549  * indent-tabs-mode: nil
1550  * End:
1551  * vim: shiftwidth=4 tabstop=8 expandtab
1552  */
1553