removed unused code in comments
[pazpar2-moved-to-github.git] / src / http.c
1 /* $Id: http.c,v 1.25 2007-04-11 11:10:05 marc 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 <unistd.h>
27 #include <stdlib.h>
28 #include <strings.h>
29 #include <ctype.h>
30 #include <fcntl.h>
31 #include <netdb.h>
32 #include <errno.h>
33 #include <assert.h>
34 #include <string.h>
35
36 #if HAVE_CONFIG_H
37 #include <cconfig.h>
38 #endif
39
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include <netdb.h>
43
44 #include <yaz/yaz-util.h>
45 #include <yaz/comstack.h>
46 #include <yaz/nmem.h>
47
48 #include "cconfig.h"
49 #include "util.h"
50 #include "eventl.h"
51 #include "pazpar2.h"
52 #include "http.h"
53 #include "http_command.h"
54
55 static void proxy_io(IOCHAN i, int event);
56 static struct http_channel *http_create(const char *addr);
57 static void http_destroy(IOCHAN i);
58
59 extern IOCHAN channel_list;
60 extern struct parameters global_parameters;
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 static struct http_buf *http_buf_create()
70 {
71     struct http_buf *r;
72
73     if (http_buf_freelist)
74     {
75         r = http_buf_freelist;
76         http_buf_freelist = http_buf_freelist->next;
77     }
78     else
79         r = xmalloc(sizeof(struct http_buf));
80     r->offset = 0;
81     r->len = 0;
82     r->next = 0;
83     return r;
84 }
85
86 static void http_buf_destroy(struct http_buf *b)
87 {
88     b->next = http_buf_freelist;
89     http_buf_freelist = b;
90 }
91
92 static void http_buf_destroy_queue(struct http_buf *b)
93 {
94     struct http_buf *p;
95     while (b)
96     {
97         p = b->next;
98         http_buf_destroy(b);
99         b = p;
100     }
101 }
102
103 #ifdef GAGA
104 // Calculate length of chain
105 static int http_buf_len(struct http_buf *b)
106 {
107     int sum = 0;
108     for (; b; b = b->next)
109         sum += b->len;
110     return sum;
111 }
112 #endif
113
114 static struct http_buf *http_buf_bybuf(char *b, int len)
115 {
116     struct http_buf *res = 0;
117     struct http_buf **p = &res;
118
119     while (len)
120     {
121         int tocopy = len;
122         if (tocopy > HTTP_BUF_SIZE)
123             tocopy = HTTP_BUF_SIZE;
124         *p = http_buf_create();
125         memcpy((*p)->buf, b, tocopy);
126         (*p)->len = tocopy;
127         len -= tocopy;
128         b += tocopy;
129         p = &(*p)->next;
130     }
131     return res;
132 }
133
134 // Add a (chain of) buffers to the end of an existing queue.
135 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
136 {
137     while (*queue)
138         queue = &(*queue)->next;
139     *queue = b;
140 }
141
142 static struct http_buf *http_buf_bywrbuf(WRBUF wrbuf)
143 {
144     // Heavens to Betsy (buf)!
145     return http_buf_bybuf(wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
146 }
147
148 // Non-destructively collapse chain of buffers into a string (max *len)
149 // Return
150 static int http_buf_peek(struct http_buf *b, char *buf, int len)
151 {
152     int rd = 0;
153     while (b && rd < len)
154     {
155         int toread = len - rd;
156         if (toread > b->len)
157             toread = b->len;
158         memcpy(buf + rd, b->buf + b->offset, toread);
159         rd += toread;
160         b = b->next;
161     }
162     buf[rd] = '\0';
163     return rd;
164 }
165
166 // Ddestructively munch up to len  from head of queue.
167 static int http_buf_read(struct http_buf **b, char *buf, int len)
168 {
169     int rd = 0;
170     while ((*b) && rd < len)
171     {
172         int toread = len - rd;
173         if (toread > (*b)->len)
174             toread = (*b)->len;
175         memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
176         rd += toread;
177         if (toread < (*b)->len)
178         {
179             (*b)->len -= toread;
180             (*b)->offset += toread;
181             break;
182         }
183         else
184         {
185             struct http_buf *n = (*b)->next;
186             http_buf_destroy(*b);
187             *b = n;
188         }
189     }
190     buf[rd] = '\0';
191     return rd;
192 }
193
194 // Buffers may overlap.
195 static void urldecode(char *i, char *o)
196 {
197     while (*i)
198     {
199         if (*i == '+')
200         {
201             *(o++) = ' ';
202             i++;
203         }
204         else if (*i == '%')
205         {
206             i++;
207             sscanf(i, "%2hhx", o);
208             i += 2;
209             o++;
210         }
211         else
212             *(o++) = *(i++);
213     }
214     *o = '\0';
215 }
216
217 // Warning: Buffers may not overlap
218 void urlencode(const char *i, char *o)
219 {
220     while (*i)
221     {
222         if (strchr(" /:", *i))
223         {
224             sprintf(o, "%%%.2X", (int) *i);
225             o += 3;
226         }
227         else
228             *(o++) = *i;
229         i++;
230     }
231     *o = '\0';
232 }
233
234 void http_addheader(struct http_response *r, const char *name, const char *value)
235 {
236     struct http_channel *c = r->channel;
237     struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
238     h->name = nmem_strdup(c->nmem, name);
239     h->value = nmem_strdup(c->nmem, value);
240     h->next = r->headers;
241     r->headers = h;
242 }
243
244 char *http_argbyname(struct http_request *r, char *name)
245 {
246     struct http_argument *p;
247     if (!name)
248         return 0;
249     for (p = r->arguments; p; p = p->next)
250         if (!strcmp(p->name, name))
251             return p->value;
252     return 0;
253 }
254
255 char *http_headerbyname(struct http_header *h, char *name)
256 {
257     for (; h; h = h->next)
258         if (!strcmp(h->name, name))
259             return h->value;
260     return 0;
261 }
262
263 struct http_response *http_create_response(struct http_channel *c)
264 {
265     struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
266     strcpy(r->code, "200");
267     r->msg = "OK";
268     r->channel = c;
269     r->headers = 0;
270     r->payload = 0;
271     return r;
272 }
273
274 // Check if buf contains a package (minus payload)
275 static int package_check(const char *buf)
276 {
277     int len = 0;
278     while (*buf) // Check if we have a sequence of lines terminated by an empty line
279     {
280         char *b = strstr(buf, "\r\n");
281
282         if (!b)
283             return 0;
284
285         len += (b - buf) + 2;
286         if (b == buf)
287             return len;
288         buf = b + 2;
289     }
290     return 0;
291 }
292
293 // Check if we have a request. Return 0 or length
294 // (including trailing CRNL) FIXME: Does not deal gracefully with requests
295 // carrying payload but this is kind of OK since we will reject anything
296 // other than an empty GET
297 static int request_check(struct http_buf *queue)
298 {
299     char tmp[4096];
300
301     http_buf_peek(queue, tmp, 4096);
302     return package_check(tmp);
303 }
304
305 struct http_response *http_parse_response_buf(struct http_channel *c, const char *buf, int len)
306 {
307     char tmp[4096];
308     struct http_response *r = http_create_response(c);
309     char *p, *p2;
310     struct http_header **hp = &r->headers;
311
312     if (len >= 4096)
313         return 0;
314     memcpy(tmp, buf, len);
315     for (p = tmp; *p && *p != ' '; p++) // Skip HTTP version
316         ;
317     p++;
318     // Response code
319     for (p2 = p; *p2 && *p2 != ' ' && p2 - p < 3; p2++)
320         r->code[p2 - p] = *p2;
321     if (!(p = strstr(tmp, "\r\n")))
322         return 0;
323     p += 2;
324     while (*p)
325     {
326         if (!(p2 = strstr(p, "\r\n")))
327             return 0;
328         if (p == p2) // End of headers
329             break;
330         else
331         {
332             struct http_header *h = *hp = nmem_malloc(c->nmem, sizeof(*h));
333             char *value = strchr(p, ':');
334             if (!value)
335                 return 0;
336             *(value++) = '\0';
337             h->name = nmem_strdup(c->nmem, p);
338             while (isspace(*value))
339                 value++;
340             if (value >= p2)  // Empty header;
341             {
342                 h->value = "";
343                 p = p2 + 2;
344                 continue;
345             }
346             *p2 = '\0';
347             h->value = nmem_strdup(c->nmem, value);
348             h->next = 0;
349             hp = &h->next;
350             p = p2 + 2;
351         }
352     }
353     return r;
354 }
355
356 struct http_request *http_parse_request(struct http_channel *c, struct http_buf **queue,
357         int len)
358 {
359     struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
360     char *p, *p2;
361     char tmp[4096];
362     char *buf = tmp;
363
364     if (len > 4096)
365         return 0;
366     if (http_buf_read(queue, buf, len) < len)
367         return 0;
368
369     r->search = "";
370     r->channel = c;
371     r->arguments = 0;
372     r->headers = 0;
373     // Parse first line
374     for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
375         *(p2++) = *p;
376     if (*p != ' ')
377     {
378         yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
379         return 0;
380     }
381     *p2 = '\0';
382
383     if (!(buf = strchr(buf, ' ')))
384     {
385         yaz_log(YLOG_WARN, "Syntax error in request (1)");
386         return 0;
387     }
388     buf++;
389     if (!(p = strchr(buf, ' ')))
390     {
391         yaz_log(YLOG_WARN, "Syntax error in request (2)");
392         return 0;
393     }
394     *(p++) = '\0';
395     if ((p2 = strchr(buf, '?'))) // Do we have arguments?
396         *(p2++) = '\0';
397     r->path = nmem_strdup(c->nmem, buf);
398     if (p2)
399     {
400         r->search = nmem_strdup(c->nmem, p2);
401         // Parse Arguments
402         while (*p2)
403         {
404             struct http_argument *a;
405             char *equal = strchr(p2, '=');
406             char *eoa = strchr(p2, '&');
407             if (!equal)
408             {
409                 yaz_log(YLOG_WARN, "Expected '=' in argument");
410                 return 0;
411             }
412             if (!eoa)
413                 eoa = equal + strlen(equal); // last argument
414             else
415                 *(eoa++) = '\0';
416             a = nmem_malloc(c->nmem, sizeof(struct http_argument));
417             *(equal++) = '\0';
418             a->name = nmem_strdup(c->nmem, p2);
419             urldecode(equal, equal);
420             a->value = nmem_strdup(c->nmem, equal);
421             a->next = r->arguments;
422             r->arguments = a;
423             p2 = eoa;
424         }
425     }
426     buf = p;
427
428     if (strncmp(buf, "HTTP/", 5))
429         strcpy(r->http_version, "1.0");
430     else
431     {
432         buf += 5;
433         if (!(p = strstr(buf, "\r\n")))
434             return 0;
435         *(p++) = '\0';
436         p++;
437         strcpy(r->http_version, buf);
438         buf = p;
439     }
440     strcpy(c->version, r->http_version);
441
442     r->headers = 0;
443     while (*buf)
444     {
445         if (!(p = strstr(buf, "\r\n")))
446             return 0;
447         if (p == buf)
448             break;
449         else
450         {
451             struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
452             if (!(p2 = strchr(buf, ':')))
453                 return 0;
454             *(p2++) = '\0';
455             h->name = nmem_strdup(c->nmem, buf);
456             while (isspace(*p2))
457                 p2++;
458             if (p2 >= p) // Empty header?
459             {
460                 buf = p + 2;
461                 continue;
462             }
463             *p = '\0';
464             h->value = nmem_strdup(c->nmem, p2);
465             h->next = r->headers;
466             r->headers = h;
467             buf = p + 2;
468         }
469     }
470
471     return r;
472 }
473
474 static struct http_buf *http_serialize_response(struct http_channel *c,
475         struct http_response *r)
476 {
477     struct http_header *h;
478
479     wrbuf_rewind(c->wrbuf);
480     wrbuf_printf(c->wrbuf, "HTTP/1.1 %s %s\r\n", r->code, r->msg);
481     for (h = r->headers; h; h = h->next)
482         wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
483     if (r->payload)
484     {
485         wrbuf_printf(c->wrbuf, "Content-length: %d\r\n", r->payload ?
486                 (int) strlen(r->payload) : 0);
487         wrbuf_printf(c->wrbuf, "Content-type: text/xml\r\n");
488     }
489     wrbuf_puts(c->wrbuf, "\r\n");
490
491     if (r->payload)
492         wrbuf_puts(c->wrbuf, r->payload);
493
494     return http_buf_bywrbuf(c->wrbuf);
495 }
496
497 // Serialize a HTTP request
498 static struct http_buf *http_serialize_request(struct http_request *r)
499 {
500     struct http_channel *c = r->channel;
501     struct http_header *h;
502     struct http_argument *a;
503
504     wrbuf_rewind(c->wrbuf);
505     wrbuf_printf(c->wrbuf, "%s %s", r->method, r->path);
506
507     if (r->arguments)
508     {
509         wrbuf_putc(c->wrbuf, '?');
510         for (a = r->arguments; a; a = a->next) {
511             if (a != r->arguments)
512                 wrbuf_putc(c->wrbuf, '&');
513             wrbuf_printf(c->wrbuf, "%s=%s", a->name, a->value);
514         }
515     }
516
517     wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
518
519     for (h = r->headers; h; h = h->next)
520         wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
521
522     wrbuf_puts(c->wrbuf, "\r\n");
523     
524     return http_buf_bywrbuf(c->wrbuf);
525 }
526
527
528 static int http_weshouldproxy(struct http_request *rq)
529 {
530     if (proxy_addr && !strstr(rq->path, "search.pz2"))
531         return 1;
532     return 0;
533 }
534
535
536 struct http_header * http_header_append(struct http_channel *ch, 
537                                         struct http_header * hp, 
538                                         const char *name, 
539                                         const char *value)
540 {
541     struct http_header *hpnew = 0; 
542
543     if (!hp | !ch)
544         return 0;
545
546     while (hp && hp->next)
547         hp = hp->next;
548
549     if(name && strlen(name)&& value && strlen(value)){
550         hpnew = nmem_malloc(ch->nmem, sizeof *hpnew);
551         hpnew->name = nmem_strdup(ch->nmem, name);
552         hpnew->value = nmem_strdup(ch->nmem, value);
553         
554         hpnew->next = 0;
555         hp->next = hpnew;
556         hp = hp->next;
557         
558         return hpnew;
559     }
560
561     return hp;
562 }
563
564     
565
566 static int http_proxy(struct http_request *rq)
567 {
568     struct http_channel *c = rq->channel;
569     struct http_proxy *p = c->proxy;
570     struct http_header *hp;
571     struct http_buf *requestbuf;
572     char server_via[128] = "";
573     char server_port[16] = "";
574     struct conf_server *ser = global_parameters.server;
575
576     if (!p) // This is a new connection. Create a proxy channel
577     {
578         int sock;
579         struct protoent *pe;
580         int one = 1;
581         int flags;
582
583         if (!(pe = getprotobyname("tcp"))) {
584             abort();
585         }
586         if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
587         {
588             yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
589             return -1;
590         }
591         if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
592                         &one, sizeof(one)) < 0)
593             abort();
594         if ((flags = fcntl(sock, F_GETFL, 0)) < 0) 
595             yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
596         if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
597             yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
598         if (connect(sock, (struct sockaddr *) proxy_addr, 
599                     sizeof(*proxy_addr)) < 0)
600             if (errno != EINPROGRESS)
601             {
602                 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
603                 return -1;
604             }
605
606         p = xmalloc(sizeof(struct http_proxy));
607         p->oqueue = 0;
608         p->channel = c;
609         p->first_response = 1;
610         c->proxy = p;
611         // We will add EVENT_OUTPUT below
612         p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
613         iochan_setdata(p->iochan, p);
614         p->iochan->next = channel_list;
615         channel_list = p->iochan;
616     }
617
618     // Do _not_ modify Host: header, just checking it's existence
619     for (hp = rq->headers; hp; hp = hp->next)
620         if (!strcmp(hp->name, "Host"))
621             break;
622     if (!hp)
623     {
624         yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
625         return -1;
626     }
627     
628     // Add new header about paraz2 version, host, remote client address, etc.
629     {
630         hp = rq->headers;
631         hp = http_header_append(c, hp, 
632                                 "X-Pazpar2-Version", PACKAGE_VERSION);
633         hp = http_header_append(c, hp, 
634                                 "X-Pazpar2-Server-Host", ser->host);
635         sprintf(server_port, "%d",  ser->port);
636         hp = http_header_append(c, hp, 
637                                 "X-Pazpar2-Server-Port", server_port);
638         sprintf(server_via,  "1.1 %s:%s (%s/%s)",  
639                 ser->host, server_port, PACKAGE_NAME, PACKAGE_VERSION);
640         hp = http_header_append(c, hp, "Via" , server_via);
641         hp = http_header_append(c, hp, "X-Forwarded-For", c->addr);
642     }
643     
644     requestbuf = http_serialize_request(rq);
645     http_buf_enqueue(&p->oqueue, requestbuf);
646     iochan_setflag(p->iochan, EVENT_OUTPUT);
647     return 0;
648 }
649
650 void http_send_response(struct http_channel *ch)
651 {
652     struct http_response *rs = ch->response;
653     struct http_buf *hb;
654
655     assert(rs);
656     hb = http_serialize_response(ch, rs);
657     if (!hb)
658     {
659         yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
660         http_destroy(ch->iochan);
661     }
662     else
663     {
664         http_buf_enqueue(&ch->oqueue, hb);
665         iochan_setflag(ch->iochan, EVENT_OUTPUT);
666         ch->state = Http_Idle;
667     }
668 }
669
670 static void http_io(IOCHAN i, int event)
671 {
672     struct http_channel *hc = iochan_getdata(i);
673
674     switch (event)
675     {
676         int res, reqlen;
677         struct http_buf *htbuf;
678
679         case EVENT_INPUT:
680             htbuf = http_buf_create();
681             res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
682             if (res == -1 && errno == EAGAIN)
683             {
684                 http_buf_destroy(htbuf);
685                 return;
686             }
687             if (res <= 0)
688             {
689                 http_buf_destroy(htbuf);
690                 http_destroy(i);
691                 return;
692             }
693             if (res > 0)
694             {
695                 htbuf->buf[res] = '\0';
696                 htbuf->len = res;
697                 http_buf_enqueue(&hc->iqueue, htbuf);
698             }
699
700             if (hc->state == Http_Busy)
701                 return;
702             if ((reqlen = request_check(hc->iqueue)) <= 2)
703                 return;
704
705             nmem_reset(hc->nmem);
706             if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
707             {
708                 yaz_log(YLOG_WARN, "Failed to parse request");
709                 http_destroy(i);
710                 return;
711             }
712             hc->response = 0;
713             yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
714                     hc->request->path,
715                     *hc->request->search ? "?" : "",
716                     hc->request->search);
717             if (http_weshouldproxy(hc->request))
718                 http_proxy(hc->request);
719             else
720             {
721                 // Execute our business logic!
722                 hc->state = Http_Busy;
723                 http_command(hc);
724             }
725             if (hc->iqueue)
726             {
727                 yaz_log(YLOG_DEBUG, "We think we have more input to read. Forcing event");
728                 iochan_setevent(i, EVENT_INPUT);
729             }
730
731             break;
732
733         case EVENT_OUTPUT:
734             if (hc->oqueue)
735             {
736                 struct http_buf *wb = hc->oqueue;
737                 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
738                 if (res <= 0)
739                 {
740                     yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
741                     http_destroy(i);
742                     return;
743                 }
744                 if (res == wb->len)
745                 {
746                     hc->oqueue = hc->oqueue->next;
747                     http_buf_destroy(wb);
748                 }
749                 else
750                 {
751                     wb->len -= res;
752                     wb->offset += res;
753                 }
754                 if (!hc->oqueue) {
755                     if (!strcmp(hc->version, "1.0"))
756                     {
757                         http_destroy(i);
758                         return;
759                     }
760                     else
761                     {
762                         iochan_clearflag(i, EVENT_OUTPUT);
763                         if (hc->iqueue)
764                             iochan_setevent(hc->iochan, EVENT_INPUT);
765                     }
766                 }
767             }
768
769             if (!hc->oqueue && hc->proxy && !hc->proxy->iochan) 
770                 http_destroy(i); // Server closed; we're done
771             break;
772         default:
773             yaz_log(YLOG_WARN, "Unexpected event on connection");
774             http_destroy(i);
775     }
776 }
777
778 #ifdef GAGA
779 // If this hostname contains our proxy host as a prefix, replace with myurl
780 static char *sub_hostname(struct http_channel *c, char *buf)
781 {
782     char tmp[1024];
783     if (strlen(buf) > 1023)
784         return buf;
785     if (strncmp(buf, "http://", 7))
786         return buf;
787     if (!strncmp(buf + 7, proxy_url, strlen(proxy_url)))
788     {
789         strcpy(tmp, myurl);
790         strcat(tmp, buf + strlen(proxy_url) + 7);
791         return nmem_strdup(c->nmem, tmp);
792     }
793     return buf;
794 }
795 #endif
796
797 // Handles I/O on a client connection to a backend web server (proxy mode)
798 static void proxy_io(IOCHAN pi, int event)
799 {
800     struct http_proxy *pc = iochan_getdata(pi);
801     struct http_channel *hc = pc->channel;
802
803     switch (event)
804     {
805         int res;
806         struct http_buf *htbuf;
807
808         case EVENT_INPUT:
809             htbuf = http_buf_create();
810             res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
811             if (res == 0 || (res < 0 && errno != EINPROGRESS))
812             {
813                 if (hc->oqueue)
814                 {
815                     yaz_log(YLOG_WARN, "Proxy read came up short");
816                     // Close channel and alert client HTTP channel that we're gone
817                     http_buf_destroy(htbuf);
818                     close(iochan_getfd(pi));
819                     iochan_destroy(pi);
820                     pc->iochan = 0;
821                 }
822                 else
823                 {
824                     http_destroy(hc->iochan);
825                     return;
826                 }
827             }
828             else
829             {
830                 htbuf->buf[res] = '\0';
831                 htbuf->offset = 0;
832                 htbuf->len = res;
833 #ifdef GAGA
834                 if (pc->first_response) // Check if this is a redirect
835                 {
836                     int len;
837                     if ((len = package_check(htbuf->buf)))
838                     {
839                         struct http_response *res = http_parse_response_buf(hc, htbuf->buf, len);
840                         if (res)
841                         {
842                             struct http_header *h;
843                             for (h = res->headers; h; h = h->next)
844                                 if (!strcmp(h->name, "Location"))
845                                 {
846                                     // We found a location header. Rewrite it.
847                                     struct http_buf *buf;
848                                     h->value = sub_hostname(hc, h->value);
849                                     buf = http_serialize_response(hc, res);
850                                     yaz_log(YLOG_LOG, "Proxy rewrite");
851                                     http_buf_enqueue(&hc->oqueue, buf);
852                                     htbuf->offset = len;
853                                     break;
854                                 }
855                         }
856                     }
857                     pc->first_response = 0;
858                 }
859 #endif
860                 // Write any remaining payload
861                 if (htbuf->len - htbuf->offset > 0)
862                     http_buf_enqueue(&hc->oqueue, htbuf);
863             }
864             iochan_setflag(hc->iochan, EVENT_OUTPUT);
865             break;
866         case EVENT_OUTPUT:
867             if (!(htbuf = pc->oqueue))
868             {
869                 iochan_clearflag(pi, EVENT_OUTPUT);
870                 return;
871             }
872             res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
873             if (res <= 0)
874             {
875                 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
876                 http_destroy(hc->iochan);
877                 return;
878             }
879             if (res == htbuf->len)
880             {
881                 struct http_buf *np = htbuf->next;
882                 http_buf_destroy(htbuf);
883                 pc->oqueue = np;
884             }
885             else
886             {
887                 htbuf->len -= res;
888                 htbuf->offset += res;
889             }
890
891             if (!pc->oqueue) {
892                 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
893             }
894             break;
895         default:
896             yaz_log(YLOG_WARN, "Unexpected event on connection");
897             http_destroy(hc->iochan);
898     }
899 }
900
901 // Cleanup channel
902 static void http_destroy(IOCHAN i)
903 {
904     struct http_channel *s = iochan_getdata(i);
905
906     if (s->proxy)
907     {
908         if (s->proxy->iochan)
909         {
910             close(iochan_getfd(s->proxy->iochan));
911             iochan_destroy(s->proxy->iochan);
912         }
913         http_buf_destroy_queue(s->proxy->oqueue);
914         xfree(s->proxy);
915     }
916     s->next = http_channel_freelist;
917     http_channel_freelist = s;
918     close(iochan_getfd(i));
919     iochan_destroy(i);
920 }
921
922 static struct http_channel *http_create(const char *addr)
923 {
924     struct http_channel *r = http_channel_freelist;
925
926     if (r)
927     {
928         http_channel_freelist = r->next;
929         nmem_reset(r->nmem);
930         wrbuf_rewind(r->wrbuf);
931     }
932     else
933     {
934         r = xmalloc(sizeof(struct http_channel));
935         r->nmem = nmem_create();
936         r->wrbuf = wrbuf_alloc();
937     }
938     r->proxy = 0;
939     r->iochan = 0;
940     r->iqueue = r->oqueue = 0;
941     r->state = Http_Idle;
942     r->request = 0;
943     r->response = 0;
944     if (!addr)
945     {
946         yaz_log(YLOG_WARN, "Invalid HTTP forward address");
947         exit(1);
948     }
949     r->addr = nmem_strdup(r->nmem, addr);
950     return r;
951 }
952
953
954 /* Accept a new command connection */
955 static void http_accept(IOCHAN i, int event)
956 {
957     struct sockaddr_in addr;
958     int fd = iochan_getfd(i);
959     socklen_t len;
960     int s;
961     IOCHAN c;
962     int flags;
963     struct http_channel *ch;
964
965     len = sizeof addr;
966     if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
967     {
968         yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
969         return;
970     }
971     if ((flags = fcntl(s, F_GETFL, 0)) < 0) 
972         yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
973     if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
974         yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
975
976     yaz_log(YLOG_DEBUG, "New command connection");
977     c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
978     
979     ch = http_create(inet_ntoa(addr.sin_addr));
980     ch->iochan = c;
981     iochan_setdata(c, ch);
982
983     c->next = channel_list;
984     channel_list = c;
985 }
986
987 /* Create a http-channel listener, syntax [host:]port */
988 void http_init(const char *addr)
989 {
990     IOCHAN c;
991     int l;
992     struct protoent *p;
993     struct sockaddr_in myaddr;
994     int one = 1;
995     const char *pp;
996     int port;
997
998     yaz_log(YLOG_LOG, "HTTP listener %s", addr);
999
1000     memset(&myaddr, 0, sizeof myaddr);
1001     myaddr.sin_family = AF_INET;
1002     pp = strchr(addr, ':');
1003     if (pp)
1004     {
1005         int len = pp - addr;
1006         char hostname[128];
1007         struct hostent *he;
1008
1009         strncpy(hostname, addr, len);
1010         hostname[len] = '\0';
1011         if (!(he = gethostbyname(hostname)))
1012         {
1013             yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
1014             exit(1);
1015         }
1016         
1017         memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1018         port = atoi(pp + 1);
1019
1020         yaz_log(YLOG_LOG, "HTTP address  %s:%d", 
1021                 "" == he->h_addr_list[0] ? he->h_addr_list[0] : "127.0.0.1" , 
1022                     port);
1023
1024     }
1025     else
1026     {
1027         port = atoi(addr);
1028         myaddr.sin_addr.s_addr = INADDR_ANY;
1029     }
1030
1031     myaddr.sin_port = htons(port);
1032
1033     if (!(p = getprotobyname("tcp"))) {
1034         abort();
1035     }
1036     if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
1037         yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
1038     if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
1039                     &one, sizeof(one)) < 0)
1040         abort();
1041
1042     if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0) 
1043         yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
1044     if (listen(l, SOMAXCONN) < 0) 
1045         yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
1046
1047     c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
1048     c->next = channel_list;
1049     channel_list = c;
1050 }
1051
1052 void http_set_proxyaddr(char *host, char *base_url)
1053 {
1054     char *p;
1055     int port;
1056     struct hostent *he;
1057
1058     strcpy(myurl, base_url);
1059     strcpy(proxy_url, host);
1060     p = strchr(host, ':');
1061     yaz_log(YLOG_DEBUG, "Proxying for %s", host);
1062     yaz_log(YLOG_LOG, "HTTP backend  %s", proxy_url);
1063     if (p) {
1064         port = atoi(p + 1);
1065         *p = '\0';
1066     }
1067     else
1068         port = 80;
1069     if (!(he = gethostbyname(host))) 
1070     {
1071         fprintf(stderr, "Failed to lookup '%s'\n", host);
1072         exit(1);
1073     }
1074     proxy_addr = xmalloc(sizeof(struct sockaddr_in));
1075     proxy_addr->sin_family = he->h_addrtype;
1076     memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1077     proxy_addr->sin_port = htons(port);
1078 }
1079
1080 /*
1081  * Local variables:
1082  * c-basic-offset: 4
1083  * indent-tabs-mode: nil
1084  * End:
1085  * vim: shiftwidth=4 tabstop=8 expandtab
1086  */