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