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