Fix memory leak for termlist of type xtargets
[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     yaz_log(YLOG_WARN, "exit");
366     http_close_server(c->server);
367 }
368
369 static void cmd_init(struct http_channel *c)
370 {
371     char buf[1024];
372     struct http_request *r = c->request;
373     const char *clear = http_argbyname(r, "clear");
374     const char *content_type = http_lookup_header(r->headers, "Content-Type");
375     unsigned int sesid;
376     struct http_session *s;
377     struct http_response *rs = c->response;
378     struct conf_service *service = 0; /* no service (yet) */
379     
380     if (r->content_len && content_type && 
381         !yaz_strcmp_del("text/xml", content_type, "; "))
382     {
383         xmlDoc *doc = xmlParseMemory(r->content_buf, r->content_len);
384         xmlNode *root_n;
385         if (!doc)
386         {
387             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
388             return;
389         }
390         root_n = xmlDocGetRootElement(doc);
391         service = service_create(c->server, root_n);
392         xmlFreeDoc(doc);
393         if (!service)
394         {
395             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
396             return;
397         }
398     }
399     
400     if (!service)
401     {
402         const char *service_name = http_argbyname(c->request, "service");
403         service = locate_service(c->server, service_name);
404         if (!service)
405         {
406             error(rs, PAZPAR2_NO_SERVICE, service_name ? service_name : "unnamed");
407             return;
408         }
409     }
410     sesid = make_sessionid();
411     s = http_session_create(service, c->http_sessions, sesid);
412     
413     yaz_log(c->http_sessions->log_level, "%p Session init %u ", s, sesid);
414     if (!clear || *clear == '0')
415         session_init_databases(s->psession);
416     else
417         yaz_log(YLOG_LOG, "HTTP Session %u init: No databases preloaded", sesid);
418     
419     if (process_settings(s->psession, c->request, c->response) < 0)
420         return;
421     
422     sprintf(buf, HTTP_COMMAND_RESPONSE_PREFIX 
423             "<init><status>OK</status><session>%d", sesid);
424     if (c->server->server_id)
425     {
426         strcat(buf, ".");
427         strcat(buf, c->server->server_id);
428     }
429     strcat(buf, "</session>"
430            "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol></init>");
431     rs->payload = nmem_strdup(c->nmem, buf);
432     http_send_response(c);
433 }
434
435 static void apply_local_setting(void *client_data,
436                                 struct setting *set)
437 {
438     struct session *se =  (struct session *) client_data;
439
440     session_apply_setting(se, nmem_strdup(se->session_nmem, set->target),
441                           nmem_strdup(se->session_nmem, set->name),
442                           nmem_strdup(se->session_nmem, set->value));
443 }
444
445 static void cmd_settings(struct http_channel *c)
446 {
447     struct http_response *rs = c->response;
448     struct http_request *rq = c->request;
449     struct http_session *s = locate_session(c);
450     const char *content_type = http_lookup_header(rq->headers, "Content-Type");
451
452     if (!s)
453         return;
454
455     if (rq->content_len && content_type && 
456         !yaz_strcmp_del("text/xml", content_type, "; "))
457     {
458         xmlDoc *doc = xmlParseMemory(rq->content_buf, rq->content_len);
459         xmlNode *root_n;
460         if (!doc)
461         {
462             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
463             return;
464         }
465         root_n = xmlDocGetRootElement(doc);
466
467         settings_read_node_x(root_n, s->psession, apply_local_setting);
468
469         xmlFreeDoc(doc);
470     }
471     if (process_settings(s->psession, rq, rs) < 0) {
472         release_session(c,s);
473         return;
474     }
475     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<settings><status>OK</status></settings>";
476     http_send_response(c);
477     release_session(c,s);
478 }
479
480 // Compares two hitsbytarget nodes by hitcount
481 static int cmp_ht(const void *p1, const void *p2)
482 {
483     const struct hitsbytarget *h1 = p1;
484     const struct hitsbytarget *h2 = p2;
485     return h2->hits - h1->hits;
486 }
487
488 // This implements functionality somewhat similar to 'bytarget', but in a termlist form
489 static int targets_termlist(WRBUF wrbuf, struct session *se, int num,
490                              NMEM nmem)
491 {
492     struct hitsbytarget *ht;
493     int count, i;
494
495     ht = hitsbytarget(se, &count, nmem);
496     qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
497     for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
498     {
499
500         // do only print terms which have display names
501     
502         wrbuf_puts(wrbuf, "<term>\n");
503
504         wrbuf_puts(wrbuf, "<id>");
505         wrbuf_xmlputs(wrbuf, ht[i].id);
506         wrbuf_puts(wrbuf, "</id>\n");
507         
508         wrbuf_puts(wrbuf, "<name>");
509         if (!ht[i].name || !ht[i].name[0])
510             wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
511         else
512             wrbuf_xmlputs(wrbuf, ht[i].name);
513         wrbuf_puts(wrbuf, "</name>\n");
514         
515         wrbuf_printf(wrbuf, "<frequency>" ODR_INT_PRINTF "</frequency>\n",
516                      ht[i].hits);
517         
518         wrbuf_puts(wrbuf, "<state>");
519         wrbuf_xmlputs(wrbuf, ht[i].state);
520         wrbuf_puts(wrbuf, "</state>\n");
521         
522         wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
523                      ht[i].diagnostic);
524         wrbuf_puts(wrbuf, "</term>\n");
525     }
526     return count;
527 }
528
529 static void cmd_termlist(struct http_channel *c)
530 {
531     struct http_response *rs = c->response;
532     struct http_request *rq = c->request;
533     struct http_session *s = locate_session(c);
534     struct termlist_score **p;
535     int len;
536     int i;
537     const char *name = http_argbyname(rq, "name");
538     const char *nums = http_argbyname(rq, "num");
539     int num = 15;
540     int status;
541     WRBUF debug_log = wrbuf_alloc();
542
543     if (!s)
544         return;
545
546     status = session_active_clients(s->psession);
547
548     if (!name)
549         name = "subject";
550     if (strlen(name) > 255)
551         return;
552     if (nums)
553         num = atoi(nums);
554
555     wrbuf_rewind(c->wrbuf);
556
557     wrbuf_puts(c->wrbuf, "<termlist>\n");
558     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", status);
559     while (*name)
560     {
561         char tname[256];
562         const char *tp;
563
564         if (!(tp = strchr(name, ',')))
565             tp = name + strlen(name);
566         strncpy(tname, name, tp - name);
567         tname[tp - name] = '\0';
568         wrbuf_puts(c->wrbuf, "<list name=\"");
569         wrbuf_xmlputs(c->wrbuf, tname);
570         wrbuf_puts(c->wrbuf, "\">\n");
571         if (!strcmp(tname, "xtargets")) {
572             int targets = targets_termlist(c->wrbuf, s->psession, num, c->nmem);
573             wrbuf_printf(debug_log, " xtargets: %d", targets);
574         }
575         else
576         {
577             p = termlist(s->psession, tname, &len);
578             if (p && len)
579                 wrbuf_printf(debug_log, " %s: %d", tname, len);
580             if (p) {
581                 for (i = 0; i < len && i < num; i++){
582                     // prevnt sending empty term elements
583                     if (!p[i]->term || !p[i]->term[0])
584                         continue;
585
586                     wrbuf_puts(c->wrbuf, "<term>");
587                     wrbuf_puts(c->wrbuf, "<name>");
588                     wrbuf_xmlputs(c->wrbuf, p[i]->term);
589                     wrbuf_puts(c->wrbuf, "</name>");
590                         
591                     wrbuf_printf(c->wrbuf, 
592                                  "<frequency>%d</frequency>", 
593                                  p[i]->frequency);
594                     wrbuf_puts(c->wrbuf, "</term>\n");
595                }
596             }
597         }
598         wrbuf_puts(c->wrbuf, "</list>\n");
599         name = tp;
600         if (*name == ',')
601             name++;
602     }
603     wrbuf_puts(c->wrbuf, "</termlist>\n");
604     yaz_log(YLOG_DEBUG, "termlist response: %s ", wrbuf_cstr(debug_log));
605     wrbuf_destroy(debug_log);
606     rs->payload = nmem_strdup(rq->channel->nmem, wrbuf_cstr(c->wrbuf));
607     http_send_response(c);
608     release_session(c,s);
609 }
610
611 size_t session_get_memory_status(struct session *session);
612
613 static void session_status(struct http_channel *c, struct http_session *s)
614 {
615     size_t session_nmem;
616     wrbuf_printf(c->wrbuf, "<http_count>%u</http_count>\n", s->activity_counter);
617     wrbuf_printf(c->wrbuf, "<http_nmem>%zu</http_nmem>\n", nmem_total(s->nmem) );
618     session_nmem = session_get_memory_status(s->psession);
619     wrbuf_printf(c->wrbuf, "<session_nmem>%zu</session_nmem>\n", session_nmem);
620 }
621
622 static void cmd_session_status(struct http_channel *c) {
623     struct http_response *rs = c->response;
624     struct http_session *s = locate_session(c);
625     if (!s)
626         return;
627
628     wrbuf_rewind(c->wrbuf);
629     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<sessionstatus><status>OK</status>\n");
630     session_status(c, s);
631     wrbuf_puts(c->wrbuf, "</sessionstatus>\n");
632     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
633     http_send_response(c);
634     release_session(c,s);
635
636 }
637
638 int sessions_count(void);
639 int clients_count(void);
640 #ifdef HAVE_RESULTSETS_COUNT
641 int resultsets_count(void);
642 #else
643 #define resultsets_count()      0
644 #endif
645
646 static void cmd_server_status(struct http_channel *c)
647 {
648     struct http_response *rs = c->response;
649     int sessions   = sessions_count();
650     int clients    = clients_count();
651     int resultsets = resultsets_count();
652     wrbuf_rewind(c->wrbuf);
653     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<server-status>\n");
654     wrbuf_printf(c->wrbuf, "  <sessions>%u</sessions>\n", sessions);
655     wrbuf_printf(c->wrbuf, "  <clients>%u</clients>\n",   clients);
656     /* Only works if yaz has been compiled with enabling of this */
657     wrbuf_printf(c->wrbuf, "  <resultsets>%u</resultsets>\n",resultsets);
658     print_meminfo(c->wrbuf);
659
660 /* TODO add all sessions status                         */
661 /*    http_sessions_t http_sessions = c->http_sessions; */
662 /*    struct http_session *p;                           */
663 /*
664     yaz_mutex_enter(http_sessions->mutex);
665     for (p = http_sessions->session_list; p; p = p->next) {
666         p->activity_counter++;
667         wrbuf_puts(c->wrbuf, "<session-status>\n");
668         wrbuf_printf(c->wrbuf, "<id>%s</id>\n", p->session_id);
669         yaz_mutex_leave(http_sessions->mutex);
670         session_status(c, p);
671         wrbuf_puts(c->wrbuf, "</session-status>\n");
672         yaz_mutex_enter(http_sessions->mutex);
673         p->activity_counter--;
674     }
675     yaz_mutex_leave(http_sessions->mutex);
676 */
677     wrbuf_puts(c->wrbuf, "</server-status>\n");
678     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
679     http_send_response(c);
680     xmalloc_trav(0);
681 }
682
683
684 static void cmd_bytarget(struct http_channel *c)
685 {
686     struct http_response *rs = c->response;
687     struct http_request *rq = c->request;
688     struct http_session *s = locate_session(c);
689     struct hitsbytarget *ht;
690     const char *settings = http_argbyname(rq, "settings");
691     int count, i;
692
693     if (!s)
694         return;
695     ht = hitsbytarget(s->psession, &count, c->nmem);
696     wrbuf_rewind(c->wrbuf);
697     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<bytarget><status>OK</status>");
698
699     for (i = 0; i < count; i++)
700     {
701         wrbuf_puts(c->wrbuf, "\n<target>");
702
703         wrbuf_puts(c->wrbuf, "<id>");
704         wrbuf_xmlputs(c->wrbuf, ht[i].id);
705         wrbuf_puts(c->wrbuf, "</id>\n");
706
707         if (ht[i].name && ht[i].name[0]) 
708         {
709             wrbuf_puts(c->wrbuf, "<name>");
710             wrbuf_xmlputs(c->wrbuf, ht[i].name);
711             wrbuf_puts(c->wrbuf, "</name>\n");
712         }
713
714         wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", ht[i].hits);
715         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
716         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
717
718         wrbuf_puts(c->wrbuf, "<state>");
719         wrbuf_xmlputs(c->wrbuf, ht[i].state);
720         wrbuf_puts(c->wrbuf, "</state>\n");
721         if (settings && *settings == '1')
722         {
723             wrbuf_puts(c->wrbuf, "<settings>\n");
724             wrbuf_puts(c->wrbuf, ht[i].settings_xml);
725             wrbuf_puts(c->wrbuf, "</settings>\n");
726         }
727         wrbuf_puts(c->wrbuf, "</target>");
728     }
729
730     wrbuf_puts(c->wrbuf, "</bytarget>");
731     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
732     http_send_response(c);
733     release_session(c,s);
734 }
735
736 static void write_metadata(WRBUF w, struct conf_service *service,
737         struct record_metadata **ml, int full)
738 {
739     int imeta;
740
741     for (imeta = 0; imeta < service->num_metadata; imeta++)
742     {
743         struct conf_metadata *cmd = &service->metadata[imeta];
744         struct record_metadata *md;
745         if (!cmd->brief && !full)
746             continue;
747         for (md = ml[imeta]; md; md = md->next)
748         {
749             struct record_metadata_attr *attr = md->attributes;
750             wrbuf_printf(w, "\n<md-%s", cmd->name);
751
752             for (; attr; attr = attr->next)
753             {
754                 wrbuf_printf(w, " %s=\"", attr->name);
755                 wrbuf_xmlputs(w, attr->value);
756                 wrbuf_puts(w, "\"");
757             }
758             wrbuf_puts(w, ">");
759             switch (cmd->type)
760             {
761                 case Metadata_type_generic:
762                     wrbuf_xmlputs(w, md->data.text.disp);
763                     break;
764                 case Metadata_type_year:
765                     wrbuf_printf(w, "%d", md->data.number.min);
766                     if (md->data.number.min != md->data.number.max)
767                         wrbuf_printf(w, "-%d", md->data.number.max);
768                     break;
769                 default:
770                     wrbuf_puts(w, "[can't represent]");
771             }
772             wrbuf_printf(w, "</md-%s>", cmd->name);
773         }
774     }
775 }
776
777 static void write_subrecord(struct record *r, WRBUF w,
778         struct conf_service *service, int show_details)
779 {
780     const char *name = session_setting_oneval(
781         client_get_database(r->client), PZ_NAME);
782
783     wrbuf_puts(w, "<location id=\"");
784     wrbuf_xmlputs(w, client_get_database(r->client)->database->url);
785     wrbuf_puts(w, "\" ");
786
787     wrbuf_puts(w, "name=\"");
788     wrbuf_xmlputs(w,  *name ? name : "Unknown");
789     wrbuf_puts(w, "\">");
790
791     write_metadata(w, service, r->metadata, show_details);
792     wrbuf_puts(w, "</location>\n");
793 }
794
795 static void show_raw_record_error(void *data, const char *addinfo)
796 {
797     http_channel_observer_t obs = data;
798     struct http_channel *c = http_channel_observer_chan(obs);
799     struct http_response *rs = c->response;
800
801     http_remove_observer(obs);
802
803     error(rs, PAZPAR2_RECORD_FAIL, addinfo);
804 }
805
806 static void show_raw_record_ok(void *data, const char *buf, size_t sz)
807 {
808     http_channel_observer_t obs = data;
809     struct http_channel *c = http_channel_observer_chan(obs);
810     struct http_response *rs = c->response;
811
812     http_remove_observer(obs);
813
814     wrbuf_write(c->wrbuf, buf, sz);
815     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
816     http_send_response(c);
817 }
818
819
820 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
821 {
822     http_channel_observer_t obs = data;
823     struct http_channel *c = http_channel_observer_chan(obs);
824     struct http_response *rs = c->response;
825
826     http_remove_observer(obs);
827
828     wrbuf_write(c->wrbuf, buf, sz);
829     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
830
831     rs->content_type = "application/octet-stream";
832     http_send_response(c);
833 }
834
835
836 void show_raw_reset(void *data, struct http_channel *c, void *data2)
837 {
838     //struct client *client = data;
839     //client_show_raw_remove(client, data2);
840 }
841
842 static void cmd_record_ready(void *data);
843
844 static void cmd_record(struct http_channel *c)
845 {
846     struct http_response *rs = c->response;
847     struct http_request *rq = c->request;
848     struct http_session *s = locate_session(c);
849     struct record_cluster *rec, *prev_r, *next_r;
850     struct record *r;
851     struct conf_service *service;
852     const char *idstr = http_argbyname(rq, "id");
853     const char *offsetstr = http_argbyname(rq, "offset");
854     const char *binarystr = http_argbyname(rq, "binary");
855     
856     if (!s)
857         return;
858     service = s->psession->service;
859     if (!idstr)
860     {
861         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
862         return;
863     }
864     wrbuf_rewind(c->wrbuf);
865     if (!(rec = show_single_start(s->psession, idstr, &prev_r, &next_r)))
866     {
867         if (session_active_clients(s->psession) == 0)
868         {
869             error(rs, PAZPAR2_RECORD_MISSING, idstr);
870         }
871         else if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
872                               cmd_record_ready, c, c) != 0)
873         {
874             error(rs, PAZPAR2_RECORD_MISSING, idstr);
875         }
876         release_session(c, s);
877         return;
878     }
879     if (offsetstr)
880     {
881         int offset = atoi(offsetstr);
882         const char *syntax = http_argbyname(rq, "syntax");
883         const char *esn = http_argbyname(rq, "esn");
884         int i;
885         struct record*r = rec->records;
886         int binary = 0;
887
888         if (binarystr && *binarystr != '0')
889             binary = 1;
890
891         for (i = 0; i < offset && r; r = r->next, i++)
892             ;
893         if (!r)
894         {
895             error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
896         }
897         else
898         {
899             http_channel_observer_t obs =
900                 http_add_observer(c, r->client, show_raw_reset);
901             int ret = client_show_raw_begin(r->client, r->position,
902                                         syntax, esn, 
903                                         obs /* data */,
904                                         show_raw_record_error,
905                                         (binary ? 
906                                          show_raw_record_ok_binary : 
907                                          show_raw_record_ok),
908                                         (binary ? 1 : 0));
909             if (ret == -1)
910             {
911                 http_remove_observer(obs);
912                 error(rs, PAZPAR2_NO_SESSION, 0);
913             }
914         }
915     }
916     else
917     {
918         wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<record>\n");
919         wrbuf_puts(c->wrbuf, "<recid>");
920         wrbuf_xmlputs(c->wrbuf, rec->recid);
921         wrbuf_puts(c->wrbuf, "</recid>\n");
922         if (prev_r)
923         {
924             wrbuf_puts(c->wrbuf, "<prevrecid>");
925             wrbuf_xmlputs(c->wrbuf, prev_r->recid);
926             wrbuf_puts(c->wrbuf, "</prevrecid>\n");
927         }
928         if (next_r)
929         {
930             wrbuf_puts(c->wrbuf, "<nextrecid>");
931             wrbuf_xmlputs(c->wrbuf, next_r->recid);
932             wrbuf_puts(c->wrbuf, "</nextrecid>\n");
933         }
934         wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", 
935                      session_active_clients(s->psession));
936         write_metadata(c->wrbuf, service, rec->metadata, 1);
937         for (r = rec->records; r; r = r->next)
938             write_subrecord(r, c->wrbuf, service, 1);
939         wrbuf_puts(c->wrbuf, "</record>\n");
940         rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
941         http_send_response(c);
942     }
943     show_single_stop(s->psession, rec);
944     release_session(c, s);
945 }
946
947 static void cmd_record_ready(void *data)
948 {
949     struct http_channel *c = (struct http_channel *) data;
950
951     cmd_record(c);
952 }
953
954 static void show_records(struct http_channel *c, int active)
955 {
956     struct http_request *rq = c->request;
957     struct http_response *rs = c->response;
958     struct http_session *s = locate_session(c);
959     struct record_cluster **rl;
960     struct reclist_sortparms *sp;
961     const char *start = http_argbyname(rq, "start");
962     const char *num = http_argbyname(rq, "num");
963     const char *sort = http_argbyname(rq, "sort");
964     int startn = 0;
965     int numn = 20;
966     int total;
967     Odr_int total_hits;
968     int i;
969
970     if (!s)
971         return;
972
973     // We haven't counted clients yet if we're called on a block release
974     if (active < 0)
975         active = session_active_clients(s->psession);
976
977     if (start)
978         startn = atoi(start);
979     if (num)
980         numn = atoi(num);
981     if (!sort)
982         sort = "relevance";
983     if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
984     {
985         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
986         release_session(c, s);
987         return;
988     }
989
990     
991     rl = show_range_start(s->psession, sp, startn, &numn, &total, &total_hits);
992
993     wrbuf_rewind(c->wrbuf);
994     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<show>\n<status>OK</status>\n");
995     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
996     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
997     wrbuf_printf(c->wrbuf, "<total>" ODR_INT_PRINTF "</total>\n", total_hits);
998     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
999     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
1000
1001     for (i = 0; i < numn; i++)
1002     {
1003         int ccount;
1004         struct record *p;
1005         struct record_cluster *rec = rl[i];
1006         struct conf_service *service = s->psession->service;
1007
1008         wrbuf_puts(c->wrbuf, "<hit>\n");
1009         write_metadata(c->wrbuf, service, rec->metadata, 0);
1010         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
1011             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
1012         if (ccount > 1)
1013             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
1014         if (strstr(sort, "relevance"))
1015             wrbuf_printf(c->wrbuf, "<relevance>%d</relevance>\n",
1016                          rec->relevance_score);
1017         wrbuf_puts(c->wrbuf, "<recid>");
1018         wrbuf_xmlputs(c->wrbuf, rec->recid);
1019         wrbuf_puts(c->wrbuf, "</recid>\n");
1020         wrbuf_puts(c->wrbuf, "</hit>\n");
1021     }
1022
1023     show_range_stop(s->psession, rl);
1024
1025     wrbuf_puts(c->wrbuf, "</show>\n");
1026     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1027     http_send_response(c);
1028     release_session(c, s);
1029 }
1030
1031 static void show_records_ready(void *data)
1032 {
1033     struct http_channel *c = (struct http_channel *) data;
1034
1035     show_records(c, -1);
1036 }
1037
1038 static void cmd_show(struct http_channel *c)
1039 {
1040     struct http_request *rq = c->request;
1041     struct http_session *s = locate_session(c);
1042     const char *block = http_argbyname(rq, "block");
1043     int status;
1044
1045     if (!s)
1046         return;
1047
1048     status = session_active_clients(s->psession);
1049
1050     if (block)
1051     {
1052         if (!strcmp(block, "preferred") && !session_is_preferred_clients_ready(s->psession) && reclist_get_num_records(s->psession->reclist) == 0) {
1053             // if there is already a watch/block. we do not block this one
1054             if (session_set_watch(s->psession, SESSION_WATCH_SHOW_PREF,
1055                                   show_records_ready, c, c) != 0)
1056             {
1057                 yaz_log(c->http_sessions->log_level,
1058                         "%p Session %u: Blocking on cmd_show. Waiting for preferred targets", s, s->session_id);
1059             }
1060             release_session(c,s);
1061             return;
1062
1063         }
1064         else if (status && reclist_get_num_records(s->psession->reclist) == 0)
1065         {
1066             // if there is already a watch/block. we do not block this one
1067             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
1068                                   show_records_ready, c, c) != 0)
1069             {
1070                 yaz_log(c->http_sessions->log_level, "%p Session %u: Blocking on cmd_show", s, s->session_id);
1071             }
1072             release_session(c,s);
1073             return;
1074         }
1075     }
1076     show_records(c, status);
1077     release_session(c,s);
1078 }
1079
1080 static void cmd_ping(struct http_channel *c)
1081 {
1082     struct http_response *rs = c->response;
1083     struct http_session *s = locate_session(c);
1084     if (!s)
1085         return;
1086     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<ping><status>OK</status></ping>";
1087     http_send_response(c);
1088     release_session(c, s);
1089 }
1090
1091 static int utf_8_valid(const char *str)
1092 {
1093     yaz_iconv_t cd = yaz_iconv_open("utf-8", "utf-8");
1094     if (cd)
1095     {
1096         /* check that query is UTF-8 encoded */
1097         char *inbuf = (char *) str; /* we know iconv does not alter this */
1098         size_t inbytesleft = strlen(inbuf);
1099
1100         size_t outbytesleft = strlen(inbuf) + 10;
1101         char *out = xmalloc(outbytesleft);
1102         char *outbuf = out;
1103         size_t r = yaz_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
1104
1105         /* if OK, try flushing the rest  */
1106         if (r != (size_t) (-1))
1107             r = yaz_iconv(cd, 0, 0, &outbuf, &outbytesleft);
1108         yaz_iconv_close(cd);
1109         xfree(out);
1110         if (r == (size_t) (-1))
1111             return 0;
1112     }
1113     return 1;
1114 }
1115
1116 static void cmd_search(struct http_channel *c)
1117 {
1118     struct http_request *rq = c->request;
1119     struct http_response *rs = c->response;
1120     struct http_session *s = locate_session(c);
1121     const char *query = http_argbyname(rq, "query");
1122     const char *filter = http_argbyname(rq, "filter");
1123     const char *maxrecs = http_argbyname(rq, "maxrecs");
1124     const char *startrecs = http_argbyname(rq, "startrecs");
1125     enum pazpar2_error_code code;
1126     const char *addinfo = 0;
1127
1128     if (!s)
1129         return;
1130     if (!query)
1131     {
1132         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
1133         release_session(c,s);
1134         return;
1135     }
1136     if (!utf_8_valid(query))
1137     {
1138         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
1139         release_session(c,s);
1140         return;
1141     }
1142     code = search(s->psession, query, startrecs, maxrecs, filter, &addinfo);
1143     if (code)
1144     {
1145         error(rs, code, addinfo);
1146         release_session(c,s);
1147         return;
1148     }
1149     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<search><status>OK</status></search>";
1150     http_send_response(c);
1151     release_session(c,s);
1152 }
1153
1154
1155 static void cmd_stat(struct http_channel *c)
1156 {
1157     struct http_response *rs = c->response;
1158     struct http_session *s = locate_session(c);
1159     struct statistics stat;
1160     int clients;
1161
1162     float progress = 0;
1163
1164     if (!s)
1165         return;
1166
1167     clients = session_active_clients(s->psession);
1168     statistics(s->psession, &stat);
1169
1170     if (stat.num_clients > 0) {
1171         progress = (stat.num_clients  - clients) / (float)stat.num_clients;
1172     }
1173
1174     wrbuf_rewind(c->wrbuf);
1175     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<stat>");
1176     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
1177     wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", stat.num_hits);
1178     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
1179     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
1180     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
1181     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
1182     wrbuf_printf(c->wrbuf, "<working>%d</working>\n", stat.num_working);
1183     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
1184     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
1185     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
1186     wrbuf_printf(c->wrbuf, "<progress>%.2f</progress>\n", progress);
1187     wrbuf_puts(c->wrbuf, "</stat>");
1188     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1189     http_send_response(c);
1190     release_session(c,s);
1191 }
1192
1193 static void cmd_info(struct http_channel *c)
1194 {
1195     char yaz_version_str[20];
1196     struct http_response *rs = c->response;
1197
1198     wrbuf_rewind(c->wrbuf);
1199     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<info>\n");
1200     wrbuf_puts(c->wrbuf, " <version>\n");
1201     wrbuf_puts(c->wrbuf, "  <pazpar2");
1202 #ifdef PAZPAR2_VERSION_SHA1
1203     wrbuf_printf(c->wrbuf, " sha1=\"%s\"", PAZPAR2_VERSION_SHA1);
1204 #endif
1205     wrbuf_puts(c->wrbuf, ">");
1206     wrbuf_xmlputs(c->wrbuf, VERSION);
1207     wrbuf_puts(c->wrbuf, "</pazpar2>");
1208
1209
1210     yaz_version(yaz_version_str, 0);
1211     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
1212     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
1213     wrbuf_puts(c->wrbuf, "\">");
1214     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
1215     wrbuf_puts(c->wrbuf, "</yaz>\n");
1216
1217     wrbuf_puts(c->wrbuf, " </version>\n");
1218     
1219     info_services(c->server, c->wrbuf);
1220
1221     wrbuf_puts(c->wrbuf, "</info>");
1222     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1223     http_send_response(c);
1224 }
1225
1226 struct {
1227     char *name;
1228     void (*fun)(struct http_channel *c);
1229 } commands[] = {
1230     { "init", cmd_init },
1231     { "settings", cmd_settings },
1232     { "stat", cmd_stat },
1233     { "bytarget", cmd_bytarget },
1234     { "show", cmd_show },
1235     { "search", cmd_search },
1236     { "termlist", cmd_termlist },
1237     { "exit", cmd_exit },
1238     { "session-status", cmd_session_status },
1239     { "server-status", cmd_server_status },
1240     { "ping", cmd_ping },
1241     { "record", cmd_record },
1242     { "info", cmd_info },
1243     {0,0}
1244 };
1245
1246 void http_command(struct http_channel *c)
1247 {
1248     const char *command = http_argbyname(c->request, "command");
1249     struct http_response *rs = http_create_response(c);
1250     int i;
1251
1252     c->response = rs;
1253
1254     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
1255     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
1256
1257     if (!command)
1258     {
1259         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
1260         return;
1261     }
1262     for (i = 0; commands[i].name; i++)
1263         if (!strcmp(commands[i].name, command))
1264         {
1265             (*commands[i].fun)(c);
1266             break;
1267         }
1268     if (!commands[i].name)
1269         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
1270
1271     return;
1272 }
1273
1274 /*
1275  * Local variables:
1276  * c-basic-offset: 4
1277  * c-file-style: "Stroustrup"
1278  * indent-tabs-mode: nil
1279  * End:
1280  * vim: shiftwidth=4 tabstop=8 expandtab
1281  */
1282