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