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