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