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