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