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