1 /* $Id: http.c,v 1.33 2007-06-04 14:44:22 adam Exp $
2 Copyright (c) 2006-2007, Index Data.
4 This file is part of Pazpar2.
6 Pazpar2 is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
11 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with Pazpar2; see the file LICENSE. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
23 #include <sys/socket.h>
24 #include <sys/types.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
44 #include <yaz/yaz-util.h>
45 #include <yaz/comstack.h>
53 #include "http_command.h"
55 static void proxy_io(IOCHAN i, int event);
56 static struct http_channel *http_create(const char *addr);
57 static void http_destroy(IOCHAN i);
59 // If this is set, we proxy normal HTTP requests
60 static struct sockaddr_in *proxy_addr = 0;
61 static char proxy_url[256] = "";
62 static char myurl[256] = "";
63 static struct http_buf *http_buf_freelist = 0;
64 static struct http_channel *http_channel_freelist = 0;
66 static struct http_buf *http_buf_create()
70 if (http_buf_freelist)
72 r = http_buf_freelist;
73 http_buf_freelist = http_buf_freelist->next;
76 r = xmalloc(sizeof(struct http_buf));
83 static void http_buf_destroy(struct http_buf *b)
85 b->next = http_buf_freelist;
86 http_buf_freelist = b;
89 static void http_buf_destroy_queue(struct http_buf *b)
101 // Calculate length of chain
102 static int http_buf_len(struct http_buf *b)
105 for (; b; b = b->next)
111 static struct http_buf *http_buf_bybuf(char *b, int len)
113 struct http_buf *res = 0;
114 struct http_buf **p = &res;
119 if (tocopy > HTTP_BUF_SIZE)
120 tocopy = HTTP_BUF_SIZE;
121 *p = http_buf_create();
122 memcpy((*p)->buf, b, tocopy);
131 // Add a (chain of) buffers to the end of an existing queue.
132 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
135 queue = &(*queue)->next;
139 static struct http_buf *http_buf_bywrbuf(WRBUF wrbuf)
141 // Heavens to Betsy (buf)!
142 return http_buf_bybuf(wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
145 // Non-destructively collapse chain of buffers into a string (max *len)
147 static int http_buf_peek(struct http_buf *b, char *buf, int len)
150 while (b && rd < len)
152 int toread = len - rd;
155 memcpy(buf + rd, b->buf + b->offset, toread);
163 // Ddestructively munch up to len from head of queue.
164 static int http_buf_read(struct http_buf **b, char *buf, int len)
167 while ((*b) && rd < len)
169 int toread = len - rd;
170 if (toread > (*b)->len)
172 memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
174 if (toread < (*b)->len)
177 (*b)->offset += toread;
182 struct http_buf *n = (*b)->next;
183 http_buf_destroy(*b);
191 // Buffers may overlap.
192 static void urldecode(char *i, char *o)
204 sscanf(i, "%2hhx", o);
214 // Warning: Buffers may not overlap
215 void urlencode(const char *i, char *o)
219 if (strchr(" /:", *i))
221 sprintf(o, "%%%.2X", (int) *i);
231 void http_addheader(struct http_response *r, const char *name, const char *value)
233 struct http_channel *c = r->channel;
234 struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
235 h->name = nmem_strdup(c->nmem, name);
236 h->value = nmem_strdup(c->nmem, value);
237 h->next = r->headers;
241 char *http_argbyname(struct http_request *r, char *name)
243 struct http_argument *p;
246 for (p = r->arguments; p; p = p->next)
247 if (!strcmp(p->name, name))
252 char *http_headerbyname(struct http_header *h, char *name)
254 for (; h; h = h->next)
255 if (!strcmp(h->name, name))
260 struct http_response *http_create_response(struct http_channel *c)
262 struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
263 strcpy(r->code, "200");
271 // Check if buf contains a package (minus payload)
272 static int package_check(const char *buf)
275 while (*buf) // Check if we have a sequence of lines terminated by an empty line
277 char *b = strstr(buf, "\r\n");
282 len += (b - buf) + 2;
290 // Check if we have a request. Return 0 or length
291 // (including trailing CRNL) FIXME: Does not deal gracefully with requests
292 // carrying payload but this is kind of OK since we will reject anything
293 // other than an empty GET
294 static int request_check(struct http_buf *queue)
298 http_buf_peek(queue, tmp, 4096);
299 return package_check(tmp);
302 struct http_response *http_parse_response_buf(struct http_channel *c, const char *buf, int len)
305 struct http_response *r = http_create_response(c);
307 struct http_header **hp = &r->headers;
311 memcpy(tmp, buf, len);
312 for (p = tmp; *p && *p != ' '; p++) // Skip HTTP version
316 for (p2 = p; *p2 && *p2 != ' ' && p2 - p < 3; p2++)
317 r->code[p2 - p] = *p2;
318 if (!(p = strstr(tmp, "\r\n")))
323 if (!(p2 = strstr(p, "\r\n")))
325 if (p == p2) // End of headers
329 struct http_header *h = *hp = nmem_malloc(c->nmem, sizeof(*h));
330 char *value = strchr(p, ':');
334 h->name = nmem_strdup(c->nmem, p);
335 while (isspace(*value))
337 if (value >= p2) // Empty header;
344 h->value = nmem_strdup(c->nmem, value);
353 struct http_request *http_parse_request(struct http_channel *c,
354 struct http_buf **queue,
357 struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
364 if (http_buf_read(queue, buf, len) < len)
372 for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
376 yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
381 if (!(buf = strchr(buf, ' ')))
383 yaz_log(YLOG_WARN, "Syntax error in request (1)");
387 if (!(p = strchr(buf, ' ')))
389 yaz_log(YLOG_WARN, "Syntax error in request (2)");
393 if ((p2 = strchr(buf, '?'))) // Do we have arguments?
395 r->path = nmem_strdup(c->nmem, buf);
398 r->search = nmem_strdup(c->nmem, p2);
402 struct http_argument *a;
403 char *equal = strchr(p2, '=');
404 char *eoa = strchr(p2, '&');
407 yaz_log(YLOG_WARN, "Expected '=' in argument");
411 eoa = equal + strlen(equal); // last argument
414 a = nmem_malloc(c->nmem, sizeof(struct http_argument));
416 a->name = nmem_strdup(c->nmem, p2);
417 urldecode(equal, equal);
418 a->value = nmem_strdup(c->nmem, equal);
419 a->next = r->arguments;
426 if (strncmp(buf, "HTTP/", 5))
427 strcpy(r->http_version, "1.0");
431 if (!(p = strstr(buf, "\r\n")))
435 strcpy(r->http_version, buf);
438 strcpy(c->version, r->http_version);
443 if (!(p = strstr(buf, "\r\n")))
449 struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
450 if (!(p2 = strchr(buf, ':')))
453 h->name = nmem_strdup(c->nmem, buf);
456 if (p2 >= p) // Empty header?
462 h->value = nmem_strdup(c->nmem, p2);
463 h->next = r->headers;
472 static struct http_buf *http_serialize_response(struct http_channel *c,
473 struct http_response *r)
475 struct http_header *h;
477 wrbuf_rewind(c->wrbuf);
478 wrbuf_printf(c->wrbuf, "HTTP/1.1 %s %s\r\n", r->code, r->msg);
479 for (h = r->headers; h; h = h->next)
480 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
483 wrbuf_printf(c->wrbuf, "Content-length: %d\r\n", r->payload ?
484 (int) strlen(r->payload) : 0);
485 wrbuf_printf(c->wrbuf, "Content-type: text/xml\r\n");
488 xmlDoc *doc = xmlParseMemory(r->payload, strlen(r->payload));
495 yaz_log(YLOG_WARN, "Sending non-wellformed "
496 "response (bug #1162");
497 yaz_log(YLOG_WARN, "payload: %s", r->payload);
501 wrbuf_puts(c->wrbuf, "\r\n");
504 wrbuf_puts(c->wrbuf, r->payload);
506 return http_buf_bywrbuf(c->wrbuf);
509 // Serialize a HTTP request
510 static struct http_buf *http_serialize_request(struct http_request *r)
512 struct http_channel *c = r->channel;
513 struct http_header *h;
514 struct http_argument *a;
516 wrbuf_rewind(c->wrbuf);
517 wrbuf_printf(c->wrbuf, "%s %s", r->method, r->path);
521 wrbuf_putc(c->wrbuf, '?');
522 for (a = r->arguments; a; a = a->next) {
523 if (a != r->arguments)
524 wrbuf_putc(c->wrbuf, '&');
525 wrbuf_printf(c->wrbuf, "%s=%s", a->name, a->value);
529 wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
531 for (h = r->headers; h; h = h->next)
532 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
534 wrbuf_puts(c->wrbuf, "\r\n");
536 return http_buf_bywrbuf(c->wrbuf);
540 static int http_weshouldproxy(struct http_request *rq)
542 if (proxy_addr && !strstr(rq->path, "search.pz2"))
548 struct http_header * http_header_append(struct http_channel *ch,
549 struct http_header * hp,
553 struct http_header *hpnew = 0;
558 while (hp && hp->next)
561 if(name && strlen(name)&& value && strlen(value)){
562 hpnew = nmem_malloc(ch->nmem, sizeof *hpnew);
563 hpnew->name = nmem_strdup(ch->nmem, name);
564 hpnew->value = nmem_strdup(ch->nmem, value);
578 static int http_proxy(struct http_request *rq)
580 struct http_channel *c = rq->channel;
581 struct http_proxy *p = c->proxy;
582 struct http_header *hp;
583 struct http_buf *requestbuf;
584 char server_via[128] = "";
585 char server_port[16] = "";
586 struct conf_server *ser = global_parameters.server;
588 if (!p) // This is a new connection. Create a proxy channel
595 if (!(pe = getprotobyname("tcp"))) {
598 if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
600 yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
603 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
604 &one, sizeof(one)) < 0)
606 if ((flags = fcntl(sock, F_GETFL, 0)) < 0)
607 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
608 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
609 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
610 if (connect(sock, (struct sockaddr *) proxy_addr,
611 sizeof(*proxy_addr)) < 0)
612 if (errno != EINPROGRESS)
614 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
618 p = xmalloc(sizeof(struct http_proxy));
621 p->first_response = 1;
623 // We will add EVENT_OUTPUT below
624 p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
625 iochan_setdata(p->iochan, p);
626 pazpar2_add_channel(p->iochan);
629 // Do _not_ modify Host: header, just checking it's existence
630 for (hp = rq->headers; hp; hp = hp->next)
631 if (!strcmp(hp->name, "Host"))
635 yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
639 // Add new header about paraz2 version, host, remote client address, etc.
642 hp = http_header_append(c, hp,
643 "X-Pazpar2-Version", PACKAGE_VERSION);
644 hp = http_header_append(c, hp,
645 "X-Pazpar2-Server-Host", ser->host);
646 sprintf(server_port, "%d", ser->port);
647 hp = http_header_append(c, hp,
648 "X-Pazpar2-Server-Port", server_port);
649 sprintf(server_via, "1.1 %s:%s (%s/%s)",
650 ser->host, server_port, PACKAGE_NAME, PACKAGE_VERSION);
651 hp = http_header_append(c, hp, "Via" , server_via);
652 hp = http_header_append(c, hp, "X-Forwarded-For", c->addr);
655 requestbuf = http_serialize_request(rq);
656 http_buf_enqueue(&p->oqueue, requestbuf);
657 iochan_setflag(p->iochan, EVENT_OUTPUT);
661 void http_send_response(struct http_channel *ch)
663 struct http_response *rs = ch->response;
667 hb = http_serialize_response(ch, rs);
670 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
671 http_destroy(ch->iochan);
675 http_buf_enqueue(&ch->oqueue, hb);
676 iochan_setflag(ch->iochan, EVENT_OUTPUT);
677 ch->state = Http_Idle;
681 static void http_io(IOCHAN i, int event)
683 struct http_channel *hc = iochan_getdata(i);
688 struct http_buf *htbuf;
691 htbuf = http_buf_create();
692 res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
693 if (res == -1 && errno == EAGAIN)
695 http_buf_destroy(htbuf);
700 http_buf_destroy(htbuf);
706 htbuf->buf[res] = '\0';
708 http_buf_enqueue(&hc->iqueue, htbuf);
711 if (hc->state == Http_Busy)
713 if ((reqlen = request_check(hc->iqueue)) <= 2)
716 nmem_reset(hc->nmem);
717 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
719 yaz_log(YLOG_WARN, "Failed to parse request");
724 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
726 *hc->request->search ? "?" : "",
727 hc->request->search);
728 if (http_weshouldproxy(hc->request))
729 http_proxy(hc->request);
732 // Execute our business logic!
733 hc->state = Http_Busy;
738 yaz_log(YLOG_DEBUG, "We think we have more input to read. Forcing event");
739 iochan_setevent(i, EVENT_INPUT);
747 struct http_buf *wb = hc->oqueue;
748 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
751 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
757 hc->oqueue = hc->oqueue->next;
758 http_buf_destroy(wb);
766 if (!strcmp(hc->version, "1.0"))
773 iochan_clearflag(i, EVENT_OUTPUT);
775 iochan_setevent(hc->iochan, EVENT_INPUT);
780 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
781 http_destroy(i); // Server closed; we're done
784 yaz_log(YLOG_WARN, "Unexpected event on connection");
790 // If this hostname contains our proxy host as a prefix, replace with myurl
791 static char *sub_hostname(struct http_channel *c, char *buf)
794 if (strlen(buf) > 1023)
796 if (strncmp(buf, "http://", 7))
798 if (!strncmp(buf + 7, proxy_url, strlen(proxy_url)))
801 strcat(tmp, buf + strlen(proxy_url) + 7);
802 return nmem_strdup(c->nmem, tmp);
808 // Handles I/O on a client connection to a backend web server (proxy mode)
809 static void proxy_io(IOCHAN pi, int event)
811 struct http_proxy *pc = iochan_getdata(pi);
812 struct http_channel *hc = pc->channel;
817 struct http_buf *htbuf;
820 htbuf = http_buf_create();
821 res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
822 if (res == 0 || (res < 0 && errno != EINPROGRESS))
826 yaz_log(YLOG_WARN, "Proxy read came up short");
827 // Close channel and alert client HTTP channel that we're gone
828 http_buf_destroy(htbuf);
829 close(iochan_getfd(pi));
835 http_destroy(hc->iochan);
841 htbuf->buf[res] = '\0';
845 if (pc->first_response) // Check if this is a redirect
848 if ((len = package_check(htbuf->buf)))
850 struct http_response *res = http_parse_response_buf(hc, htbuf->buf, len);
853 struct http_header *h;
854 for (h = res->headers; h; h = h->next)
855 if (!strcmp(h->name, "Location"))
857 // We found a location header. Rewrite it.
858 struct http_buf *buf;
859 h->value = sub_hostname(hc, h->value);
860 buf = http_serialize_response(hc, res);
861 yaz_log(YLOG_LOG, "Proxy rewrite");
862 http_buf_enqueue(&hc->oqueue, buf);
868 pc->first_response = 0;
871 // Write any remaining payload
872 if (htbuf->len - htbuf->offset > 0)
873 http_buf_enqueue(&hc->oqueue, htbuf);
875 iochan_setflag(hc->iochan, EVENT_OUTPUT);
878 if (!(htbuf = pc->oqueue))
880 iochan_clearflag(pi, EVENT_OUTPUT);
883 res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
886 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
887 http_destroy(hc->iochan);
890 if (res == htbuf->len)
892 struct http_buf *np = htbuf->next;
893 http_buf_destroy(htbuf);
899 htbuf->offset += res;
903 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
907 yaz_log(YLOG_WARN, "Unexpected event on connection");
908 http_destroy(hc->iochan);
913 static void http_destroy(IOCHAN i)
915 struct http_channel *s = iochan_getdata(i);
919 if (s->proxy->iochan)
921 close(iochan_getfd(s->proxy->iochan));
922 iochan_destroy(s->proxy->iochan);
924 http_buf_destroy_queue(s->proxy->oqueue);
927 s->next = http_channel_freelist;
928 http_channel_freelist = s;
929 close(iochan_getfd(i));
933 static struct http_channel *http_create(const char *addr)
935 struct http_channel *r = http_channel_freelist;
939 http_channel_freelist = r->next;
941 wrbuf_rewind(r->wrbuf);
945 r = xmalloc(sizeof(struct http_channel));
946 r->nmem = nmem_create();
947 r->wrbuf = wrbuf_alloc();
951 r->iqueue = r->oqueue = 0;
952 r->state = Http_Idle;
957 yaz_log(YLOG_WARN, "Invalid HTTP forward address");
960 strcpy(r->addr, addr);
965 /* Accept a new command connection */
966 static void http_accept(IOCHAN i, int event)
968 struct sockaddr_in addr;
969 int fd = iochan_getfd(i);
974 struct http_channel *ch;
977 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
979 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
982 if ((flags = fcntl(s, F_GETFL, 0)) < 0)
983 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
984 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
985 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
987 yaz_log(YLOG_DEBUG, "New command connection");
988 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
990 ch = http_create(inet_ntoa(addr.sin_addr));
992 iochan_setdata(c, ch);
994 pazpar2_add_channel(c);
997 /* Create a http-channel listener, syntax [host:]port */
998 void http_init(const char *addr)
1003 struct sockaddr_in myaddr;
1008 yaz_log(YLOG_LOG, "HTTP listener %s", addr);
1010 memset(&myaddr, 0, sizeof myaddr);
1011 myaddr.sin_family = AF_INET;
1012 pp = strchr(addr, ':');
1015 int len = pp - addr;
1019 strncpy(hostname, addr, len);
1020 hostname[len] = '\0';
1021 if (!(he = gethostbyname(hostname))){
1022 yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
1026 memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1027 port = atoi(pp + 1);
1029 yaz_log(YLOG_LOG, "HTTP address %s:%d",
1030 "" == he->h_addr_list[0] ? he->h_addr_list[0] : "127.0.0.1" ,
1037 myaddr.sin_addr.s_addr = INADDR_ANY;
1040 myaddr.sin_port = htons(port);
1042 if (!(p = getprotobyname("tcp"))) {
1045 if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
1046 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
1047 if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
1048 &one, sizeof(one)) < 0)
1051 if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0)
1053 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
1056 if (listen(l, SOMAXCONN) < 0)
1058 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
1062 c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
1063 pazpar2_add_channel(c);
1066 void http_set_proxyaddr(char *host, char *base_url)
1072 strcpy(myurl, base_url);
1073 strcpy(proxy_url, host);
1074 p = strchr(host, ':');
1075 yaz_log(YLOG_DEBUG, "Proxying for %s", host);
1076 yaz_log(YLOG_LOG, "HTTP backend %s", proxy_url);
1083 if (!(he = gethostbyname(host)))
1085 fprintf(stderr, "Failed to lookup '%s'\n", host);
1088 proxy_addr = xmalloc(sizeof(struct sockaddr_in));
1089 proxy_addr->sin_family = he->h_addrtype;
1090 memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1091 proxy_addr->sin_port = htons(port);
1097 * indent-tabs-mode: nil
1099 * vim: shiftwidth=4 tabstop=8 expandtab