b3e4dc7c60cb69c7f82cd1bfdb2a68123b8d6c2d
[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, wrbuf_cstr(ht[i].settings_xml));
725             wrbuf_puts(c->wrbuf, "</settings>\n");
726         }
727         wrbuf_puts(c->wrbuf, "</target>");
728         wrbuf_destroy(ht[i].settings_xml);
729     }
730
731     wrbuf_puts(c->wrbuf, "</bytarget>");
732     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
733     http_send_response(c);
734     release_session(c,s);
735 }
736
737 static void write_metadata(WRBUF w, struct conf_service *service,
738         struct record_metadata **ml, int full)
739 {
740     int imeta;
741
742     for (imeta = 0; imeta < service->num_metadata; imeta++)
743     {
744         struct conf_metadata *cmd = &service->metadata[imeta];
745         struct record_metadata *md;
746         if (!cmd->brief && !full)
747             continue;
748         for (md = ml[imeta]; md; md = md->next)
749         {
750             struct record_metadata_attr *attr = md->attributes;
751             wrbuf_printf(w, "\n<md-%s", cmd->name);
752
753             for (; attr; attr = attr->next)
754             {
755                 wrbuf_printf(w, " %s=\"", attr->name);
756                 wrbuf_xmlputs(w, attr->value);
757                 wrbuf_puts(w, "\"");
758             }
759             wrbuf_puts(w, ">");
760             switch (cmd->type)
761             {
762                 case Metadata_type_generic:
763                     wrbuf_xmlputs(w, md->data.text.disp);
764                     break;
765                 case Metadata_type_year:
766                     wrbuf_printf(w, "%d", md->data.number.min);
767                     if (md->data.number.min != md->data.number.max)
768                         wrbuf_printf(w, "-%d", md->data.number.max);
769                     break;
770                 default:
771                     wrbuf_puts(w, "[can't represent]");
772             }
773             wrbuf_printf(w, "</md-%s>", cmd->name);
774         }
775     }
776 }
777
778 static void write_subrecord(struct record *r, WRBUF w,
779         struct conf_service *service, int show_details)
780 {
781     const char *name = session_setting_oneval(
782         client_get_database(r->client), PZ_NAME);
783
784     wrbuf_puts(w, "<location id=\"");
785     wrbuf_xmlputs(w, client_get_database(r->client)->database->url);
786     wrbuf_puts(w, "\" ");
787
788     wrbuf_puts(w, "name=\"");
789     wrbuf_xmlputs(w,  *name ? name : "Unknown");
790     wrbuf_puts(w, "\">");
791
792     write_metadata(w, service, r->metadata, show_details);
793     wrbuf_puts(w, "</location>\n");
794 }
795
796 static void show_raw_record_error(void *data, const char *addinfo)
797 {
798     http_channel_observer_t obs = data;
799     struct http_channel *c = http_channel_observer_chan(obs);
800     struct http_response *rs = c->response;
801
802     http_remove_observer(obs);
803
804     error(rs, PAZPAR2_RECORD_FAIL, addinfo);
805 }
806
807 static void show_raw_record_ok(void *data, const char *buf, size_t sz)
808 {
809     http_channel_observer_t obs = data;
810     struct http_channel *c = http_channel_observer_chan(obs);
811     struct http_response *rs = c->response;
812
813     http_remove_observer(obs);
814
815     wrbuf_write(c->wrbuf, buf, sz);
816     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
817     http_send_response(c);
818 }
819
820
821 static void show_raw_record_ok_binary(void *data, const char *buf, size_t sz)
822 {
823     http_channel_observer_t obs = data;
824     struct http_channel *c = http_channel_observer_chan(obs);
825     struct http_response *rs = c->response;
826
827     http_remove_observer(obs);
828
829     wrbuf_write(c->wrbuf, buf, sz);
830     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
831
832     rs->content_type = "application/octet-stream";
833     http_send_response(c);
834 }
835
836
837 void show_raw_reset(void *data, struct http_channel *c, void *data2)
838 {
839     //struct client *client = data;
840     //client_show_raw_remove(client, data2);
841 }
842
843 static void cmd_record_ready(void *data);
844
845 static void cmd_record(struct http_channel *c)
846 {
847     struct http_response *rs = c->response;
848     struct http_request *rq = c->request;
849     struct http_session *s = locate_session(c);
850     struct record_cluster *rec, *prev_r, *next_r;
851     struct record *r;
852     struct conf_service *service;
853     const char *idstr = http_argbyname(rq, "id");
854     const char *offsetstr = http_argbyname(rq, "offset");
855     const char *binarystr = http_argbyname(rq, "binary");
856     
857     if (!s)
858         return;
859     service = s->psession->service;
860     if (!idstr)
861     {
862         error(rs, PAZPAR2_MISSING_PARAMETER, "id");
863         return;
864     }
865     wrbuf_rewind(c->wrbuf);
866     if (!(rec = show_single_start(s->psession, idstr, &prev_r, &next_r)))
867     {
868         if (session_active_clients(s->psession) == 0)
869         {
870             error(rs, PAZPAR2_RECORD_MISSING, idstr);
871         }
872         else if (session_set_watch(s->psession, SESSION_WATCH_RECORD,
873                               cmd_record_ready, c, c) != 0)
874         {
875             error(rs, PAZPAR2_RECORD_MISSING, idstr);
876         }
877         release_session(c, s);
878         return;
879     }
880     if (offsetstr)
881     {
882         int offset = atoi(offsetstr);
883         const char *syntax = http_argbyname(rq, "syntax");
884         const char *esn = http_argbyname(rq, "esn");
885         int i;
886         struct record*r = rec->records;
887         int binary = 0;
888
889         if (binarystr && *binarystr != '0')
890             binary = 1;
891
892         for (i = 0; i < offset && r; r = r->next, i++)
893             ;
894         if (!r)
895         {
896             error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
897         }
898         else
899         {
900             http_channel_observer_t obs =
901                 http_add_observer(c, r->client, show_raw_reset);
902             int ret = client_show_raw_begin(r->client, r->position,
903                                         syntax, esn, 
904                                         obs /* data */,
905                                         show_raw_record_error,
906                                         (binary ? 
907                                          show_raw_record_ok_binary : 
908                                          show_raw_record_ok),
909                                         (binary ? 1 : 0));
910             if (ret == -1)
911             {
912                 http_remove_observer(obs);
913                 error(rs, PAZPAR2_NO_SESSION, 0);
914             }
915         }
916     }
917     else
918     {
919         wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<record>\n");
920         wrbuf_puts(c->wrbuf, "<recid>");
921         wrbuf_xmlputs(c->wrbuf, rec->recid);
922         wrbuf_puts(c->wrbuf, "</recid>\n");
923         if (prev_r)
924         {
925             wrbuf_puts(c->wrbuf, "<prevrecid>");
926             wrbuf_xmlputs(c->wrbuf, prev_r->recid);
927             wrbuf_puts(c->wrbuf, "</prevrecid>\n");
928         }
929         if (next_r)
930         {
931             wrbuf_puts(c->wrbuf, "<nextrecid>");
932             wrbuf_xmlputs(c->wrbuf, next_r->recid);
933             wrbuf_puts(c->wrbuf, "</nextrecid>\n");
934         }
935         wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", 
936                      session_active_clients(s->psession));
937         write_metadata(c->wrbuf, service, rec->metadata, 1);
938         for (r = rec->records; r; r = r->next)
939             write_subrecord(r, c->wrbuf, service, 1);
940         wrbuf_puts(c->wrbuf, "</record>\n");
941         rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
942         http_send_response(c);
943     }
944     show_single_stop(s->psession, rec);
945     release_session(c, s);
946 }
947
948 static void cmd_record_ready(void *data)
949 {
950     struct http_channel *c = (struct http_channel *) data;
951
952     cmd_record(c);
953 }
954
955 static void show_records(struct http_channel *c, int active)
956 {
957     struct http_request *rq = c->request;
958     struct http_response *rs = c->response;
959     struct http_session *s = locate_session(c);
960     struct record_cluster **rl;
961     struct reclist_sortparms *sp;
962     const char *start = http_argbyname(rq, "start");
963     const char *num = http_argbyname(rq, "num");
964     const char *sort = http_argbyname(rq, "sort");
965     int startn = 0;
966     int numn = 20;
967     int total;
968     Odr_int total_hits;
969     int i;
970
971     if (!s)
972         return;
973
974     // We haven't counted clients yet if we're called on a block release
975     if (active < 0)
976         active = session_active_clients(s->psession);
977
978     if (start)
979         startn = atoi(start);
980     if (num)
981         numn = atoi(num);
982     if (!sort)
983         sort = "relevance";
984     if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
985     {
986         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
987         release_session(c, s);
988         return;
989     }
990
991     
992     rl = show_range_start(s->psession, sp, startn, &numn, &total, &total_hits);
993
994     wrbuf_rewind(c->wrbuf);
995     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<show>\n<status>OK</status>\n");
996     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
997     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
998     wrbuf_printf(c->wrbuf, "<total>" ODR_INT_PRINTF "</total>\n", total_hits);
999     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
1000     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
1001
1002     for (i = 0; i < numn; i++)
1003     {
1004         int ccount;
1005         struct record *p;
1006         struct record_cluster *rec = rl[i];
1007         struct conf_service *service = s->psession->service;
1008
1009         wrbuf_puts(c->wrbuf, "<hit>\n");
1010         write_metadata(c->wrbuf, service, rec->metadata, 0);
1011         for (ccount = 0, p = rl[i]->records; p;  p = p->next, ccount++)
1012             write_subrecord(p, c->wrbuf, service, 0); // subrecs w/o details
1013         if (ccount > 1)
1014             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
1015         if (strstr(sort, "relevance"))
1016             wrbuf_printf(c->wrbuf, "<relevance>%d</relevance>\n",
1017                          rec->relevance_score);
1018         wrbuf_puts(c->wrbuf, "<recid>");
1019         wrbuf_xmlputs(c->wrbuf, rec->recid);
1020         wrbuf_puts(c->wrbuf, "</recid>\n");
1021         wrbuf_puts(c->wrbuf, "</hit>\n");
1022     }
1023
1024     show_range_stop(s->psession, rl);
1025
1026     wrbuf_puts(c->wrbuf, "</show>\n");
1027     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1028     http_send_response(c);
1029     release_session(c, s);
1030 }
1031
1032 static void show_records_ready(void *data)
1033 {
1034     struct http_channel *c = (struct http_channel *) data;
1035
1036     show_records(c, -1);
1037 }
1038
1039 static void cmd_show(struct http_channel *c)
1040 {
1041     struct http_request *rq = c->request;
1042     struct http_session *s = locate_session(c);
1043     const char *block = http_argbyname(rq, "block");
1044     int status;
1045
1046     if (!s)
1047         return;
1048
1049     status = session_active_clients(s->psession);
1050
1051     if (block)
1052     {
1053         if (!strcmp(block, "preferred") && !session_is_preferred_clients_ready(s->psession) && reclist_get_num_records(s->psession->reclist) == 0) {
1054             // if there is already a watch/block. we do not block this one
1055             if (session_set_watch(s->psession, SESSION_WATCH_SHOW_PREF,
1056                                   show_records_ready, c, c) != 0)
1057             {
1058                 yaz_log(c->http_sessions->log_level,
1059                         "%p Session %u: Blocking on cmd_show. Waiting for preferred targets", s, s->session_id);
1060             }
1061             release_session(c,s);
1062             return;
1063
1064         }
1065         else if (status && reclist_get_num_records(s->psession->reclist) == 0)
1066         {
1067             // if there is already a watch/block. we do not block this one
1068             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
1069                                   show_records_ready, c, c) != 0)
1070             {
1071                 yaz_log(c->http_sessions->log_level, "%p Session %u: Blocking on cmd_show", s, s->session_id);
1072             }
1073             release_session(c,s);
1074             return;
1075         }
1076     }
1077     show_records(c, status);
1078     release_session(c,s);
1079 }
1080
1081 static void cmd_ping(struct http_channel *c)
1082 {
1083     struct http_response *rs = c->response;
1084     struct http_session *s = locate_session(c);
1085     if (!s)
1086         return;
1087     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<ping><status>OK</status></ping>";
1088     http_send_response(c);
1089     release_session(c, s);
1090 }
1091
1092 static int utf_8_valid(const char *str)
1093 {
1094     yaz_iconv_t cd = yaz_iconv_open("utf-8", "utf-8");
1095     if (cd)
1096     {
1097         /* check that query is UTF-8 encoded */
1098         char *inbuf = (char *) str; /* we know iconv does not alter this */
1099         size_t inbytesleft = strlen(inbuf);
1100
1101         size_t outbytesleft = strlen(inbuf) + 10;
1102         char *out = xmalloc(outbytesleft);
1103         char *outbuf = out;
1104         size_t r = yaz_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
1105
1106         /* if OK, try flushing the rest  */
1107         if (r != (size_t) (-1))
1108             r = yaz_iconv(cd, 0, 0, &outbuf, &outbytesleft);
1109         yaz_iconv_close(cd);
1110         xfree(out);
1111         if (r == (size_t) (-1))
1112             return 0;
1113     }
1114     return 1;
1115 }
1116
1117 static void cmd_search(struct http_channel *c)
1118 {
1119     struct http_request *rq = c->request;
1120     struct http_response *rs = c->response;
1121     struct http_session *s = locate_session(c);
1122     const char *query = http_argbyname(rq, "query");
1123     const char *filter = http_argbyname(rq, "filter");
1124     const char *maxrecs = http_argbyname(rq, "maxrecs");
1125     const char *startrecs = http_argbyname(rq, "startrecs");
1126     enum pazpar2_error_code code;
1127     const char *addinfo = 0;
1128
1129     if (!s)
1130         return;
1131     if (!query)
1132     {
1133         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
1134         release_session(c,s);
1135         return;
1136     }
1137     if (!utf_8_valid(query))
1138     {
1139         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
1140         release_session(c,s);
1141         return;
1142     }
1143     code = search(s->psession, query, startrecs, maxrecs, filter, &addinfo);
1144     if (code)
1145     {
1146         error(rs, code, addinfo);
1147         release_session(c,s);
1148         return;
1149     }
1150     rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<search><status>OK</status></search>";
1151     http_send_response(c);
1152     release_session(c,s);
1153 }
1154
1155
1156 static void cmd_stat(struct http_channel *c)
1157 {
1158     struct http_response *rs = c->response;
1159     struct http_session *s = locate_session(c);
1160     struct statistics stat;
1161     int clients;
1162
1163     float progress = 0;
1164
1165     if (!s)
1166         return;
1167
1168     clients = session_active_clients(s->psession);
1169     statistics(s->psession, &stat);
1170
1171     if (stat.num_clients > 0) {
1172         progress = (stat.num_clients  - clients) / (float)stat.num_clients;
1173     }
1174
1175     wrbuf_rewind(c->wrbuf);
1176     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<stat>");
1177     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
1178     wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", stat.num_hits);
1179     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
1180     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
1181     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
1182     wrbuf_printf(c->wrbuf, "<connecting>%d</connecting>\n", stat.num_connecting);
1183     wrbuf_printf(c->wrbuf, "<working>%d</working>\n", stat.num_working);
1184     wrbuf_printf(c->wrbuf, "<idle>%d</idle>\n", stat.num_idle);
1185     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
1186     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
1187     wrbuf_printf(c->wrbuf, "<progress>%.2f</progress>\n", progress);
1188     wrbuf_puts(c->wrbuf, "</stat>");
1189     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1190     http_send_response(c);
1191     release_session(c,s);
1192 }
1193
1194 static void cmd_info(struct http_channel *c)
1195 {
1196     char yaz_version_str[20];
1197     struct http_response *rs = c->response;
1198
1199     wrbuf_rewind(c->wrbuf);
1200     wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<info>\n");
1201     wrbuf_puts(c->wrbuf, " <version>\n");
1202     wrbuf_puts(c->wrbuf, "  <pazpar2");
1203 #ifdef PAZPAR2_VERSION_SHA1
1204     wrbuf_printf(c->wrbuf, " sha1=\"%s\"", PAZPAR2_VERSION_SHA1);
1205 #endif
1206     wrbuf_puts(c->wrbuf, ">");
1207     wrbuf_xmlputs(c->wrbuf, VERSION);
1208     wrbuf_puts(c->wrbuf, "</pazpar2>");
1209
1210
1211     yaz_version(yaz_version_str, 0);
1212     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
1213     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
1214     wrbuf_puts(c->wrbuf, "\">");
1215     wrbuf_xmlputs(c->wrbuf, yaz_version_str);
1216     wrbuf_puts(c->wrbuf, "</yaz>\n");
1217
1218     wrbuf_puts(c->wrbuf, " </version>\n");
1219     
1220     info_services(c->server, c->wrbuf);
1221
1222     wrbuf_puts(c->wrbuf, "</info>");
1223     rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
1224     http_send_response(c);
1225 }
1226
1227 struct {
1228     char *name;
1229     void (*fun)(struct http_channel *c);
1230 } commands[] = {
1231     { "init", cmd_init },
1232     { "settings", cmd_settings },
1233     { "stat", cmd_stat },
1234     { "bytarget", cmd_bytarget },
1235     { "show", cmd_show },
1236     { "search", cmd_search },
1237     { "termlist", cmd_termlist },
1238     { "exit", cmd_exit },
1239     { "session-status", cmd_session_status },
1240     { "server-status", cmd_server_status },
1241     { "ping", cmd_ping },
1242     { "record", cmd_record },
1243     { "info", cmd_info },
1244     {0,0}
1245 };
1246
1247 void http_command(struct http_channel *c)
1248 {
1249     const char *command = http_argbyname(c->request, "command");
1250     struct http_response *rs = http_create_response(c);
1251     int i;
1252
1253     c->response = rs;
1254
1255     http_addheader(rs, "Expires", "Thu, 19 Nov 1981 08:52:00 GMT");
1256     http_addheader(rs, "Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
1257
1258     if (!command)
1259     {
1260         error(rs, PAZPAR2_MISSING_PARAMETER, "command");
1261         return;
1262     }
1263     for (i = 0; commands[i].name; i++)
1264         if (!strcmp(commands[i].name, command))
1265         {
1266             (*commands[i].fun)(c);
1267             break;
1268         }
1269     if (!commands[i].name)
1270         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "command");
1271
1272     return;
1273 }
1274
1275 /*
1276  * Local variables:
1277  * c-basic-offset: 4
1278  * c-file-style: "Stroustrup"
1279  * indent-tabs-mode: nil
1280  * End:
1281  * vim: shiftwidth=4 tabstop=8 expandtab
1282  */
1283