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