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