Use queue for raw show; to solve Bug #1644.
[pazpar2-moved-to-github.git] / src / http.c
1 /* $Id: http.c,v 1.41 2007-10-02 12:11:14 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     return r;
297 }
298
299
300 static const char *next_crlf(const char *cp, size_t *skipped)
301 {
302     const char *next_cp = strchr(cp, '\n');
303     if (next_cp)
304     {
305         if (next_cp > cp && next_cp[-1] == '\r')
306             *skipped = next_cp - cp - 1;
307         else
308             *skipped = next_cp - cp;
309         next_cp++;
310     }
311     return next_cp;
312 }
313
314 // Check if buf contains a package (minus payload)
315 static int package_check(const char *buf, int sz)
316 {
317     int content_len = 0;
318     int len = 0;
319
320     while (*buf)
321     {
322         size_t skipped = 0;
323         const char *b = next_crlf(buf, &skipped);
324
325         if (!b)
326         {
327             // we did not find CRLF.. See if buffer is too large..
328             if (sz >= MAX_HTTP_HEADER-1)
329                 return MAX_HTTP_HEADER-1; // yes. Return that (will fail later)
330             break;
331         }
332         len += (b - buf);
333         if (skipped == 0)
334         {
335             // CRLF CRLF , i.e. end of header
336             if (len + content_len <= sz)
337                 return len + content_len;
338             break;
339         }
340         buf = b;
341         // following first skip of \r\n so that we don't consider Method
342         if (!strncasecmp(buf, "Content-Length:", 15))
343         {
344             const char *cp = buf+15;
345             while (*cp == ' ')
346                 cp++;
347             content_len = 0;
348             while (*cp && isdigit(*cp))
349                 content_len = content_len*10 + (*cp++ - '0');
350             if (content_len < 0) /* prevent negative offsets */
351                 content_len = 0;
352         }
353     }
354     return 0;     // incomplete request
355 }
356
357 // Check if we have a request. Return 0 or length
358 static int request_check(struct http_buf *queue)
359 {
360     char tmp[MAX_HTTP_HEADER];
361
362     // only peek at the header..
363     http_buf_peek(queue, tmp, MAX_HTTP_HEADER-1);
364     // still we only return non-zero if the complete request is received..
365     return package_check(tmp, http_buf_size(queue));
366 }
367
368 struct http_response *http_parse_response_buf(struct http_channel *c, const char *buf, int len)
369 {
370     char tmp[MAX_HTTP_HEADER];
371     struct http_response *r = http_create_response(c);
372     char *p, *p2;
373     struct http_header **hp = &r->headers;
374
375     if (len >= MAX_HTTP_HEADER)
376         return 0;
377     memcpy(tmp, buf, len);
378     for (p = tmp; *p && *p != ' '; p++) // Skip HTTP version
379         ;
380     p++;
381     // Response code
382     for (p2 = p; *p2 && *p2 != ' ' && p2 - p < 3; p2++)
383         r->code[p2 - p] = *p2;
384     if (!(p = strstr(tmp, "\r\n")))
385         return 0;
386     p += 2;
387     while (*p)
388     {
389         if (!(p2 = strstr(p, "\r\n")))
390             return 0;
391         if (p == p2) // End of headers
392             break;
393         else
394         {
395             struct http_header *h = *hp = nmem_malloc(c->nmem, sizeof(*h));
396             char *value = strchr(p, ':');
397             if (!value)
398                 return 0;
399             *(value++) = '\0';
400             h->name = nmem_strdup(c->nmem, p);
401             while (isspace(*value))
402                 value++;
403             if (value >= p2)  // Empty header;
404             {
405                 h->value = "";
406                 p = p2 + 2;
407                 continue;
408             }
409             *p2 = '\0';
410             h->value = nmem_strdup(c->nmem, value);
411             h->next = 0;
412             hp = &h->next;
413             p = p2 + 2;
414         }
415     }
416     return r;
417 }
418
419 static int http_parse_arguments(struct http_request *r, NMEM nmem,
420                                 const char *args)
421 {
422     const char *p2 = args;
423
424     while (*p2)
425     {
426         struct http_argument *a;
427         const char *equal = strchr(p2, '=');
428         const char *eoa = strchr(p2, '&');
429         if (!equal)
430         {
431             yaz_log(YLOG_WARN, "Expected '=' in argument");
432             return -1;
433         }
434         if (!eoa)
435             eoa = equal + strlen(equal); // last argument
436         else if (equal > eoa)
437         {
438             yaz_log(YLOG_WARN, "Missing '&' in argument");
439             return -1;
440         }
441         a = nmem_malloc(nmem, sizeof(struct http_argument));
442         a->name = nmem_strdupn(nmem, p2, equal - p2);
443         a->value = nmem_strdupn(nmem, equal+1, eoa - equal - 1);
444         urldecode(a->name, a->name);
445         urldecode(a->value, a->value);
446         a->next = r->arguments;
447         r->arguments = a;
448         p2 = eoa;
449         while (*p2 == '&')
450             p2++;
451     }
452     return 0;
453 }
454
455 struct http_request *http_parse_request(struct http_channel *c,
456                                         struct http_buf **queue,
457                                         int len)
458 {
459     struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
460     char *p, *p2;
461     char *start = nmem_malloc(c->nmem, len+1);
462     char *buf = start;
463
464     if (http_buf_read(queue, buf, len) < len)
465     {
466         yaz_log(YLOG_WARN, "http_buf_read < len (%d)", len);
467         return 0;
468     }
469     r->search = "";
470     r->channel = c;
471     r->arguments = 0;
472     r->headers = 0;
473     r->content_buf = 0;
474     r->content_len = 0;
475     // Parse first line
476     for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
477         *(p2++) = *p;
478     if (*p != ' ')
479     {
480         yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
481         return 0;
482     }
483     *p2 = '\0';
484
485     if (!(buf = strchr(buf, ' ')))
486     {
487         yaz_log(YLOG_WARN, "Missing Request-URI in HTTP request");
488         return 0;
489     }
490     buf++;
491     if (!(p = strchr(buf, ' ')))
492     {
493         yaz_log(YLOG_WARN, "HTTP Request-URI not terminated (too long?)");
494         return 0;
495     }
496     *(p++) = '\0';
497     if ((p2 = strchr(buf, '?'))) // Do we have arguments?
498         *(p2++) = '\0';
499     r->path = nmem_strdup(c->nmem, buf);
500     if (p2)
501     {
502         r->search = nmem_strdup(c->nmem, p2);
503         // Parse Arguments
504         http_parse_arguments(r, c->nmem, p2);
505     }
506     buf = p;
507
508     if (strncmp(buf, "HTTP/", 5))
509         strcpy(r->http_version, "1.0");
510     else
511     {
512         size_t skipped;
513         buf += 5; // strlen("HTTP/")
514
515         p = (char*) next_crlf(buf, &skipped);
516         if (!p || skipped < 3 || skipped > 5)
517             return 0;
518
519         memcpy(r->http_version, buf, skipped);
520         r->http_version[skipped] = '\0';
521         buf = p;
522     }
523     strcpy(c->version, r->http_version);
524
525     r->headers = 0;
526     while (*buf)
527     {
528         size_t skipped;
529
530         p = (char *) next_crlf(buf, &skipped);
531         if (!p)
532         {
533             return 0;
534         }
535         else if (skipped == 0)
536         {
537             buf = p;
538             break;
539         }
540         else
541         {
542             char *cp;
543             char *n_v = nmem_malloc(c->nmem, skipped+1);
544             struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
545
546             memcpy(n_v, buf, skipped);
547             n_v[skipped] = '\0';
548
549             if (!(cp = strchr(n_v, ':')))
550                 return 0;
551             h->name = nmem_strdupn(c->nmem, n_v, cp - n_v);
552             cp++;
553             while (isspace(*cp))
554                 cp++;
555             h->value = nmem_strdup(c->nmem, cp);
556             h->next = r->headers;
557             r->headers = h;
558             buf = p;
559         }
560     }
561
562     // determine if we do keep alive
563     if (!strcmp(c->version, "1.0"))
564     {
565         const char *v = http_lookup_header(r->headers, "Connection");
566         if (v && !strcmp(v, "Keep-Alive"))
567             c->keep_alive = 1;
568         else
569             c->keep_alive = 0;
570     }
571     else
572     {
573         const char *v = http_lookup_header(r->headers, "Connection");
574         if (v && !strcmp(v, "close"))
575             c->keep_alive = 0;
576         else
577             c->keep_alive = 1;
578     }
579     if (buf < start + len)
580     {
581         const char *content_type = http_lookup_header(r->headers,
582                                                       "Content-Type");
583         r->content_len = start + len - buf;
584         r->content_buf = buf;
585
586         if (!strcmp(content_type, "application/x-www-form-urlencoded"))
587         {
588             http_parse_arguments(r, c->nmem, r->content_buf);
589         }
590     }
591     return r;
592 }
593
594 static struct http_buf *http_serialize_response(struct http_channel *c,
595         struct http_response *r)
596 {
597     struct http_header *h;
598
599     wrbuf_rewind(c->wrbuf);
600     wrbuf_printf(c->wrbuf, "HTTP/%s %s %s\r\n", c->version, r->code, r->msg);
601     for (h = r->headers; h; h = h->next)
602         wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
603     if (r->payload)
604     {
605         wrbuf_printf(c->wrbuf, "Content-Length: %d\r\n", r->payload ?
606                 (int) strlen(r->payload) : 0);
607         wrbuf_printf(c->wrbuf, "Content-Type: text/xml\r\n");
608         if (1)
609         {
610             xmlDoc *doc = xmlParseMemory(r->payload, strlen(r->payload));
611             if (doc)
612             {
613                 xmlFreeDoc(doc);
614             }
615             else
616             {
617                 yaz_log(YLOG_WARN, "Sending non-wellformed "
618                         "response (bug #1162");
619                 yaz_log(YLOG_WARN, "payload: %s", r->payload);
620             }
621         }
622     }
623     wrbuf_puts(c->wrbuf, "\r\n");
624
625     if (r->payload)
626         wrbuf_puts(c->wrbuf, r->payload);
627
628     return http_buf_bywrbuf(c->wrbuf);
629 }
630
631 // Serialize a HTTP request
632 static struct http_buf *http_serialize_request(struct http_request *r)
633 {
634     struct http_channel *c = r->channel;
635     struct http_header *h;
636
637     wrbuf_rewind(c->wrbuf);
638     wrbuf_printf(c->wrbuf, "%s %s%s%s", r->method, r->path,
639                  *r->search ? "?" : "", r->search);
640
641     wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
642
643     for (h = r->headers; h; h = h->next)
644         wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
645
646     wrbuf_puts(c->wrbuf, "\r\n");
647
648     if (r->content_buf)
649         wrbuf_write(c->wrbuf, r->content_buf, r->content_len);
650
651 #if 0
652     yaz_log(YLOG_LOG, "WRITING TO PROXY:\n%s\n----",
653             wrbuf_cstr(c->wrbuf));
654 #endif
655     return http_buf_bywrbuf(c->wrbuf);
656 }
657
658
659 static int http_weshouldproxy(struct http_request *rq)
660 {
661     if (proxy_addr && !strstr(rq->path, "search.pz2"))
662         return 1;
663     return 0;
664 }
665
666
667 struct http_header * http_header_append(struct http_channel *ch, 
668                                         struct http_header * hp, 
669                                         const char *name, 
670                                         const char *value)
671 {
672     struct http_header *hpnew = 0; 
673
674     if (!hp | !ch)
675         return 0;
676
677     while (hp && hp->next)
678         hp = hp->next;
679
680     if(name && strlen(name)&& value && strlen(value)){
681         hpnew = nmem_malloc(ch->nmem, sizeof *hpnew);
682         hpnew->name = nmem_strdup(ch->nmem, name);
683         hpnew->value = nmem_strdup(ch->nmem, value);
684         
685         hpnew->next = 0;
686         hp->next = hpnew;
687         hp = hp->next;
688         
689         return hpnew;
690     }
691
692     return hp;
693 }
694
695     
696
697 static int http_proxy(struct http_request *rq)
698 {
699     struct http_channel *c = rq->channel;
700     struct http_proxy *p = c->proxy;
701     struct http_header *hp;
702     struct http_buf *requestbuf;
703     char server_via[128] = "";
704     char server_port[16] = "";
705     struct conf_server *ser = global_parameters.server;
706
707     if (!p) // This is a new connection. Create a proxy channel
708     {
709         int sock;
710         struct protoent *pe;
711         int one = 1;
712         int flags;
713
714         if (!(pe = getprotobyname("tcp"))) {
715             abort();
716         }
717         if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
718         {
719             yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
720             return -1;
721         }
722         if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
723                         &one, sizeof(one)) < 0)
724             abort();
725         if ((flags = fcntl(sock, F_GETFL, 0)) < 0) 
726             yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
727         if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
728             yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
729         if (connect(sock, (struct sockaddr *) proxy_addr, 
730                     sizeof(*proxy_addr)) < 0)
731             if (errno != EINPROGRESS)
732             {
733                 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
734                 return -1;
735             }
736
737         p = xmalloc(sizeof(struct http_proxy));
738         p->oqueue = 0;
739         p->channel = c;
740         p->first_response = 1;
741         c->proxy = p;
742         // We will add EVENT_OUTPUT below
743         p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
744         iochan_setdata(p->iochan, p);
745         pazpar2_add_channel(p->iochan);
746     }
747
748     // Do _not_ modify Host: header, just checking it's existence
749
750     if (!http_lookup_header(rq->headers, "Host"))
751     {
752         yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
753         return -1;
754     }
755     
756     // Add new header about paraz2 version, host, remote client address, etc.
757     {
758         hp = rq->headers;
759         hp = http_header_append(c, hp, 
760                                 "X-Pazpar2-Version", PACKAGE_VERSION);
761         hp = http_header_append(c, hp, 
762                                 "X-Pazpar2-Server-Host", ser->host);
763         sprintf(server_port, "%d",  ser->port);
764         hp = http_header_append(c, hp, 
765                                 "X-Pazpar2-Server-Port", server_port);
766         sprintf(server_via,  "1.1 %s:%s (%s/%s)",  
767                 ser->host, server_port, PACKAGE_NAME, PACKAGE_VERSION);
768         hp = http_header_append(c, hp, "Via" , server_via);
769         hp = http_header_append(c, hp, "X-Forwarded-For", c->addr);
770     }
771     
772     requestbuf = http_serialize_request(rq);
773
774     http_buf_enqueue(&p->oqueue, requestbuf);
775     iochan_setflag(p->iochan, EVENT_OUTPUT);
776     return 0;
777 }
778
779 void http_send_response(struct http_channel *ch)
780 {
781     struct http_response *rs = ch->response;
782     struct http_buf *hb;
783
784     assert(rs);
785     hb = http_serialize_response(ch, rs);
786     if (!hb)
787     {
788         yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
789         http_destroy(ch->iochan);
790     }
791     else
792     {
793         http_buf_enqueue(&ch->oqueue, hb);
794         iochan_setflag(ch->iochan, EVENT_OUTPUT);
795         ch->state = Http_Idle;
796     }
797 }
798
799 static void http_error(struct http_channel *hc, int no, const char *msg)
800 {
801     struct http_response *rs = http_create_response(hc);
802
803     hc->response = rs;
804     hc->keep_alive = 0;  // not keeping this HTTP session alive
805
806     sprintf(rs->code, "%d", no);
807
808     rs->msg = nmem_strdup(hc->nmem, msg);
809     rs->payload = nmem_malloc(hc->nmem, 100);
810     yaz_snprintf(rs->payload, 99, "<error>HTTP Error %d: %s</error>\n",
811                  no, msg);
812     http_send_response(hc);
813 }
814
815 static void http_io(IOCHAN i, int event)
816 {
817     struct http_channel *hc = iochan_getdata(i);
818
819     switch (event)
820     {
821         int res, reqlen;
822         struct http_buf *htbuf;
823
824         case EVENT_INPUT:
825             htbuf = http_buf_create();
826             res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
827             if (res == -1 && errno == EAGAIN)
828             {
829                 http_buf_destroy(htbuf);
830                 return;
831             }
832             if (res <= 0)
833             {
834                 http_buf_destroy(htbuf);
835                 http_destroy(i);
836                 return;
837             }
838             htbuf->buf[res] = '\0';
839             htbuf->len = res;
840             http_buf_enqueue(&hc->iqueue, htbuf);
841
842             while (1)
843             {
844                 if (hc->state == Http_Busy)
845                     return;
846                 reqlen = request_check(hc->iqueue);
847                 if (reqlen <= 2)
848                     return;
849                 // we have a complete HTTP request
850                 nmem_reset(hc->nmem);
851                 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
852                 {
853                     yaz_log(YLOG_WARN, "Failed to parse request");
854                     http_error(hc, 400, "Bad Request");
855                     return;
856                 }
857                 hc->response = 0;
858                 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
859                         hc->request->path,
860                         *hc->request->search ? "?" : "",
861                         hc->request->search);
862                 if (http_weshouldproxy(hc->request))
863                     http_proxy(hc->request);
864                 else
865                 {
866                     // Execute our business logic!
867                     hc->state = Http_Busy;
868                     http_command(hc);
869                 }
870             }
871             break;
872         case EVENT_OUTPUT:
873             if (hc->oqueue)
874             {
875                 struct http_buf *wb = hc->oqueue;
876                 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
877                 if (res <= 0)
878                 {
879                     yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
880                     http_destroy(i);
881                     return;
882                 }
883                 if (res == wb->len)
884                 {
885                     hc->oqueue = hc->oqueue->next;
886                     http_buf_destroy(wb);
887                 }
888                 else
889                 {
890                     wb->len -= res;
891                     wb->offset += res;
892                 }
893                 if (!hc->oqueue) {
894                     if (!hc->keep_alive)
895                     {
896                         http_destroy(i);
897                         return;
898                     }
899                     else
900                     {
901                         iochan_clearflag(i, EVENT_OUTPUT);
902                         if (hc->iqueue)
903                             iochan_setevent(hc->iochan, EVENT_INPUT);
904                     }
905                 }
906             }
907
908             if (!hc->oqueue && hc->proxy && !hc->proxy->iochan) 
909                 http_destroy(i); // Server closed; we're done
910             break;
911         default:
912             yaz_log(YLOG_WARN, "Unexpected event on connection");
913             http_destroy(i);
914     }
915 }
916
917 #ifdef GAGA
918 // If this hostname contains our proxy host as a prefix, replace with myurl
919 static char *sub_hostname(struct http_channel *c, char *buf)
920 {
921     char tmp[1024];
922     if (strlen(buf) > 1023)
923         return buf;
924     if (strncmp(buf, "http://", 7))
925         return buf;
926     if (!strncmp(buf + 7, proxy_url, strlen(proxy_url)))
927     {
928         strcpy(tmp, myurl);
929         strcat(tmp, buf + strlen(proxy_url) + 7);
930         return nmem_strdup(c->nmem, tmp);
931     }
932     return buf;
933 }
934 #endif
935
936 // Handles I/O on a client connection to a backend web server (proxy mode)
937 static void proxy_io(IOCHAN pi, int event)
938 {
939     struct http_proxy *pc = iochan_getdata(pi);
940     struct http_channel *hc = pc->channel;
941
942     switch (event)
943     {
944         int res;
945         struct http_buf *htbuf;
946
947         case EVENT_INPUT:
948             htbuf = http_buf_create();
949             res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
950             if (res == 0 || (res < 0 && errno != EINPROGRESS))
951             {
952                 if (hc->oqueue)
953                 {
954                     yaz_log(YLOG_WARN, "Proxy read came up short");
955                     // Close channel and alert client HTTP channel that we're gone
956                     http_buf_destroy(htbuf);
957                     close(iochan_getfd(pi));
958                     iochan_destroy(pi);
959                     pc->iochan = 0;
960                 }
961                 else
962                 {
963                     http_destroy(hc->iochan);
964                     return;
965                 }
966             }
967             else
968             {
969                 htbuf->buf[res] = '\0';
970                 htbuf->offset = 0;
971                 htbuf->len = res;
972 #ifdef GAGA
973                 if (pc->first_response) // Check if this is a redirect
974                 {
975                     int len;
976                     if ((len = package_check(htbuf->buf)))
977                     {
978                         struct http_response *res = http_parse_response_buf(hc, htbuf->buf, len);
979                         if (res)
980                         {
981                             const char *location = http_lookup_header(
982                                 res->header, "Location");
983                             if (location)
984                             {
985                                 // We found a location header. Rewrite it.
986                                 struct http_buf *buf;
987                                 h->value = sub_hostname(hc, location);
988                                 buf = http_serialize_response(hc, res);
989                                 yaz_log(YLOG_LOG, "Proxy rewrite");
990                                 http_buf_enqueue(&hc->oqueue, buf);
991                                 htbuf->offset = len;
992                                 break;
993                             }
994                         }
995                     }
996                     pc->first_response = 0;
997                 }
998 #endif
999                 // Write any remaining payload
1000                 if (htbuf->len - htbuf->offset > 0)
1001                     http_buf_enqueue(&hc->oqueue, htbuf);
1002             }
1003             iochan_setflag(hc->iochan, EVENT_OUTPUT);
1004             break;
1005         case EVENT_OUTPUT:
1006             if (!(htbuf = pc->oqueue))
1007             {
1008                 iochan_clearflag(pi, EVENT_OUTPUT);
1009                 return;
1010             }
1011             res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
1012             if (res <= 0)
1013             {
1014                 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
1015                 http_destroy(hc->iochan);
1016                 return;
1017             }
1018             if (res == htbuf->len)
1019             {
1020                 struct http_buf *np = htbuf->next;
1021                 http_buf_destroy(htbuf);
1022                 pc->oqueue = np;
1023             }
1024             else
1025             {
1026                 htbuf->len -= res;
1027                 htbuf->offset += res;
1028             }
1029
1030             if (!pc->oqueue) {
1031                 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
1032             }
1033             break;
1034         default:
1035             yaz_log(YLOG_WARN, "Unexpected event on connection");
1036             http_destroy(hc->iochan);
1037     }
1038 }
1039
1040 static void http_fire_observers(struct http_channel *c);
1041 static void http_destroy_observers(struct http_channel *c);
1042
1043 // Cleanup channel
1044 static void http_destroy(IOCHAN i)
1045 {
1046     struct http_channel *s = iochan_getdata(i);
1047
1048     if (s->proxy)
1049     {
1050         if (s->proxy->iochan)
1051         {
1052             close(iochan_getfd(s->proxy->iochan));
1053             iochan_destroy(s->proxy->iochan);
1054         }
1055         http_buf_destroy_queue(s->proxy->oqueue);
1056         xfree(s->proxy);
1057     }
1058     http_buf_destroy_queue(s->iqueue);
1059     http_buf_destroy_queue(s->oqueue);
1060     http_fire_observers(s);
1061     http_destroy_observers(s);
1062     s->next = http_channel_freelist;
1063     http_channel_freelist = s;
1064     close(iochan_getfd(i));
1065     iochan_destroy(i);
1066 }
1067
1068 static struct http_channel *http_create(const char *addr)
1069 {
1070     struct http_channel *r = http_channel_freelist;
1071
1072     if (r)
1073     {
1074         http_channel_freelist = r->next;
1075         nmem_reset(r->nmem);
1076         wrbuf_rewind(r->wrbuf);
1077     }
1078     else
1079     {
1080         r = xmalloc(sizeof(struct http_channel));
1081         r->nmem = nmem_create();
1082         r->wrbuf = wrbuf_alloc();
1083     }
1084     r->proxy = 0;
1085     r->iochan = 0;
1086     r->iqueue = r->oqueue = 0;
1087     r->state = Http_Idle;
1088     r->keep_alive = 0;
1089     r->request = 0;
1090     r->response = 0;
1091     if (!addr)
1092     {
1093         yaz_log(YLOG_WARN, "Invalid HTTP forward address");
1094         exit(1);
1095     }
1096     strcpy(r->addr, addr);
1097     r->observers = 0;
1098     return r;
1099 }
1100
1101
1102 /* Accept a new command connection */
1103 static void http_accept(IOCHAN i, int event)
1104 {
1105     struct sockaddr_in addr;
1106     int fd = iochan_getfd(i);
1107     socklen_t len;
1108     int s;
1109     IOCHAN c;
1110     int flags;
1111     struct http_channel *ch;
1112
1113     len = sizeof addr;
1114     if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
1115     {
1116         yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
1117         return;
1118     }
1119     if ((flags = fcntl(s, F_GETFL, 0)) < 0) 
1120         yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
1121     if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
1122         yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
1123
1124     yaz_log(YLOG_DEBUG, "New command connection");
1125     c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
1126     
1127     ch = http_create(inet_ntoa(addr.sin_addr));
1128     ch->iochan = c;
1129     iochan_setdata(c, ch);
1130
1131     pazpar2_add_channel(c);
1132 }
1133
1134 /* Create a http-channel listener, syntax [host:]port */
1135 void http_init(const char *addr)
1136 {
1137     IOCHAN c;
1138     int l;
1139     struct protoent *p;
1140     struct sockaddr_in myaddr;
1141     int one = 1;
1142     const char *pp;
1143     int port;
1144
1145     yaz_log(YLOG_LOG, "HTTP listener %s", addr);
1146
1147     memset(&myaddr, 0, sizeof myaddr);
1148     myaddr.sin_family = AF_INET;
1149     pp = strchr(addr, ':');
1150     if (pp)
1151     {
1152         int len = pp - addr;
1153         char hostname[128];
1154         struct hostent *he;
1155
1156         strncpy(hostname, addr, len);
1157         hostname[len] = '\0';
1158         if (!(he = gethostbyname(hostname))){
1159             yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
1160             exit(1);
1161         }
1162         
1163         memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1164         port = atoi(pp + 1);
1165     }
1166     else
1167     {
1168         port = atoi(addr);
1169         myaddr.sin_addr.s_addr = INADDR_ANY;
1170     }
1171
1172     myaddr.sin_port = htons(port);
1173
1174     if (!(p = getprotobyname("tcp"))) {
1175         abort();
1176     }
1177     if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
1178         yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
1179     if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
1180                     &one, sizeof(one)) < 0)
1181         abort();
1182
1183     if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0) 
1184     {
1185         yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
1186         exit(1);
1187     }
1188     if (listen(l, SOMAXCONN) < 0) 
1189     {
1190         yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
1191         exit(1);
1192     }
1193
1194     c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
1195     pazpar2_add_channel(c);
1196 }
1197
1198 void http_set_proxyaddr(char *host, char *base_url)
1199 {
1200     char *p;
1201     int port;
1202     struct hostent *he;
1203
1204     strcpy(myurl, base_url);
1205     strcpy(proxy_url, host);
1206     p = strchr(host, ':');
1207     yaz_log(YLOG_DEBUG, "Proxying for %s", host);
1208     yaz_log(YLOG_LOG, "HTTP backend  %s", proxy_url);
1209     if (p) {
1210         port = atoi(p + 1);
1211         *p = '\0';
1212     }
1213     else
1214         port = 80;
1215     if (!(he = gethostbyname(host))) 
1216     {
1217         fprintf(stderr, "Failed to lookup '%s'\n", host);
1218         exit(1);
1219     }
1220     proxy_addr = xmalloc(sizeof(struct sockaddr_in));
1221     proxy_addr->sin_family = he->h_addrtype;
1222     memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1223     proxy_addr->sin_port = htons(port);
1224 }
1225
1226 static void http_fire_observers(struct http_channel *c)
1227 {
1228     http_channel_observer_t p = c->observers;
1229     while (p)
1230     {
1231         p->destroy(p->data, c, p->data2);
1232         p = p->next;
1233     }
1234 }
1235
1236 static void http_destroy_observers(struct http_channel *c)
1237 {
1238     while (c->observers)
1239     {
1240         http_channel_observer_t obs = c->observers;
1241         c->observers = obs->next;
1242         xfree(obs);
1243     }
1244 }
1245
1246 http_channel_observer_t http_add_observer(struct http_channel *c, void *data,
1247                                           http_channel_destroy_t des)
1248 {
1249     http_channel_observer_t obs = xmalloc(sizeof(*obs));
1250     obs->chan = c;
1251     obs->data = data;
1252     obs->data2 = 0;
1253     obs->destroy= des;
1254     obs->next = c->observers;
1255     c->observers = obs;
1256     return obs;
1257 }
1258
1259 void http_remove_observer(http_channel_observer_t obs)
1260 {
1261     struct http_channel *c = obs->chan;
1262     http_channel_observer_t found, *p = &c->observers;
1263     while (*p != obs)
1264         p = &(*p)->next;
1265     found = *p;
1266     assert(found);
1267     *p = (*p)->next;
1268     xfree(found);
1269 }
1270
1271 struct http_channel *http_channel_observer_chan(http_channel_observer_t obs)
1272 {
1273     return obs->chan;
1274 }
1275
1276 void http_observer_set_data2(http_channel_observer_t obs, void *data2)
1277 {
1278     obs->data2 = data2;
1279 }
1280
1281
1282 /*
1283  * Local variables:
1284  * c-basic-offset: 4
1285  * indent-tabs-mode: nil
1286  * End:
1287  * vim: shiftwidth=4 tabstop=8 expandtab
1288  */