Refactor for and implement bytarget block
[pazpar2-moved-to-github.git] / src / http_command.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2011 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 int http_session_use(int delta)
97 {
98     int sessions;
99     if (!g_http_session_mutex)
100         yaz_mutex_create(&g_http_session_mutex);
101     yaz_mutex_enter(g_http_session_mutex);
102     g_http_sessions += delta;
103     sessions = g_http_sessions;
104     yaz_mutex_leave(g_http_session_mutex);
105     yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), sessions);
106     return sessions;
107
108 }
109
110 http_sessions_t http_sessions_create(void)
111 {
112     http_sessions_t hs = xmalloc(sizeof(*hs));
113     hs->session_list = 0;
114     hs->mutex = 0;
115     pazpar2_mutex_create(&hs->mutex, "http_sessions");
116     hs->log_level = yaz_log_module_level("HTTP");
117     return hs;
118 }
119
120 void http_sessions_destroy(http_sessions_t hs)
121 {
122     if (hs)
123     {
124         struct http_session *s = hs->session_list;
125         while (s)
126         {
127             struct http_session *s_next = s->next;
128             iochan_destroy(s->timeout_iochan);
129             destroy_session(s->psession);
130             nmem_destroy(s->nmem);
131             s = s_next;
132         }
133         yaz_mutex_destroy(&hs->mutex);
134         xfree(hs);
135     }
136 }
137
138 void http_session_destroy(struct http_session *s);
139
140 static void session_timeout(IOCHAN i, int event)
141 {
142     struct http_session *s = iochan_getdata(i);
143     http_session_destroy(s);
144 }
145
146 struct http_session *http_session_create(struct conf_service *service,
147                                          http_sessions_t http_sessions,
148                                          unsigned int sesid)
149 {
150     NMEM nmem = nmem_create();
151     struct http_session *r = nmem_malloc(nmem, sizeof(*r));
152     char tmp_str[50];
153
154     sprintf(tmp_str, "session#%u", sesid);
155     r->psession = new_session(nmem, service, sesid);
156     r->session_id = sesid;
157     r->timestamp = 0;
158     r->nmem = nmem;
159     r->destroy_counter = r->activity_counter = 0;
160     r->http_sessions = http_sessions;
161
162     yaz_mutex_enter(http_sessions->mutex);
163     r->next = http_sessions->session_list;
164     http_sessions->session_list = r;
165     yaz_mutex_leave(http_sessions->mutex);
166
167     r->timeout_iochan = iochan_create(-1, session_timeout, 0, "http_session_timeout");
168     iochan_setdata(r->timeout_iochan, r);
169     yaz_log(http_sessions->log_level, "%p Session %u created. timeout chan=%p timeout=%d", r, sesid, r->timeout_iochan, service->session_timeout);
170     iochan_settimeout(r->timeout_iochan, service->session_timeout);
171
172     iochan_add(service->server->iochan_man, r->timeout_iochan);
173     http_session_use(1);
174     return r;
175 }
176
177 void http_session_destroy(struct http_session *s)
178 {
179     int must_destroy = 0;
180
181     http_sessions_t http_sessions = s->http_sessions;
182
183     yaz_log(http_sessions->log_level, "%p HTTP Session %u destroyed", s, s->session_id);
184     yaz_mutex_enter(http_sessions->mutex);
185     /* only if http_session has no active http sessions on it can be destroyed */
186     if (s->destroy_counter == s->activity_counter)
187     {
188         struct http_session **p = 0;
189         must_destroy = 1;
190         for (p = &http_sessions->session_list; *p; p = &(*p)->next)
191             if (*p == s)
192             {
193                 *p = (*p)->next;
194                 break;
195             }
196     }
197     yaz_mutex_leave(http_sessions->mutex);
198     if (must_destroy)
199     {   /* destroying for real */
200         yaz_log(http_sessions->log_level, "%p HTTP Session %u destroyed", s, s->session_id);
201         iochan_destroy(s->timeout_iochan);
202         destroy_session(s->psession);
203         http_session_use(-1);
204         nmem_destroy(s->nmem);
205     }
206     else {
207         yaz_log(http_sessions->log_level, "%p HTTP Session %u destroyed delayed. Active clients (%d-%d). Waiting for new timeout.",
208                 s, s->session_id, s->activity_counter, s->destroy_counter);
209     }
210
211 }
212
213 static const char *get_msg(enum pazpar2_error_code code)
214 {
215     struct pazpar2_error_msg {
216         enum pazpar2_error_code code;
217         const char *msg;
218     };
219     static const struct pazpar2_error_msg ar[] = {
220         { PAZPAR2_NO_SESSION, "Session does not exist or it has expired"},
221         { PAZPAR2_MISSING_PARAMETER, "Missing parameter"},
222         { PAZPAR2_MALFORMED_PARAMETER_VALUE, "Malformed parameter value"},
223         { PAZPAR2_MALFORMED_PARAMETER_ENCODING, "Malformed parameter encoding"},
224         { PAZPAR2_MALFORMED_SETTING, "Malformed setting argument"},
225         { PAZPAR2_HITCOUNTS_FAILED, "Failed to retrieve hitcounts"},
226         { PAZPAR2_RECORD_MISSING, "Record missing"},
227         { PAZPAR2_NO_TARGETS, "No targets"},
228         { PAZPAR2_CONFIG_TARGET, "Target cannot be configured"},
229         { PAZPAR2_RECORD_FAIL, "Record command failed"},
230         { PAZPAR2_NOT_IMPLEMENTED, "Not implemented"},
231         { PAZPAR2_NO_SERVICE, "No service"},
232         { PAZPAR2_LAST_ERROR, "Last error"},
233         { 0, 0 }
234     };
235     int i = 0;
236     while (ar[i].msg)
237     {
238         if (code == ar[i].code)
239             return ar[i].msg;
240         i++;
241     }
242     return "No error";
243 }
244
245 static void error(struct http_response *rs, 
246                   enum pazpar2_error_code code,
247                   const char *addinfo)
248 {
249     struct http_channel *c = rs->channel;
250     WRBUF text = wrbuf_alloc();
251     const char *http_status = "417";
252     const char *msg = get_msg(code);
253     
254     rs->msg = nmem_strdup(c->nmem, msg);
255     strcpy(rs->code, http_status);
256
257     wrbuf_printf(text, HTTP_COMMAND_RESPONSE_PREFIX "<error code=\"%d\" msg=\"%s\">", (int) code,
258                msg);
259     if (addinfo)
260         wrbuf_xmlputs(text, addinfo);
261     wrbuf_puts(text, "</error>");
262
263     yaz_log(YLOG_WARN, "HTTP %s %s%s%s", http_status,
264             msg, addinfo ? ": " : "" , addinfo ? addinfo : "");
265     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(text));
266     wrbuf_destroy(text);
267     http_send_response(c);
268 }
269
270 static void response_open_no_status(struct http_channel *c, const char *command)
271 {
272     wrbuf_rewind(c->wrbuf);
273     wrbuf_printf(c->wrbuf, "%s<%s>",
274                  HTTP_COMMAND_RESPONSE_PREFIX, command);
275 }
276
277 static void response_open(struct http_channel *c, const char *command)
278 {
279     response_open_no_status(c, command);
280     wrbuf_puts(c->wrbuf, "<status>OK</status>");
281 }
282
283 static void response_close(struct http_channel *c, const char *command)
284 {
285     struct http_response *rs = c->response;
286
287     wrbuf_printf(c->wrbuf, "</%s>", command);
288     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
289     http_send_response(c);
290 }
291
292 unsigned int make_sessionid(void)
293 {
294     static int seq = 0; /* thread pr */
295     unsigned int res;
296
297     seq++;
298     if (global_parameters.predictable_sessions)
299         res = seq;
300     else
301     {
302 #ifdef WIN32
303         res = seq;
304 #else
305         struct timeval t;
306
307         if (gettimeofday(&t, 0) < 0)
308         {
309             yaz_log(YLOG_WARN|YLOG_ERRNO, "gettimeofday");
310             exit(1);
311         }
312         /* at most 256 sessions per second .. 
313            (long long would be more appropriate)*/
314         res = t.tv_sec;
315         res = ((res << 8) | (seq & 0xff)) & ((1U << 31) - 1);
316 #endif
317     }
318     return res;
319 }
320
321 static struct http_session *locate_session(struct http_channel *c)
322 {
323     struct http_response *rs = c->response;
324     struct http_request *rq = c->request;
325     struct http_session *p;
326     const char *session = http_argbyname(rq, "session");
327     http_sessions_t http_sessions = c->http_sessions;
328     unsigned int id;
329
330     if (!session)
331     {
332         error(rs, PAZPAR2_MISSING_PARAMETER, "session");
333         return 0;
334     }
335     id = atoi(session);
336     yaz_mutex_enter(http_sessions->mutex);
337     for (p = http_sessions->session_list; p; p = p->next)
338         if (id == p->session_id)
339             break;
340     if (p)
341         p->activity_counter++;
342     yaz_mutex_leave(http_sessions->mutex);
343     if (p)
344         iochan_activity(p->timeout_iochan);
345     else
346         error(rs, PAZPAR2_NO_SESSION, session);
347     return p;
348 }
349
350 // Call after use of locate_session, in order to increment the destroy_counter
351 static void release_session(struct http_channel *c,
352                             struct http_session *session)
353 {
354     http_sessions_t http_sessions = c->http_sessions;
355     yaz_mutex_enter(http_sessions->mutex);
356     if (session)
357         session->destroy_counter++;
358     yaz_mutex_leave(http_sessions->mutex);
359 }
360
361 // Decode settings parameters and apply to session
362 // Syntax: setting[target]=value
363 static int process_settings(struct session *se, struct http_request *rq,
364                             struct http_response *rs)
365 {
366     struct http_argument *a;
367
368     for (a = rq->arguments; a; a = a->next)
369         if (strchr(a->name, '['))
370         {
371             char **res;
372             int num;
373             char *dbname;
374             char *setting;
375
376             // Nmem_strsplit *rules*!!!
377             nmem_strsplit(se->session_nmem, "[]", a->name, &res, &num);
378             if (num != 2)
379             {
380                 error(rs, PAZPAR2_MALFORMED_SETTING, a->name);
381                 return -1;
382             }
383             setting = res[0];
384             dbname = res[1];
385             session_apply_setting(se, dbname, setting,
386                     nmem_strdup(se->session_nmem, a->value));
387         }
388     return 0;
389 }
390
391 static void cmd_exit(struct http_channel *c)
392 {
393     yaz_log(YLOG_WARN, "exit");
394
395     response_open(c, "exit");
396     response_close(c, "exit");
397     http_close_server(c->server);
398 }
399
400 static void cmd_init(struct http_channel *c)
401 {
402     struct http_request *r = c->request;
403     const char *clear = http_argbyname(r, "clear");
404     const char *content_type = http_lookup_header(r->headers, "Content-Type");
405     unsigned int sesid;
406     struct http_session *s;
407     struct http_response *rs = c->response;
408     struct conf_service *service = 0; /* no service (yet) */
409     
410     if (r->content_len && content_type && 
411         !yaz_strcmp_del("text/xml", content_type, "; "))
412     {
413         xmlDoc *doc = xmlParseMemory(r->content_buf, r->content_len);
414         xmlNode *root_n;
415         if (!doc)
416         {
417             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
418             return;
419         }
420         root_n = xmlDocGetRootElement(doc);
421         service = service_create(c->server, root_n);
422         xmlFreeDoc(doc);
423         if (!service)
424         {
425             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
426             return;
427         }
428     }
429     
430     if (!service)
431     {
432         const char *service_name = http_argbyname(c->request, "service");
433         service = locate_service(c->server, service_name);
434         if (!service)
435         {
436             error(rs, PAZPAR2_NO_SERVICE, service_name ? service_name : "unnamed");
437             return;
438         }
439     }
440     sesid = make_sessionid();
441     s = http_session_create(service, c->http_sessions, sesid);
442     
443     yaz_log(c->http_sessions->log_level, "%p Session init %u ", s, sesid);
444     if (!clear || *clear == '0')
445         session_init_databases(s->psession);
446     else
447         yaz_log(YLOG_LOG, "HTTP Session %u init: No databases preloaded", sesid);
448     
449     if (process_settings(s->psession, c->request, c->response) < 0)
450         return;
451
452     response_open(c, "init");
453     wrbuf_printf(c->wrbuf, "<session>%d", sesid);
454     if (c->server->server_id)
455     {
456         wrbuf_puts(c->wrbuf, ".");
457         wrbuf_puts(c->wrbuf, c->server->server_id);
458     }
459     wrbuf_puts(c->wrbuf, "</session>"
460                "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol>");
461     
462     response_close(c, "init");
463 }
464
465 static void apply_local_setting(void *client_data,
466                                 struct setting *set)
467 {
468     struct session *se =  (struct session *) client_data;
469
470     session_apply_setting(se, nmem_strdup(se->session_nmem, set->target),
471                           nmem_strdup(se->session_nmem, set->name),
472                           nmem_strdup(se->session_nmem, set->value));
473 }
474
475 static void cmd_settings(struct http_channel *c)
476 {
477     struct http_response *rs = c->response;
478     struct http_request *rq = c->request;
479     struct http_session *s = locate_session(c);
480     const char *content_type = http_lookup_header(rq->headers, "Content-Type");
481
482     if (!s)
483         return;
484
485     if (rq->content_len && content_type && 
486         !yaz_strcmp_del("text/xml", content_type, "; "))
487     {
488         xmlDoc *doc = xmlParseMemory(rq->content_buf, rq->content_len);
489         xmlNode *root_n;
490         if (!doc)
491         {
492             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
493             return;
494         }
495         root_n = xmlDocGetRootElement(doc);
496
497         settings_read_node_x(root_n, s->psession, apply_local_setting);
498
499         xmlFreeDoc(doc);
500     }
501     if (process_settings(s->psession, rq, rs) < 0)
502     {
503         release_session(c, s);
504         return;
505     }
506     response_open(c, "settings");
507     response_close(c, "settings");
508     release_session(c, s);
509 }
510
511 static void cmd_termlist(struct http_channel *c)
512 {
513     struct http_request *rq = c->request;
514     struct http_session *s = locate_session(c);
515     const char *name = http_argbyname(rq, "name");
516     const char *nums = http_argbyname(rq, "num");
517     int num = 15;
518     int status;
519
520     if (!s)
521         return;
522
523     status = session_active_clients(s->psession);
524
525     if (nums)
526         num = atoi(nums);
527
528     response_open_no_status(c, "termlist");
529     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", status);
530
531     perform_termlist(c, s->psession, name, num);
532
533     response_close(c, "termlist");
534     release_session(c, s);
535 }
536
537 size_t session_get_memory_status(struct session *session);
538
539 static void session_status(struct http_channel *c, struct http_session *s)
540 {
541     size_t session_nmem;
542     wrbuf_printf(c->wrbuf, "<http_count>%u</http_count>\n", s->activity_counter);
543     wrbuf_printf(c->wrbuf, "<http_nmem>%zu</http_nmem>\n", nmem_total(s->nmem) );
544     session_nmem = session_get_memory_status(s->psession);
545     wrbuf_printf(c->wrbuf, "<session_nmem>%zu</session_nmem>\n", session_nmem);
546 }
547
548 static void cmd_session_status(struct http_channel *c)
549 {
550     struct http_session *s = locate_session(c);
551     if (!s)
552         return;
553
554     response_open(c, "session-status");
555     session_status(c, s);
556     response_close(c, "session-status");
557     release_session(c, s);
558 }
559
560 int sessions_count(void);
561 int clients_count(void);
562 #ifdef HAVE_RESULTSETS_COUNT
563 int resultsets_count(void);
564 #else
565 #define resultsets_count()      0
566 #endif
567
568 static void cmd_server_status(struct http_channel *c)
569 {
570     int sessions   = sessions_count();
571     int clients    = clients_count();
572     int resultsets = resultsets_count();
573
574     response_open(c, "server-status");
575     wrbuf_printf(c->wrbuf, "\n  <sessions>%u</sessions>\n", sessions);
576     wrbuf_printf(c->wrbuf, "  <clients>%u</clients>\n",   clients);
577     /* Only works if yaz has been compiled with enabling of this */
578     wrbuf_printf(c->wrbuf, "  <resultsets>%u</resultsets>\n",resultsets);
579     print_meminfo(c->wrbuf);
580
581 /* TODO add all sessions status                         */
582 /*    http_sessions_t http_sessions = c->http_sessions; */
583 /*    struct http_session *p;                           */
584 /*
585     yaz_mutex_enter(http_sessions->mutex);
586     for (p = http_sessions->session_list; p; p = p->next)
587     {
588         p->activity_counter++;
589         wrbuf_puts(c->wrbuf, "<session-status>\n");
590         wrbuf_printf(c->wrbuf, "<id>%s</id>\n", p->session_id);
591         yaz_mutex_leave(http_sessions->mutex);
592         session_status(c, p);
593         wrbuf_puts(c->wrbuf, "</session-status>\n");
594         yaz_mutex_enter(http_sessions->mutex);
595         p->activity_counter--;
596     }
597     yaz_mutex_leave(http_sessions->mutex);
598 */
599     response_close(c, "server-status");
600     xmalloc_trav(0);
601 }
602
603 static void bytarget_response(struct http_channel *c) {
604     int count, i;
605     struct hitsbytarget *ht;
606     struct http_request *rq = c->request;
607     const char *settings = http_argbyname(rq, "settings");
608     struct http_session *s = locate_session(c);
609
610     ht = get_hitsbytarget(s->psession, &count, c->nmem);
611     response_open(c, "bytarget");
612
613     for (i = 0; i < count; i++)
614     {
615         wrbuf_puts(c->wrbuf, "\n<target>");
616
617         wrbuf_puts(c->wrbuf, "<id>");
618         wrbuf_xmlputs(c->wrbuf, ht[i].id);
619         wrbuf_puts(c->wrbuf, "</id>\n");
620
621         if (ht[i].name && ht[i].name[0]) 
622         {
623             wrbuf_puts(c->wrbuf, "<name>");
624             wrbuf_xmlputs(c->wrbuf, ht[i].name);
625             wrbuf_puts(c->wrbuf, "</name>\n");
626         }
627
628         wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", ht[i].hits);
629         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
630         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
631
632         wrbuf_puts(c->wrbuf, "<state>");
633         wrbuf_xmlputs(c->wrbuf, ht[i].state);
634         wrbuf_puts(c->wrbuf, "</state>\n");
635         if (settings && *settings == '1')
636         {
637             wrbuf_puts(c->wrbuf, "<settings>\n");
638             wrbuf_puts(c->wrbuf, ht[i].settings_xml);
639             wrbuf_puts(c->wrbuf, "</settings>\n");
640         }
641         if (ht[i].suggestions_xml && ht[i].suggestions_xml[0]) {
642             wrbuf_puts(c->wrbuf, "<suggestions>");
643             wrbuf_puts(c->wrbuf, ht[i].suggestions_xml);
644             wrbuf_puts(c->wrbuf, "</suggestions>");
645         }
646         wrbuf_puts(c->wrbuf, "</target>");
647     }
648     response_close(c, "bytarget");
649     release_session(c, s);
650 }
651
652 static void bytarget_result_ready(void *data)
653 {
654     struct http_channel *c = (struct http_channel *) data;
655
656     bytarget_response(c);
657 }
658
659
660 static void cmd_bytarget(struct http_channel *c)
661 {
662     struct http_request *rq = c->request;
663     struct http_session *s = locate_session(c);
664     const char *block = http_argbyname(rq, "block");
665     struct hitsbytarget *ht;
666
667     if (!s)
668         return;
669
670     if (block && strcmp("1",*block) == 0)
671     {
672         // if there is already a watch/block. we do not block this one
673         if (session_set_watch(s->psession, SESSION_WATCH_BYTARGET,
674                               bytarget_result_ready, c, c) != 0)
675         {
676             yaz_log(c->http_sessions->log_level, "%p Session %u: Blocking on cmd_bytarget", s, s->session_id);
677         }
678         release_session(c, s);
679         return;
680     }
681     bytarget_response(c);
682     release_session(c, s);
683 }
684
685 static void write_metadata(WRBUF w, struct conf_service *service,
686         struct record_metadata **ml, int full)
687 {
688     int imeta;
689
690     for (imeta = 0; imeta < service->num_metadata; imeta++)
691     {
692         struct conf_metadata *cmd = &service->metadata[imeta];
693         struct record_metadata *md;
694         if (!cmd->brief && !full)
695             continue;
696         for (md = ml[imeta]; md; md = md->next)
697         {
698             struct record_metadata_attr *attr = md->attributes;
699             wrbuf_printf(w, "\n<md-%s", cmd->name);
700
701             for (; attr; attr = attr->next)
702             {
703                 wrbuf_printf(w, " %s=\"", attr->name);
704                 wrbuf_xmlputs(w, attr->value);
705                 wrbuf_puts(w, "\"");
706             }
707             wrbuf_puts(w, ">");
708             switch (cmd->type)
709             {
710                 case Metadata_type_generic:
711                     wrbuf_xmlputs(w, md->data.text.disp);
712                     break;
713                 case Metadata_type_year:
714                     wrbuf_printf(w, "%d", md->data.number.min);
715                     if (md->data.number.min != md->data.number.max)
716                         wrbuf_printf(w, "-%d", md->data.number.max);
717                     break;
718                 default:
719                     wrbuf_puts(w, "[can't represent]");
720             }
721             wrbuf_printf(w, "</md-%s>", cmd->name);
722         }
723     }
724 }
725
726 static void write_subrecord(struct record *r, WRBUF w,
727         struct conf_service *service, int show_details)
728 {
729     const char *name = session_setting_oneval(
730         client_get_database(r->client), PZ_NAME);
731
732     wrbuf_puts(w, "<location id=\"");
733     wrbuf_xmlputs(w, client_get_id(r->client));
734     wrbuf_puts(w, "\" ");
735
736     wrbuf_puts(w, "name=\"");
737     wrbuf_xmlputs(w,  *name ? name : "Unknown");
738     wrbuf_puts(w, "\">");
739
740     write_metadata(w, service, r->metadata, show_details);
741     wrbuf_puts(w, "</location>\n");
742 }
743
744 static void show_raw_record_error(void *data, const char *addinfo)
745 {
746     http_channel_observer_t obs = data;
747     struct http_channel *c = http_channel_observer_chan(obs);
748     struct http_response *rs = c->response;
749
750     http_remove_observer(obs);
751
752     error(rs, PAZPAR2_RECORD_FAIL, addinfo);
753 }
754
755 static void show_raw_record_ok(void *data, const char *buf, size_t sz)
756 {
757     http_channel_observer_t obs = data;
758     struct http_channel *c = http_channel_observer_chan(obs);
759     struct http_response *rs = c->response;
760
761     http_remove_observer(obs);
762
763     wrbuf_write(c->wrbuf, buf, sz);
764     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
765     http_send_response(c);
766 }
767
768
769 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
770 {
771     http_channel_observer_t obs = data;
772     struct http_channel *c = http_channel_observer_chan(obs);
773     struct http_response *rs = c->response;
774
775     http_remove_observer(obs);
776
777     wrbuf_write(c->wrbuf, buf, sz);
778     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
779
780     rs->content_type = "application/octet-stream";
781     http_send_response(c);
782 }
783
784
785 void show_raw_reset(void *data, struct http_channel *c, void *data2)
786 {
787     //struct client *client = data;
788     //client_show_raw_remove(client, data2);
789 }
790
791 static void cmd_record_ready(void *data);
792
793 static void cmd_record(struct http_channel *c)
794 {
795     struct http_response *rs = c->response;
796     struct http_request *rq = c->request;
797     struct http_session *s = locate_session(c);
798     struct record_cluster *rec, *prev_r, *next_r;
799     struct record *r;
800     struct conf_service *service;
801     const char *idstr = http_argbyname(rq, "id");
802     const char *offsetstr = http_argbyname(rq, "offset");
803     const char *binarystr = http_argbyname(rq, "binary");
804     
805     if (!s)
806         return;
807     service = s->psession->service;
808     if (!idstr)
809     {
810         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
811         return;
812     }
813     wrbuf_rewind(c->wrbuf);
814     if (!(rec = show_single_start(s->psession, idstr, &prev_r, &next_r)))
815     {
816         if (session_active_clients(s->psession) == 0)
817         {
818             error(rs, PAZPAR2_RECORD_MISSING, idstr);
819         }
820         else if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
821                               cmd_record_ready, c, c) != 0)
822         {
823             error(rs, PAZPAR2_RECORD_MISSING, idstr);
824         }
825         release_session(c, s);
826         return;
827     }
828     if (offsetstr)
829     {
830         int offset = atoi(offsetstr);
831         const char *syntax = http_argbyname(rq, "syntax");
832         const char *esn = http_argbyname(rq, "esn");
833         int i;
834         struct record*r = rec->records;
835         int binary = 0;
836
837         if (binarystr && *binarystr != '0')
838             binary = 1;
839
840         for (i = 0; i < offset && r; r = r->next, i++)
841             ;
842         if (!r)
843         {
844             error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
845         }
846         else
847         {
848             http_channel_observer_t obs =
849                 http_add_observer(c, r->client, show_raw_reset);
850             int ret = client_show_raw_begin(r->client, r->position,
851                                         syntax, esn, 
852                                         obs /* data */,
853                                         show_raw_record_error,
854                                         (binary ? 
855                                          show_raw_record_ok_binary : 
856                                          show_raw_record_ok),
857                                         (binary ? 1 : 0));
858             if (ret == -1)
859             {
860                 http_remove_observer(obs);
861                 error(rs, PAZPAR2_NO_SESSION, 0);
862             }
863         }
864     }
865     else
866     {
867         response_open_no_status(c, "record");
868         wrbuf_puts(c->wrbuf, "\n<recid>");
869         wrbuf_xmlputs(c->wrbuf, rec->recid);
870         wrbuf_puts(c->wrbuf, "</recid>\n");
871         if (prev_r)
872         {
873             wrbuf_puts(c->wrbuf, "<prevrecid>");
874             wrbuf_xmlputs(c->wrbuf, prev_r->recid);
875             wrbuf_puts(c->wrbuf, "</prevrecid>\n");
876         }
877         if (next_r)
878         {
879             wrbuf_puts(c->wrbuf, "<nextrecid>");
880             wrbuf_xmlputs(c->wrbuf, next_r->recid);
881             wrbuf_puts(c->wrbuf, "</nextrecid>\n");
882         }
883         wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", 
884                      session_active_clients(s->psession));
885         write_metadata(c->wrbuf, service, rec->metadata, 1);
886         for (r = rec->records; r; r = r->next)
887             write_subrecord(r, c->wrbuf, service, 1);
888         response_close(c, "record");
889     }
890     show_single_stop(s->psession, rec);
891     release_session(c, s);
892 }
893
894 static void cmd_record_ready(void *data)
895 {
896     struct http_channel *c = (struct http_channel *) data;
897
898     cmd_record(c);
899 }
900
901 static void show_records(struct http_channel *c, int active)
902 {
903     struct http_request *rq = c->request;
904     struct http_response *rs = c->response;
905     struct http_session *s = locate_session(c);
906     struct record_cluster **rl;
907     struct reclist_sortparms *sp;
908     const char *start = http_argbyname(rq, "start");
909     const char *num = http_argbyname(rq, "num");
910     const char *sort = http_argbyname(rq, "sort");
911     int startn = 0;
912     int numn = 20;
913     int total;
914     Odr_int total_hits;
915     int i;
916
917     if (!s)
918         return;
919
920     // We haven't counted clients yet if we're called on a block release
921     if (active < 0)
922         active = session_active_clients(s->psession);
923
924     if (start)
925         startn = atoi(start);
926     if (num)
927         numn = atoi(num);
928     if (!sort)
929         sort = "relevance";
930     if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
931     {
932         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
933         release_session(c, s);
934         return;
935
936     }
937
938     
939     rl = show_range_start(s->psession, sp, startn, &numn, &total, &total_hits);
940
941     response_open(c, "show");
942     wrbuf_printf(c->wrbuf, "\n<activeclients>%d</activeclients>\n", active);
943     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
944     wrbuf_printf(c->wrbuf, "<total>" ODR_INT_PRINTF "</total>\n", total_hits);
945     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
946     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
947
948     for (i = 0; i < numn; i++)
949     {
950         int ccount;
951         struct record *p;
952         struct record_cluster *rec = rl[i];
953         struct conf_service *service = s->psession->service;
954
955         wrbuf_puts(c->wrbuf, "<hit>\n");
956         write_metadata(c->wrbuf, service, rec->metadata, 0);
957         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
958             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
959         if (ccount > 1)
960             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
961         if (strstr(sort, "relevance"))
962             wrbuf_printf(c->wrbuf, "<relevance>%d</relevance>\n",
963                          rec->relevance_score);
964         wrbuf_puts(c->wrbuf, "<recid>");
965         wrbuf_xmlputs(c->wrbuf, rec->recid);
966         wrbuf_puts(c->wrbuf, "</recid>\n");
967         wrbuf_puts(c->wrbuf, "</hit>\n");
968     }
969
970     show_range_stop(s->psession, rl);
971
972     response_close(c, "show");
973     release_session(c, s);
974 }
975
976 static void show_records_ready(void *data)
977 {
978     struct http_channel *c = (struct http_channel *) data;
979
980     show_records(c, -1);
981 }
982
983 static void cmd_show(struct http_channel *c)
984 {
985     struct http_request *rq = c->request;
986     struct http_session *s = locate_session(c);
987     const char *block = http_argbyname(rq, "block");
988     const char *sort = http_argbyname(rq, "sort");
989     struct reclist_sortparms *sp;
990     int status;
991
992     if (!s)
993         return;
994
995     if (!sort)
996         sort = "relevance";
997     
998     if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
999     {
1000         error(c->response, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
1001         release_session(c, s);
1002         return;
1003     }
1004     session_sort(s->psession, sp->name, sp->increasing);
1005
1006     status = session_active_clients(s->psession);
1007
1008     if (block)
1009     {
1010         if (!strcmp(block, "preferred") && !session_is_preferred_clients_ready(s->psession) && reclist_get_num_records(s->psession->reclist) == 0)
1011         {
1012             // if there is already a watch/block. we do not block this one
1013             if (session_set_watch(s->psession, SESSION_WATCH_SHOW_PREF,
1014                                   show_records_ready, c, c) != 0)
1015             {
1016                 yaz_log(c->http_sessions->log_level,
1017                         "%p Session %u: Blocking on cmd_show. Waiting for preferred targets", s, s->session_id);
1018             }
1019             release_session(c, s);
1020             return;
1021
1022         }
1023         else if (status)
1024         {
1025             // if there is already a watch/block. we do not block this one
1026             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
1027                                   show_records_ready, c, c) != 0)
1028             {
1029                 yaz_log(c->http_sessions->log_level, "%p Session %u: Blocking on cmd_show", s, s->session_id);
1030             }
1031             release_session(c, s);
1032             return;
1033         }
1034     }
1035     show_records(c, status);
1036     release_session(c, s);
1037 }
1038
1039 static void cmd_ping(struct http_channel *c)
1040 {
1041     struct http_session *s = locate_session(c);
1042     if (!s)
1043         return;
1044     response_open(c, "ping");
1045     response_close(c, "ping");
1046     release_session(c, s);
1047 }
1048
1049 static void cmd_search(struct http_channel *c)
1050 {
1051     struct http_request *rq = c->request;
1052     struct http_response *rs = c->response;
1053     struct http_session *s = locate_session(c);
1054     const char *query = http_argbyname(rq, "query");
1055     const char *filter = http_argbyname(rq, "filter");
1056     const char *maxrecs = http_argbyname(rq, "maxrecs");
1057     const char *startrecs = http_argbyname(rq, "startrecs");
1058     const char *limit = http_argbyname(rq, "limit");
1059     enum pazpar2_error_code code;
1060     const char *addinfo = 0;
1061
1062     if (!s)
1063         return;
1064     if (!query)
1065     {
1066         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
1067         release_session(c, s);
1068         return;
1069     }
1070     if (!yaz_utf8_check(query))
1071     {
1072         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
1073         release_session(c, s);
1074         return;
1075     }
1076     code = session_search(s->psession, query, startrecs, maxrecs, filter, limit,
1077                           &addinfo, "relevance", 0);
1078     if (code)
1079     {
1080         error(rs, code, addinfo);
1081         release_session(c, s);
1082         return;
1083     }
1084     response_open(c, "search");
1085     response_close(c, "search");
1086     release_session(c, s);
1087 }
1088
1089
1090 static void cmd_stat(struct http_channel *c)
1091 {
1092     struct http_session *s = locate_session(c);
1093     struct statistics stat;
1094     int clients;
1095
1096     float progress = 0;
1097
1098     if (!s)
1099         return;
1100
1101     clients = session_active_clients(s->psession);
1102     statistics(s->psession, &stat);
1103
1104     if (stat.num_clients > 0)
1105     {
1106         progress = (stat.num_clients  - clients) / (float)stat.num_clients;
1107     }
1108
1109     response_open_no_status(c, "stat");
1110     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
1111     wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", stat.num_hits);
1112     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
1113     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
1114     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
1115     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
1116     wrbuf_printf(c->wrbuf, "<working>%d</working>\n", stat.num_working);
1117     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
1118     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
1119     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
1120     wrbuf_printf(c->wrbuf, "<progress>%.2f</progress>\n", progress);
1121     response_close(c, "stat");
1122     release_session(c, s);
1123 }
1124
1125 static void cmd_info(struct http_channel *c)
1126 {
1127     char yaz_version_str[20];
1128
1129     response_open_no_status(c, "info");
1130     wrbuf_puts(c->wrbuf, " <version>\n");
1131     wrbuf_puts(c->wrbuf, "  <pazpar2");
1132 #ifdef PAZPAR2_VERSION_SHA1
1133     wrbuf_printf(c->wrbuf, " sha1=\"%s\"", PAZPAR2_VERSION_SHA1);
1134 #endif
1135     wrbuf_puts(c->wrbuf, ">");
1136     wrbuf_xmlputs(c->wrbuf, VERSION);
1137     wrbuf_puts(c->wrbuf, "</pazpar2>");
1138
1139     yaz_version(yaz_version_str, 0);
1140     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
1141     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
1142     wrbuf_puts(c->wrbuf, "\">");
1143     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
1144     wrbuf_puts(c->wrbuf, "</yaz>\n");
1145
1146     wrbuf_puts(c->wrbuf, " </version>\n");
1147     
1148     info_services(c->server, c->wrbuf);
1149
1150     response_close(c, "info");
1151 }
1152
1153 struct {
1154     char *name;
1155     void (*fun)(struct http_channel *c);
1156 } commands[] = {
1157     { "init", cmd_init },
1158     { "settings", cmd_settings },
1159     { "stat", cmd_stat },
1160     { "bytarget", cmd_bytarget },
1161     { "show", cmd_show },
1162     { "search", cmd_search },
1163     { "termlist", cmd_termlist },
1164     { "exit", cmd_exit },
1165     { "session-status", cmd_session_status },
1166     { "server-status", cmd_server_status },
1167     { "ping", cmd_ping },
1168     { "record", cmd_record },
1169     { "info", cmd_info },
1170     {0,0}
1171 };
1172
1173 void http_command(struct http_channel *c)
1174 {
1175     const char *command = http_argbyname(c->request, "command");
1176     struct http_response *rs = http_create_response(c);
1177     int i;
1178
1179     c->response = rs;
1180
1181     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
1182     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
1183
1184     if (!command)
1185     {
1186         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
1187         return;
1188     }
1189     for (i = 0; commands[i].name; i++)
1190         if (!strcmp(commands[i].name, command))
1191         {
1192             (*commands[i].fun)(c);
1193             break;
1194         }
1195     if (!commands[i].name)
1196         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
1197
1198     return;
1199 }
1200
1201 /*
1202  * Local variables:
1203  * c-basic-offset: 4
1204  * c-file-style: "Stroustrup"
1205  * indent-tabs-mode: nil
1206  * End:
1207  * vim: shiftwidth=4 tabstop=8 expandtab
1208  */
1209