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