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