session.[ch] replaces logic.c, pazpar2.h
[pazpar2-moved-to-github.git] / src / http.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
24 #include <stdio.h>
25 #ifdef WIN32
26 #include <winsock.h>
27 typedef int socklen_t;
28 #endif
29
30 #if HAVE_SYS_SOCKET_H
31 #include <sys/socket.h>
32 #endif
33
34 #include <sys/types.h>
35
36 #include <yaz/snprintf.h>
37 #if HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40
41 #include <stdlib.h>
42 #include <string.h>
43 #include <ctype.h>
44 #include <fcntl.h>
45 #if HAVE_NETDB_H
46 #include <netdb.h>
47 #endif
48
49 #include <errno.h>
50 #include <assert.h>
51 #include <string.h>
52
53 #if HAVE_NETINET_IN_H
54 #include <netinet/in.h>
55 #endif
56
57 #if HAVE_ARPA_INET_H
58 #include <arpa/inet.h>
59 #endif
60
61 #include <yaz/yaz-util.h>
62 #include <yaz/comstack.h>
63 #include <yaz/nmem.h>
64 #include <yaz/mutex.h>
65
66 #include "session.h"
67 #include "http.h"
68
69 #define MAX_HTTP_HEADER 4096
70
71 #ifdef WIN32
72 #define strncasecmp _strnicmp
73 #define strcasecmp _stricmp
74 #endif
75
76 struct http_buf
77 {
78 #define HTTP_BUF_SIZE 4096
79     char buf[4096];
80     int offset;
81     int len;
82     struct http_buf *next;
83 };
84
85
86 static void proxy_io(IOCHAN i, int event);
87 static struct http_channel *http_channel_create(http_server_t http_server,
88                                                 const char *addr,
89                                                 struct conf_server *server);
90 static void http_channel_destroy(IOCHAN i);
91 static http_server_t http_server_create(void);
92 static void http_server_incref(http_server_t hs);
93
94 struct http_server
95 {
96     struct http_buf *http_buf_freelist;
97     struct http_channel *http_channel_freelist;
98     YAZ_MUTEX mutex;
99     int listener_socket;
100     int ref_count;
101     http_sessions_t http_sessions;
102     struct sockaddr_in *proxy_addr;
103 };
104
105 struct http_channel_observer_s {
106     void *data;
107     void *data2;
108     http_channel_destroy_t destroy;
109     struct http_channel_observer_s *next;
110     struct http_channel *chan;
111 };
112
113
114 const char *http_lookup_header(struct http_header *header,
115                                const char *name)
116 {
117     for (; header; header = header->next)
118         if (!strcasecmp(name, header->name))
119             return header->value;
120     return 0;
121 }
122
123 static struct http_buf *http_buf_create(http_server_t hs)
124 {
125     struct http_buf *r = 0;
126
127     yaz_mutex_enter(hs->mutex);
128     if (hs->http_buf_freelist)
129     {
130         r = hs->http_buf_freelist;
131         hs->http_buf_freelist = hs->http_buf_freelist->next;
132     }
133     yaz_mutex_leave(hs->mutex);
134     if (!r)
135         r = xmalloc(sizeof(struct http_buf));
136     r->offset = 0;
137     r->len = 0;
138     r->next = 0;
139     return r;
140 }
141
142 static void http_buf_destroy(http_server_t hs, struct http_buf *b)
143 {
144     yaz_mutex_enter(hs->mutex);
145     b->next = hs->http_buf_freelist;
146     hs->http_buf_freelist = b;
147     yaz_mutex_leave(hs->mutex);
148 }
149
150 static void http_buf_destroy_queue(http_server_t hs, struct http_buf *b)
151 {
152     struct http_buf *p;
153     while (b)
154     {
155         p = b->next;
156         http_buf_destroy(hs, b);
157         b = p;
158     }
159 }
160
161 static struct http_buf *http_buf_bybuf(http_server_t hs, char *b, int len)
162 {
163     struct http_buf *res = 0;
164     struct http_buf **p = &res;
165
166     while (len)
167     {
168         int tocopy = len;
169         if (tocopy > HTTP_BUF_SIZE)
170             tocopy = HTTP_BUF_SIZE;
171         *p = http_buf_create(hs);
172         memcpy((*p)->buf, b, tocopy);
173         (*p)->len = tocopy;
174         len -= tocopy;
175         b += tocopy;
176         p = &(*p)->next;
177     }
178     return res;
179 }
180
181 // Add a (chain of) buffers to the end of an existing queue.
182 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
183 {
184     while (*queue)
185         queue = &(*queue)->next;
186     *queue = b;
187 }
188
189 static struct http_buf *http_buf_bywrbuf(http_server_t hs, WRBUF wrbuf)
190 {
191     // Heavens to Betsy (buf)!
192     return http_buf_bybuf(hs, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
193 }
194
195 // Non-destructively collapse chain of buffers into a string (max *len)
196 // Return
197 static void http_buf_peek(struct http_buf *b, char *buf, int len)
198 {
199     int rd = 0;
200     while (b && rd < len)
201     {
202         int toread = len - rd;
203         if (toread > b->len)
204             toread = b->len;
205         memcpy(buf + rd, b->buf + b->offset, toread);
206         rd += toread;
207         b = b->next;
208     }
209     buf[rd] = '\0';
210 }
211
212 static int http_buf_size(struct http_buf *b)
213 {
214     int sz = 0;
215     for (; b; b = b->next)
216         sz += b->len;
217     return sz;
218 }
219
220 // Ddestructively munch up to len  from head of queue.
221 static int http_buf_read(http_server_t hs,
222                          struct http_buf **b, char *buf, int len)
223 {
224     int rd = 0;
225     while ((*b) && rd < len)
226     {
227         int toread = len - rd;
228         if (toread > (*b)->len)
229             toread = (*b)->len;
230         memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
231         rd += toread;
232         if (toread < (*b)->len)
233         {
234             (*b)->len -= toread;
235             (*b)->offset += toread;
236             break;
237         }
238         else
239         {
240             struct http_buf *n = (*b)->next;
241             http_buf_destroy(hs, *b);
242             *b = n;
243         }
244     }
245     buf[rd] = '\0';
246     return rd;
247 }
248
249 // Buffers may overlap.
250 static void urldecode(char *i, char *o)
251 {
252     while (*i)
253     {
254         if (*i == '+')
255         {
256             *(o++) = ' ';
257             i++;
258         }
259         else if (*i == '%' && i[1] && i[2])
260         {
261             int v;
262             i++;
263             sscanf(i, "%2x", &v);
264             *o++ = v;
265             i += 2;
266         }
267         else
268             *(o++) = *(i++);
269     }
270     *o = '\0';
271 }
272
273 // Warning: Buffers may not overlap
274 void urlencode(const char *i, char *o)
275 {
276     while (*i)
277     {
278         if (strchr(" /:", *i))
279         {
280             sprintf(o, "%%%.2X", (int) *i);
281             o += 3;
282         }
283         else
284             *(o++) = *i;
285         i++;
286     }
287     *o = '\0';
288 }
289
290 void http_addheader(struct http_response *r, const char *name, const char *value)
291 {
292     struct http_channel *c = r->channel;
293     struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
294     h->name = nmem_strdup(c->nmem, name);
295     h->value = nmem_strdup(c->nmem, value);
296     h->next = r->headers;
297     r->headers = h;
298 }
299
300 const char *http_argbyname(struct http_request *r, const char *name)
301 {
302     struct http_argument *p;
303     if (!name)
304         return 0;
305     for (p = r->arguments; p; p = p->next)
306         if (!strcmp(p->name, name))
307             return p->value;
308     return 0;
309 }
310
311 const char *http_headerbyname(struct http_header *h, const char *name)
312 {
313     for (; h; h = h->next)
314         if (!strcmp(h->name, name))
315             return h->value;
316     return 0;
317 }
318
319 struct http_response *http_create_response(struct http_channel *c)
320 {
321     struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
322     strcpy(r->code, "200");
323     r->msg = "OK";
324     r->channel = c;
325     r->headers = 0;
326     r->payload = 0;
327     r->content_type = "text/xml";
328     return r;
329 }
330
331
332 static const char *next_crlf(const char *cp, size_t *skipped)
333 {
334     const char *next_cp = strchr(cp, '\n');
335     if (next_cp)
336     {
337         if (next_cp > cp && next_cp[-1] == '\r')
338             *skipped = next_cp - cp - 1;
339         else
340             *skipped = next_cp - cp;
341         next_cp++;
342     }
343     return next_cp;
344 }
345
346 // Check if buf contains a package (minus payload)
347 static int package_check(const char *buf, int sz)
348 {
349     int content_len = 0;
350     int len = 0;
351
352     while (*buf)
353     {
354         size_t skipped = 0;
355         const char *b = next_crlf(buf, &skipped);
356
357         if (!b)
358         {
359             // we did not find CRLF.. See if buffer is too large..
360             if (sz >= MAX_HTTP_HEADER-1)
361                 return MAX_HTTP_HEADER-1; // yes. Return that (will fail later)
362             break;
363         }
364         len += (b - buf);
365         if (skipped == 0)
366         {
367             // CRLF CRLF , i.e. end of header
368             if (len + content_len <= sz)
369                 return len + content_len;
370             break;
371         }
372         buf = b;
373         // following first skip of \r\n so that we don't consider Method
374         if (!strncasecmp(buf, "Content-Length:", 15))
375         {
376             const char *cp = buf+15;
377             while (*cp == ' ')
378                 cp++;
379             content_len = 0;
380             while (*cp && isdigit(*(const unsigned char *)cp))
381                 content_len = content_len*10 + (*cp++ - '0');
382             if (content_len < 0) /* prevent negative offsets */
383                 content_len = 0;
384         }
385     }
386     return 0;     // incomplete request
387 }
388
389 // Check if we have a request. Return 0 or length
390 static int request_check(struct http_buf *queue)
391 {
392     char tmp[MAX_HTTP_HEADER];
393
394     // only peek at the header..
395     http_buf_peek(queue, tmp, MAX_HTTP_HEADER-1);
396     // still we only return non-zero if the complete request is received..
397     return package_check(tmp, http_buf_size(queue));
398 }
399
400 struct http_response *http_parse_response_buf(struct http_channel *c, const char *buf, int len)
401 {
402     char tmp[MAX_HTTP_HEADER];
403     struct http_response *r = http_create_response(c);
404     char *p, *p2;
405     struct http_header **hp = &r->headers;
406
407     if (len >= MAX_HTTP_HEADER)
408         return 0;
409     memcpy(tmp, buf, len);
410     for (p = tmp; *p && *p != ' '; p++) // Skip HTTP version
411         ;
412     p++;
413     // Response code
414     for (p2 = p; *p2 && *p2 != ' ' && p2 - p < 3; p2++)
415         r->code[p2 - p] = *p2;
416     if (!(p = strstr(tmp, "\r\n")))
417         return 0;
418     p += 2;
419     while (*p)
420     {
421         if (!(p2 = strstr(p, "\r\n")))
422             return 0;
423         if (p == p2) // End of headers
424             break;
425         else
426         {
427             struct http_header *h = *hp = nmem_malloc(c->nmem, sizeof(*h));
428             char *value = strchr(p, ':');
429             if (!value)
430                 return 0;
431             *(value++) = '\0';
432             h->name = nmem_strdup(c->nmem, p);
433             while (isspace(*(const unsigned char *) value))
434                 value++;
435             if (value >= p2)  // Empty header;
436             {
437                 h->value = "";
438                 p = p2 + 2;
439                 continue;
440             }
441             *p2 = '\0';
442             h->value = nmem_strdup(c->nmem, value);
443             h->next = 0;
444             hp = &h->next;
445             p = p2 + 2;
446         }
447     }
448     return r;
449 }
450
451 static int http_parse_arguments(struct http_request *r, NMEM nmem,
452                                 const char *args)
453 {
454     const char *p2 = args;
455
456     while (*p2)
457     {
458         struct http_argument *a;
459         const char *equal = strchr(p2, '=');
460         const char *eoa = strchr(p2, '&');
461         if (!equal)
462         {
463             yaz_log(YLOG_WARN, "Expected '=' in argument");
464             return -1;
465         }
466         if (!eoa)
467             eoa = equal + strlen(equal); // last argument
468         else if (equal > eoa)
469         {
470             yaz_log(YLOG_WARN, "Missing '&' in argument");
471             return -1;
472         }
473         a = nmem_malloc(nmem, sizeof(struct http_argument));
474         a->name = nmem_strdupn(nmem, p2, equal - p2);
475         a->value = nmem_strdupn(nmem, equal+1, eoa - equal - 1);
476         urldecode(a->name, a->name);
477         urldecode(a->value, a->value);
478         a->next = r->arguments;
479         r->arguments = a;
480         p2 = eoa;
481         while (*p2 == '&')
482             p2++;
483     }
484     return 0;
485 }
486
487 struct http_request *http_parse_request(struct http_channel *c,
488                                         struct http_buf **queue,
489                                         int len)
490 {
491     struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
492     char *p, *p2;
493     char *start = nmem_malloc(c->nmem, len+1);
494     char *buf = start;
495
496     if (http_buf_read(c->http_server, queue, buf, len) < len)
497     {
498         yaz_log(YLOG_WARN, "http_buf_read < len (%d)", len);
499         return 0;
500     }
501     r->search = "";
502     r->channel = c;
503     r->arguments = 0;
504     r->headers = 0;
505     r->content_buf = 0;
506     r->content_len = 0;
507     // Parse first line
508     for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
509         *(p2++) = *p;
510     if (*p != ' ')
511     {
512         yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
513         return 0;
514     }
515     *p2 = '\0';
516
517     if (!(buf = strchr(buf, ' ')))
518     {
519         yaz_log(YLOG_WARN, "Missing Request-URI in HTTP request");
520         return 0;
521     }
522     buf++;
523     if (!(p = strchr(buf, ' ')))
524     {
525         yaz_log(YLOG_WARN, "HTTP Request-URI not terminated (too long?)");
526         return 0;
527     }
528     *(p++) = '\0';
529     if ((p2 = strchr(buf, '?'))) // Do we have arguments?
530         *(p2++) = '\0';
531     r->path = nmem_strdup(c->nmem, buf);
532     if (p2)
533     {
534         r->search = nmem_strdup(c->nmem, p2);
535         // Parse Arguments
536         http_parse_arguments(r, c->nmem, p2);
537     }
538     buf = p;
539
540     if (strncmp(buf, "HTTP/", 5))
541         strcpy(r->http_version, "1.0");
542     else
543     {
544         size_t skipped;
545         buf += 5; // strlen("HTTP/")
546
547         p = (char*) next_crlf(buf, &skipped);
548         if (!p || skipped < 3 || skipped > 5)
549             return 0;
550
551         memcpy(r->http_version, buf, skipped);
552         r->http_version[skipped] = '\0';
553         buf = p;
554     }
555     strcpy(c->version, r->http_version);
556
557     r->headers = 0;
558     while (*buf)
559     {
560         size_t skipped;
561
562         p = (char *) next_crlf(buf, &skipped);
563         if (!p)
564         {
565             return 0;
566         }
567         else if (skipped == 0)
568         {
569             buf = p;
570             break;
571         }
572         else
573         {
574             char *cp;
575             char *n_v = nmem_malloc(c->nmem, skipped+1);
576             struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
577
578             memcpy(n_v, buf, skipped);
579             n_v[skipped] = '\0';
580
581             if (!(cp = strchr(n_v, ':')))
582                 return 0;
583             h->name = nmem_strdupn(c->nmem, n_v, cp - n_v);
584             cp++;
585             while (isspace(*cp))
586                 cp++;
587             h->value = nmem_strdup(c->nmem, cp);
588             h->next = r->headers;
589             r->headers = h;
590             buf = p;
591         }
592     }
593
594     // determine if we do keep alive
595     if (!strcmp(c->version, "1.0"))
596     {
597         const char *v = http_lookup_header(r->headers, "Connection");
598         if (v && !strcmp(v, "Keep-Alive"))
599             c->keep_alive = 1;
600         else
601             c->keep_alive = 0;
602     }
603     else
604     {
605         const char *v = http_lookup_header(r->headers, "Connection");
606         if (v && !strcmp(v, "close"))
607             c->keep_alive = 0;
608         else
609             c->keep_alive = 1;
610     }
611     if (buf < start + len)
612     {
613         const char *content_type = http_lookup_header(r->headers,
614                                                       "Content-Type");
615         r->content_len = start + len - buf;
616         r->content_buf = buf;
617
618         if (!yaz_strcmp_del("application/x-www-form-urlencoded",
619                             content_type, "; "))
620         {
621             http_parse_arguments(r, c->nmem, r->content_buf);
622         }
623     }
624     return r;
625 }
626
627 static struct http_buf *http_serialize_response(struct http_channel *c,
628         struct http_response *r)
629 {
630     struct http_header *h;
631
632     wrbuf_rewind(c->wrbuf);
633     wrbuf_printf(c->wrbuf, "HTTP/%s %s %s\r\n", c->version, r->code, r->msg);
634     for (h = r->headers; h; h = h->next)
635         wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
636     if (r->payload)
637     {
638         wrbuf_printf(c->wrbuf, "Content-Length: %d\r\n", r->payload ?
639                 (int) strlen(r->payload) : 0);
640         wrbuf_printf(c->wrbuf, "Content-Type: %s\r\n", r->content_type);
641         if (!strcmp(r->content_type, "text/xml"))
642         {
643             xmlDoc *doc = xmlParseMemory(r->payload, strlen(r->payload));
644             if (doc)
645             {
646                 xmlFreeDoc(doc);
647             }
648             else
649             {
650                 yaz_log(YLOG_WARN, "Sending non-wellformed "
651                         "response (bug #1162");
652                 yaz_log(YLOG_WARN, "payload: %s", r->payload);
653             }
654         }
655     }
656     wrbuf_puts(c->wrbuf, "\r\n");
657
658     if (r->payload)
659         wrbuf_puts(c->wrbuf, r->payload);
660
661     return http_buf_bywrbuf(c->http_server, c->wrbuf);
662 }
663
664 // Serialize a HTTP request
665 static struct http_buf *http_serialize_request(struct http_request *r)
666 {
667     struct http_channel *c = r->channel;
668     struct http_header *h;
669
670     wrbuf_rewind(c->wrbuf);
671     wrbuf_printf(c->wrbuf, "%s %s%s%s", r->method, r->path,
672                  *r->search ? "?" : "", r->search);
673
674     wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
675
676     for (h = r->headers; h; h = h->next)
677         wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
678
679     wrbuf_puts(c->wrbuf, "\r\n");
680
681     if (r->content_buf)
682         wrbuf_write(c->wrbuf, r->content_buf, r->content_len);
683
684 #if 0
685     yaz_log(YLOG_LOG, "WRITING TO PROXY:\n%s\n----",
686             wrbuf_cstr(c->wrbuf));
687 #endif
688     return http_buf_bywrbuf(c->http_server, c->wrbuf);
689 }
690
691
692 static int http_weshouldproxy(struct http_request *rq)
693 {
694     struct http_channel *c = rq->channel;
695     if (c->server->http_server->proxy_addr && !strstr(rq->path, "search.pz2"))
696         return 1;
697     return 0;
698 }
699
700
701 struct http_header * http_header_append(struct http_channel *ch, 
702                                         struct http_header * hp, 
703                                         const char *name, 
704                                         const char *value)
705 {
706     struct http_header *hpnew = 0; 
707
708     if (!hp | !ch)
709         return 0;
710
711     while (hp && hp->next)
712         hp = hp->next;
713
714     if(name && strlen(name)&& value && strlen(value)){
715         hpnew = nmem_malloc(ch->nmem, sizeof *hpnew);
716         hpnew->name = nmem_strdup(ch->nmem, name);
717         hpnew->value = nmem_strdup(ch->nmem, value);
718         
719         hpnew->next = 0;
720         hp->next = hpnew;
721         hp = hp->next;
722         
723         return hpnew;
724     }
725
726     return hp;
727 }
728
729    
730 static int is_inprogress(void)
731 {
732 #ifdef WIN32
733     if (WSAGetLastError() == WSAEWOULDBLOCK)
734         return 1;
735 #else
736     if (errno == EINPROGRESS)
737         return 1;
738 #endif
739     return 0;
740
741
742 static void enable_nonblock(int sock)
743 {
744     int flags;
745 #ifdef WIN32
746     flags = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
747     if (ioctlsocket(sock, FIONBIO, &flags) < 0)
748         yaz_log(YLOG_FATAL|YLOG_ERRNO, "ioctlsocket");
749 #else
750     if ((flags = fcntl(sock, F_GETFL, 0)) < 0) 
751         yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
752     if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
753         yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
754 #endif
755 }
756
757 static int http_proxy(struct http_request *rq)
758 {
759     struct http_channel *c = rq->channel;
760     struct http_proxy *p = c->proxy;
761     struct http_header *hp;
762     struct http_buf *requestbuf;
763     char server_port[16] = "";
764     struct conf_server *ser = c->server;
765
766     if (!p) // This is a new connection. Create a proxy channel
767     {
768         int sock;
769         struct protoent *pe;
770         int one = 1;
771
772         if (!(pe = getprotobyname("tcp"))) {
773             abort();
774         }
775         if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
776         {
777             yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
778             return -1;
779         }
780         if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
781                         &one, sizeof(one)) < 0)
782             abort();
783         enable_nonblock(sock);
784         if (connect(sock, (struct sockaddr *)
785                     c->server->http_server->proxy_addr, 
786                     sizeof(*c->server->http_server->proxy_addr)) < 0)
787         {
788             if (!is_inprogress()) 
789             {
790                 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
791                 return -1;
792             }
793         }
794         p = xmalloc(sizeof(struct http_proxy));
795         p->oqueue = 0;
796         p->channel = c;
797         p->first_response = 1;
798         c->proxy = p;
799         // We will add EVENT_OUTPUT below
800         p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
801         iochan_setdata(p->iochan, p);
802
803         iochan_add(ser->iochan_man, p->iochan);
804     }
805
806     // Do _not_ modify Host: header, just checking it's existence
807
808     if (!http_lookup_header(rq->headers, "Host"))
809     {
810         yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
811         return -1;
812     }
813     
814     // Add new header about paraz2 version, host, remote client address, etc.
815     {
816         char server_via[128];
817
818         hp = rq->headers;
819         hp = http_header_append(c, hp, 
820                                 "X-Pazpar2-Version", PACKAGE_VERSION);
821         hp = http_header_append(c, hp, 
822                                 "X-Pazpar2-Server-Host", ser->host);
823         sprintf(server_port, "%d",  ser->port);
824         hp = http_header_append(c, hp, 
825                                 "X-Pazpar2-Server-Port", server_port);
826         yaz_snprintf(server_via, sizeof(server_via), 
827                      "1.1 %s:%s (%s/%s)",  
828                      ser->host ? ser->host : "@",
829                      server_port, PACKAGE_NAME, PACKAGE_VERSION);
830         hp = http_header_append(c, hp, "Via" , server_via);
831         hp = http_header_append(c, hp, "X-Forwarded-For", c->addr);
832     }
833     
834     requestbuf = http_serialize_request(rq);
835
836     http_buf_enqueue(&p->oqueue, requestbuf);
837     iochan_setflag(p->iochan, EVENT_OUTPUT);
838     return 0;
839 }
840
841 void http_send_response(struct http_channel *ch)
842 {
843     struct http_response *rs = ch->response;
844     struct http_buf *hb;
845
846     assert(rs);
847     hb = http_serialize_response(ch, rs);
848     if (!hb)
849     {
850         yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
851         http_channel_destroy(ch->iochan);
852     }
853     else
854     {
855         http_buf_enqueue(&ch->oqueue, hb);
856         iochan_setflag(ch->iochan, EVENT_OUTPUT);
857         ch->state = Http_Idle;
858     }
859 }
860
861 static void http_error(struct http_channel *hc, int no, const char *msg)
862 {
863     struct http_response *rs = http_create_response(hc);
864
865     hc->response = rs;
866     hc->keep_alive = 0;  // not keeping this HTTP session alive
867
868     sprintf(rs->code, "%d", no);
869
870     rs->msg = nmem_strdup(hc->nmem, msg);
871     rs->payload = nmem_malloc(hc->nmem, 100);
872     yaz_snprintf(rs->payload, 99, "<error>HTTP Error %d: %s</error>\n",
873                  no, msg);
874     http_send_response(hc);
875 }
876
877 static void http_io(IOCHAN i, int event)
878 {
879     struct http_channel *hc = iochan_getdata(i);
880
881     switch (event)
882     {
883         int res, reqlen;
884         struct http_buf *htbuf;
885
886         case EVENT_INPUT:
887             htbuf = http_buf_create(hc->http_server);
888             res = recv(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1, 0);
889             if (res == -1 && errno == EAGAIN)
890             {
891                 http_buf_destroy(hc->http_server, htbuf);
892                 return;
893             }
894             if (res <= 0)
895             {
896                 http_buf_destroy(hc->http_server, htbuf);
897                 http_channel_destroy(i);
898                 return;
899             }
900             htbuf->buf[res] = '\0';
901             htbuf->len = res;
902             http_buf_enqueue(&hc->iqueue, htbuf);
903
904             while (1)
905             {
906                 if (hc->state == Http_Busy)
907                     return;
908                 reqlen = request_check(hc->iqueue);
909                 if (reqlen <= 2)
910                     return;
911                 // we have a complete HTTP request
912                 nmem_reset(hc->nmem);
913                 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
914                 {
915                     yaz_log(YLOG_WARN, "Failed to parse request");
916                     http_error(hc, 400, "Bad Request");
917                     return;
918                 }
919                 hc->response = 0;
920                 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
921                         hc->request->path,
922                         *hc->request->search ? "?" : "",
923                         hc->request->search);
924                 if (hc->request->content_buf)
925                     yaz_log(YLOG_LOG, "%s", hc->request->content_buf);
926                 if (http_weshouldproxy(hc->request))
927                     http_proxy(hc->request);
928                 else
929                 {
930                     // Execute our business logic!
931                     hc->state = Http_Busy;
932                     http_command(hc);
933                 }
934             }
935             break;
936         case EVENT_OUTPUT:
937             if (hc->oqueue)
938             {
939                 struct http_buf *wb = hc->oqueue;
940                 res = send(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len, 0);
941                 if (res <= 0)
942                 {
943                     yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
944                     http_channel_destroy(i);
945                     return;
946                 }
947                 if (res == wb->len)
948                 {
949                     hc->oqueue = hc->oqueue->next;
950                     http_buf_destroy(hc->http_server, wb);
951                 }
952                 else
953                 {
954                     wb->len -= res;
955                     wb->offset += res;
956                 }
957                 if (!hc->oqueue) {
958                     if (!hc->keep_alive)
959                     {
960                         http_channel_destroy(i);
961                         return;
962                     }
963                     else
964                     {
965                         iochan_clearflag(i, EVENT_OUTPUT);
966                         if (hc->iqueue)
967                             iochan_setevent(hc->iochan, EVENT_INPUT);
968                     }
969                 }
970             }
971
972             if (!hc->oqueue && hc->proxy && !hc->proxy->iochan) 
973                 http_channel_destroy(i); // Server closed; we're done
974             break;
975         default:
976             yaz_log(YLOG_WARN, "Unexpected event on connection");
977             http_channel_destroy(i);
978     }
979 }
980
981 // Handles I/O on a client connection to a backend web server (proxy mode)
982 static void proxy_io(IOCHAN pi, int event)
983 {
984     struct http_proxy *pc = iochan_getdata(pi);
985     struct http_channel *hc = pc->channel;
986
987     switch (event)
988     {
989         int res;
990         struct http_buf *htbuf;
991
992         case EVENT_INPUT:
993             htbuf = http_buf_create(hc->http_server);
994             res = recv(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1, 0);
995             if (res == 0 || (res < 0 && !is_inprogress()))
996             {
997                 if (hc->oqueue)
998                 {
999                     yaz_log(YLOG_WARN, "Proxy read came up short");
1000                     // Close channel and alert client HTTP channel that we're gone
1001                     http_buf_destroy(hc->http_server, htbuf);
1002 #ifdef WIN32
1003                     closesocket(iochan_getfd(pi));
1004 #else
1005                     close(iochan_getfd(pi));
1006 #endif
1007                     iochan_destroy(pi);
1008                     pc->iochan = 0;
1009                 }
1010                 else
1011                 {
1012                     http_channel_destroy(hc->iochan);
1013                     return;
1014                 }
1015             }
1016             else
1017             {
1018                 htbuf->buf[res] = '\0';
1019                 htbuf->offset = 0;
1020                 htbuf->len = res;
1021                 // Write any remaining payload
1022                 if (htbuf->len - htbuf->offset > 0)
1023                     http_buf_enqueue(&hc->oqueue, htbuf);
1024             }
1025             iochan_setflag(hc->iochan, EVENT_OUTPUT);
1026             break;
1027         case EVENT_OUTPUT:
1028             if (!(htbuf = pc->oqueue))
1029             {
1030                 iochan_clearflag(pi, EVENT_OUTPUT);
1031                 return;
1032             }
1033             res = send(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len, 0);
1034             if (res <= 0)
1035             {
1036                 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
1037                 http_channel_destroy(hc->iochan);
1038                 return;
1039             }
1040             if (res == htbuf->len)
1041             { 
1042                 struct http_buf *np = htbuf->next;
1043                 http_buf_destroy(hc->http_server, htbuf);
1044                 pc->oqueue = np;
1045             }
1046             else
1047             {
1048                 htbuf->len -= res;
1049                 htbuf->offset += res;
1050             }
1051
1052             if (!pc->oqueue) {
1053                 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
1054             }
1055             break;
1056         default:
1057             yaz_log(YLOG_WARN, "Unexpected event on connection");
1058             http_channel_destroy(hc->iochan);
1059     }
1060 }
1061
1062 static void http_fire_observers(struct http_channel *c);
1063 static void http_destroy_observers(struct http_channel *c);
1064
1065 // Cleanup channel
1066 static void http_channel_destroy(IOCHAN i)
1067 {
1068     struct http_channel *s = iochan_getdata(i);
1069     http_server_t http_server;
1070
1071     if (s->proxy)
1072     {
1073         if (s->proxy->iochan)
1074         {
1075 #ifdef WIN32
1076             closesocket(iochan_getfd(s->proxy->iochan));
1077 #else
1078             close(iochan_getfd(s->proxy->iochan));
1079 #endif
1080             iochan_destroy(s->proxy->iochan);
1081         }
1082         http_buf_destroy_queue(s->http_server, s->proxy->oqueue);
1083         xfree(s->proxy);
1084     }
1085     http_buf_destroy_queue(s->http_server, s->iqueue);
1086     http_buf_destroy_queue(s->http_server, s->oqueue);
1087     http_fire_observers(s);
1088     http_destroy_observers(s);
1089
1090     http_server = s->http_server; /* save it for destroy (decref) */
1091
1092     yaz_mutex_enter(s->http_server->mutex);
1093     s->next = s->http_server->http_channel_freelist;
1094     s->http_server->http_channel_freelist = s;
1095     yaz_mutex_leave(s->http_server->mutex);
1096
1097     http_server_destroy(http_server);
1098
1099 #ifdef WIN32
1100     closesocket(iochan_getfd(i));
1101 #else
1102     close(iochan_getfd(i));
1103 #endif
1104     iochan_destroy(i);
1105 }
1106
1107 static struct http_channel *http_channel_create(http_server_t hs,
1108                                                 const char *addr,
1109                                                 struct conf_server *server)
1110 {
1111     struct http_channel *r;
1112
1113     yaz_mutex_enter(hs->mutex);
1114     r = hs->http_channel_freelist;
1115     if (r)
1116         hs->http_channel_freelist = r->next;
1117     yaz_mutex_leave(hs->mutex);
1118
1119     if (r)
1120     {
1121         nmem_reset(r->nmem);
1122         wrbuf_rewind(r->wrbuf);
1123     }
1124     else
1125     {
1126         r = xmalloc(sizeof(struct http_channel));
1127         r->nmem = nmem_create();
1128         r->wrbuf = wrbuf_alloc();
1129     }
1130     http_server_incref(hs);
1131     r->http_server = hs;
1132     r->http_sessions = hs->http_sessions;
1133     assert(r->http_sessions);
1134     r->server = server;
1135     r->proxy = 0;
1136     r->iochan = 0;
1137     r->iqueue = r->oqueue = 0;
1138     r->state = Http_Idle;
1139     r->keep_alive = 0;
1140     r->request = 0;
1141     r->response = 0;
1142     if (!addr)
1143     {
1144         yaz_log(YLOG_WARN, "Invalid HTTP forward address");
1145         exit(1);
1146     }
1147     strcpy(r->addr, addr);
1148     r->observers = 0;
1149     return r;
1150 }
1151
1152
1153 /* Accept a new command connection */
1154 static void http_accept(IOCHAN i, int event)
1155 {
1156     struct sockaddr_in addr;
1157     int fd = iochan_getfd(i);
1158     socklen_t len;
1159     int s;
1160     IOCHAN c;
1161     struct http_channel *ch;
1162     struct conf_server *server = iochan_getdata(i);
1163
1164     len = sizeof addr;
1165     if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
1166     {
1167         yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
1168         return;
1169     }
1170     enable_nonblock(s);
1171
1172     yaz_log(YLOG_DEBUG, "New command connection");
1173     c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
1174     
1175     ch = http_channel_create(server->http_server, inet_ntoa(addr.sin_addr),
1176                              server);
1177     ch->iochan = c;
1178     iochan_setdata(c, ch);
1179     iochan_add(server->iochan_man, c);
1180 }
1181
1182 /* Create a http-channel listener, syntax [host:]port */
1183 int http_init(const char *addr, struct conf_server *server)
1184 {
1185     IOCHAN c;
1186     int l;
1187     struct protoent *p;
1188     struct sockaddr_in myaddr;
1189     int one = 1;
1190     const char *pp;
1191     short port;
1192
1193     yaz_log(YLOG_LOG, "HTTP listener %s", addr);
1194
1195     memset(&myaddr, 0, sizeof myaddr);
1196     myaddr.sin_family = AF_INET;
1197     pp = strchr(addr, ':');
1198     if (pp)
1199     {
1200         WRBUF w = wrbuf_alloc();
1201         struct hostent *he;
1202
1203         wrbuf_write(w, addr, pp - addr);
1204         wrbuf_puts(w, "");
1205
1206         he = gethostbyname(wrbuf_cstr(w));
1207         wrbuf_destroy(w);
1208         if (!he)
1209         {
1210             yaz_log(YLOG_FATAL, "Unable to resolve '%s'", addr);
1211             return 1;
1212         }
1213         memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1214         port = atoi(pp + 1);
1215     }
1216     else
1217     {
1218         port = atoi(addr);
1219         myaddr.sin_addr.s_addr = INADDR_ANY;
1220     }
1221
1222     myaddr.sin_port = htons(port);
1223
1224     if (!(p = getprotobyname("tcp"))) {
1225         return 1;
1226     }
1227     if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
1228         yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
1229     if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
1230                     &one, sizeof(one)) < 0)
1231         return 1;
1232
1233     if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0) 
1234     {
1235         yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
1236         return 1;
1237     }
1238     if (listen(l, SOMAXCONN) < 0) 
1239     {
1240         yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
1241         return 1;
1242     }
1243
1244     server->http_server = http_server_create();
1245
1246     server->http_server->listener_socket = l;
1247
1248     c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
1249     iochan_setdata(c, server);
1250
1251     iochan_add(server->iochan_man, c);
1252     return 0;
1253 }
1254
1255 void http_close_server(struct conf_server *server)
1256 {
1257     /* break the event_loop (select) by closing down the HTTP listener sock */
1258     if (server->http_server->listener_socket)
1259     {
1260 #ifdef WIN32
1261         closesocket(server->http_server->listener_socket);
1262 #else
1263         close(server->http_server->listener_socket);
1264 #endif
1265     }
1266 }
1267
1268 void http_set_proxyaddr(const char *host, struct conf_server *server)
1269 {
1270     const char *p;
1271     short port;
1272     struct hostent *he;
1273     WRBUF w = wrbuf_alloc();
1274
1275     yaz_log(YLOG_LOG, "HTTP backend  %s", host);
1276
1277     p = strchr(host, ':');
1278     if (p)
1279     {
1280         port = atoi(p + 1);
1281         wrbuf_write(w, host, p - host);
1282         wrbuf_puts(w, "");
1283     }
1284     else
1285     {
1286         port = 80;
1287         wrbuf_puts(w, host);
1288     }
1289     if (!(he = gethostbyname(wrbuf_cstr(w))))
1290     {
1291         fprintf(stderr, "Failed to lookup '%s'\n", wrbuf_cstr(w));
1292         exit(1);
1293     }
1294     wrbuf_destroy(w);
1295
1296     server->http_server->proxy_addr = xmalloc(sizeof(struct sockaddr_in));
1297     server->http_server->proxy_addr->sin_family = he->h_addrtype;
1298     memcpy(&server->http_server->proxy_addr->sin_addr.s_addr,
1299            he->h_addr_list[0], he->h_length);
1300     server->http_server->proxy_addr->sin_port = htons(port);
1301 }
1302
1303 static void http_fire_observers(struct http_channel *c)
1304 {
1305     http_channel_observer_t p = c->observers;
1306     while (p)
1307     {
1308         p->destroy(p->data, c, p->data2);
1309         p = p->next;
1310     }
1311 }
1312
1313 static void http_destroy_observers(struct http_channel *c)
1314 {
1315     while (c->observers)
1316     {
1317         http_channel_observer_t obs = c->observers;
1318         c->observers = obs->next;
1319         xfree(obs);
1320     }
1321 }
1322
1323 http_channel_observer_t http_add_observer(struct http_channel *c, void *data,
1324                                           http_channel_destroy_t des)
1325 {
1326     http_channel_observer_t obs = xmalloc(sizeof(*obs));
1327     obs->chan = c;
1328     obs->data = data;
1329     obs->data2 = 0;
1330     obs->destroy= des;
1331     obs->next = c->observers;
1332     c->observers = obs;
1333     return obs;
1334 }
1335
1336 void http_remove_observer(http_channel_observer_t obs)
1337 {
1338     struct http_channel *c = obs->chan;
1339     http_channel_observer_t found, *p = &c->observers;
1340     while (*p != obs)
1341         p = &(*p)->next;
1342     found = *p;
1343     assert(found);
1344     *p = (*p)->next;
1345     xfree(found);
1346 }
1347
1348 struct http_channel *http_channel_observer_chan(http_channel_observer_t obs)
1349 {
1350     return obs->chan;
1351 }
1352
1353 void http_observer_set_data2(http_channel_observer_t obs, void *data2)
1354 {
1355     obs->data2 = data2;
1356 }
1357
1358 http_server_t http_server_create(void)
1359 {
1360     http_server_t hs = xmalloc(sizeof(*hs));
1361     hs->mutex = 0;
1362     hs->proxy_addr = 0;
1363     hs->ref_count = 1;
1364     hs->http_buf_freelist = 0;
1365     hs->http_channel_freelist = 0;
1366     hs->http_sessions = 0;
1367     return hs;
1368 }
1369
1370 void http_server_destroy(http_server_t hs)
1371 {
1372     if (hs)
1373     {
1374         int r;
1375
1376         if (hs->mutex)
1377         {
1378             yaz_mutex_enter(hs->mutex);
1379             r = --(hs->ref_count);
1380             yaz_mutex_leave(hs->mutex);
1381         }
1382         else
1383             r = --(hs->ref_count);
1384
1385         if (r == 0)
1386         {
1387             struct http_buf *b = hs->http_buf_freelist;
1388             struct http_channel *c = hs->http_channel_freelist;
1389             while (b)
1390             {
1391                 struct http_buf *b_next = b->next;
1392                 xfree(b);
1393                 b = b_next;
1394             }
1395             while (c)
1396             {
1397                 struct http_channel *c_next = c->next;
1398                 nmem_destroy(c->nmem);
1399                 wrbuf_destroy(c->wrbuf);
1400                 xfree(c);
1401                 c = c_next;
1402             }
1403             http_sessions_destroy(hs->http_sessions);
1404             xfree(hs->proxy_addr);
1405             yaz_mutex_destroy(&hs->mutex);
1406             xfree(hs);
1407         }
1408     }
1409 }
1410
1411 void http_server_incref(http_server_t hs)
1412 {
1413     assert(hs);
1414     yaz_mutex_enter(hs->mutex);
1415     (hs->ref_count)++;
1416     yaz_mutex_leave(hs->mutex);
1417 }
1418
1419 void http_mutex_init(struct conf_server *server)
1420 {
1421     assert(server);
1422
1423     assert(server->http_server->mutex == 0);
1424     yaz_mutex_create(&server->http_server->mutex);
1425     server->http_server->http_sessions = http_sessions_create();
1426 }
1427
1428 /*
1429  * Local variables:
1430  * c-basic-offset: 4
1431  * c-file-style: "Stroustrup"
1432  * indent-tabs-mode: nil
1433  * End:
1434  * vim: shiftwidth=4 tabstop=8 expandtab
1435  */
1436