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