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