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