2 * $Id: http.c,v 1.22 2007-04-08 23:04:20 adam Exp $
6 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <arpa/inet.h>
27 #include <yaz/yaz-util.h>
28 #include <yaz/comstack.h>
36 #include "http_command.h"
38 static void proxy_io(IOCHAN i, int event);
39 static struct http_channel *http_create(const char *addr);
40 static void http_destroy(IOCHAN i);
42 extern IOCHAN channel_list;
43 extern struct parameters global_parameters;
46 // If this is set, we proxy normal HTTP requests
47 static struct sockaddr_in *proxy_addr = 0;
48 static char proxy_url[256] = "";
49 static char myurl[256] = "";
50 static struct http_buf *http_buf_freelist = 0;
51 static struct http_channel *http_channel_freelist = 0;
53 static struct http_buf *http_buf_create()
57 if (http_buf_freelist)
59 r = http_buf_freelist;
60 http_buf_freelist = http_buf_freelist->next;
63 r = xmalloc(sizeof(struct http_buf));
70 static void http_buf_destroy(struct http_buf *b)
72 b->next = http_buf_freelist;
73 http_buf_freelist = b;
76 static void http_buf_destroy_queue(struct http_buf *b)
88 // Calculate length of chain
89 static int http_buf_len(struct http_buf *b)
92 for (; b; b = b->next)
98 static struct http_buf *http_buf_bybuf(char *b, int len)
100 struct http_buf *res = 0;
101 struct http_buf **p = &res;
106 if (tocopy > HTTP_BUF_SIZE)
107 tocopy = HTTP_BUF_SIZE;
108 *p = http_buf_create();
109 memcpy((*p)->buf, b, tocopy);
118 // Add a (chain of) buffers to the end of an existing queue.
119 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
122 queue = &(*queue)->next;
126 static struct http_buf *http_buf_bywrbuf(WRBUF wrbuf)
128 // Heavens to Betsy (buf)!
129 return http_buf_bybuf(wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
132 // Non-destructively collapse chain of buffers into a string (max *len)
134 static int http_buf_peek(struct http_buf *b, char *buf, int len)
137 while (b && rd < len)
139 int toread = len - rd;
142 memcpy(buf + rd, b->buf + b->offset, toread);
150 // Ddestructively munch up to len from head of queue.
151 static int http_buf_read(struct http_buf **b, char *buf, int len)
154 while ((*b) && rd < len)
156 int toread = len - rd;
157 if (toread > (*b)->len)
159 memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
161 if (toread < (*b)->len)
164 (*b)->offset += toread;
169 struct http_buf *n = (*b)->next;
170 http_buf_destroy(*b);
178 // Buffers may overlap.
179 static void urldecode(char *i, char *o)
191 sscanf(i, "%2hhx", o);
201 // Warning: Buffers may not overlap
202 void urlencode(const char *i, char *o)
206 if (strchr(" /:", *i))
208 sprintf(o, "%%%.2X", (int) *i);
218 void http_addheader(struct http_response *r, const char *name, const char *value)
220 struct http_channel *c = r->channel;
221 struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
222 h->name = nmem_strdup(c->nmem, name);
223 h->value = nmem_strdup(c->nmem, value);
224 h->next = r->headers;
228 char *http_argbyname(struct http_request *r, char *name)
230 struct http_argument *p;
233 for (p = r->arguments; p; p = p->next)
234 if (!strcmp(p->name, name))
239 char *http_headerbyname(struct http_header *h, char *name)
241 for (; h; h = h->next)
242 if (!strcmp(h->name, name))
247 struct http_response *http_create_response(struct http_channel *c)
249 struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
250 strcpy(r->code, "200");
258 // Check if buf contains a package (minus payload)
259 static int package_check(const char *buf)
262 while (*buf) // Check if we have a sequence of lines terminated by an empty line
264 char *b = strstr(buf, "\r\n");
269 len += (b - buf) + 2;
277 // Check if we have a request. Return 0 or length
278 // (including trailing CRNL) FIXME: Does not deal gracefully with requests
279 // carrying payload but this is kind of OK since we will reject anything
280 // other than an empty GET
281 static int request_check(struct http_buf *queue)
285 http_buf_peek(queue, tmp, 4096);
286 return package_check(tmp);
289 struct http_response *http_parse_response_buf(struct http_channel *c, const char *buf, int len)
292 struct http_response *r = http_create_response(c);
294 struct http_header **hp = &r->headers;
298 memcpy(tmp, buf, len);
299 for (p = tmp; *p && *p != ' '; p++) // Skip HTTP version
303 for (p2 = p; *p2 && *p2 != ' ' && p2 - p < 3; p2++)
304 r->code[p2 - p] = *p2;
305 if (!(p = strstr(tmp, "\r\n")))
310 if (!(p2 = strstr(p, "\r\n")))
312 if (p == p2) // End of headers
316 struct http_header *h = *hp = nmem_malloc(c->nmem, sizeof(*h));
317 char *value = strchr(p, ':');
321 h->name = nmem_strdup(c->nmem, p);
322 while (isspace(*value))
324 if (value >= p2) // Empty header;
331 h->value = nmem_strdup(c->nmem, value);
340 struct http_request *http_parse_request(struct http_channel *c, struct http_buf **queue,
343 struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
350 if (http_buf_read(queue, buf, len) < len)
358 for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
362 yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
367 if (!(buf = strchr(buf, ' ')))
369 yaz_log(YLOG_WARN, "Syntax error in request (1)");
373 if (!(p = strchr(buf, ' ')))
375 yaz_log(YLOG_WARN, "Syntax error in request (2)");
379 if ((p2 = strchr(buf, '?'))) // Do we have arguments?
381 r->path = nmem_strdup(c->nmem, buf);
384 r->search = nmem_strdup(c->nmem, p2);
388 struct http_argument *a;
389 char *equal = strchr(p2, '=');
390 char *eoa = strchr(p2, '&');
393 yaz_log(YLOG_WARN, "Expected '=' in argument");
397 eoa = equal + strlen(equal); // last argument
400 a = nmem_malloc(c->nmem, sizeof(struct http_argument));
402 a->name = nmem_strdup(c->nmem, p2);
403 urldecode(equal, equal);
404 a->value = nmem_strdup(c->nmem, equal);
405 a->next = r->arguments;
412 if (strncmp(buf, "HTTP/", 5))
413 strcpy(r->http_version, "1.0");
417 if (!(p = strstr(buf, "\r\n")))
421 strcpy(r->http_version, buf);
424 strcpy(c->version, r->http_version);
429 if (!(p = strstr(buf, "\r\n")))
435 struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
436 if (!(p2 = strchr(buf, ':')))
439 h->name = nmem_strdup(c->nmem, buf);
442 if (p2 >= p) // Empty header?
448 h->value = nmem_strdup(c->nmem, p2);
449 h->next = r->headers;
458 static struct http_buf *http_serialize_response(struct http_channel *c,
459 struct http_response *r)
461 struct http_header *h;
463 wrbuf_rewind(c->wrbuf);
464 wrbuf_printf(c->wrbuf, "HTTP/1.1 %s %s\r\n", r->code, r->msg);
465 for (h = r->headers; h; h = h->next)
466 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
469 wrbuf_printf(c->wrbuf, "Content-length: %d\r\n", r->payload ?
470 (int) strlen(r->payload) : 0);
471 wrbuf_printf(c->wrbuf, "Content-type: text/xml\r\n");
473 wrbuf_puts(c->wrbuf, "\r\n");
476 wrbuf_puts(c->wrbuf, r->payload);
478 return http_buf_bywrbuf(c->wrbuf);
481 // Serialize a HTTP request
482 static struct http_buf *http_serialize_request(struct http_request *r)
484 struct http_channel *c = r->channel;
485 struct http_header *h;
486 struct http_argument *a;
488 wrbuf_rewind(c->wrbuf);
489 wrbuf_printf(c->wrbuf, "%s %s", r->method, r->path);
493 wrbuf_putc(c->wrbuf, '?');
494 for (a = r->arguments; a; a = a->next) {
495 if (a != r->arguments)
496 wrbuf_putc(c->wrbuf, '&');
497 wrbuf_printf(c->wrbuf, "%s=%s", a->name, a->value);
501 wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
503 for (h = r->headers; h; h = h->next)
504 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
506 wrbuf_puts(c->wrbuf, "\r\n");
508 return http_buf_bywrbuf(c->wrbuf);
512 static int http_weshouldproxy(struct http_request *rq)
514 if (proxy_addr && !strstr(rq->path, "search.pz2"))
520 struct http_header * http_header_append(struct http_channel *ch,
521 struct http_header * hp,
525 struct http_header *hpnew = 0;
530 while (hp && hp->next)
533 if(name && strlen(name)&& value && strlen(value)){
534 hpnew = nmem_malloc(ch->nmem, sizeof *hpnew);
535 hpnew->name = nmem_strdup(ch->nmem, name);
536 hpnew->value = nmem_strdup(ch->nmem, value);
550 static int http_proxy(struct http_request *rq)
552 struct http_channel *c = rq->channel;
553 struct http_proxy *p = c->proxy;
554 struct http_header *hp;
555 struct http_buf *requestbuf;
556 char server_via[128] = "";
557 char server_port[16] = "";
558 struct conf_server *ser = global_parameters.server;
560 if (!p) // This is a new connection. Create a proxy channel
567 if (!(pe = getprotobyname("tcp"))) {
570 if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
572 yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
575 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
576 &one, sizeof(one)) < 0)
578 if ((flags = fcntl(sock, F_GETFL, 0)) < 0)
579 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
580 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
581 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
582 if (connect(sock, (struct sockaddr *) proxy_addr,
583 sizeof(*proxy_addr)) < 0)
584 if (errno != EINPROGRESS)
586 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
590 p = xmalloc(sizeof(struct http_proxy));
593 p->first_response = 1;
595 // We will add EVENT_OUTPUT below
596 p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
597 iochan_setdata(p->iochan, p);
598 p->iochan->next = channel_list;
599 channel_list = p->iochan;
602 // Do _not_ modify Host: header, just checking it's existence
603 for (hp = rq->headers; hp; hp = hp->next)
604 if (!strcmp(hp->name, "Host"))
608 yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
612 // Add new header about paraz2 version, host, remote client address, etc.
615 hp = http_header_append(c, hp,
616 "X-Pazpar2-Version", PACKAGE_VERSION);
617 hp = http_header_append(c, hp,
618 "X-Pazpar2-Server-Host", ser->host);
619 sprintf(server_port, "%d", ser->port);
620 hp = http_header_append(c, hp,
621 "X-Pazpar2-Server-Port", server_port);
622 sprintf(server_via, "1.1 %s:%s (%s/%s)",
623 ser->host, server_port, PACKAGE_NAME, PACKAGE_VERSION);
624 hp = http_header_append(c, hp, "Via" , server_via);
625 hp = http_header_append(c, hp, "X-Forwarded-For", c->addr);
628 requestbuf = http_serialize_request(rq);
629 http_buf_enqueue(&p->oqueue, requestbuf);
630 iochan_setflag(p->iochan, EVENT_OUTPUT);
634 void http_send_response(struct http_channel *ch)
636 struct http_response *rs = ch->response;
640 hb = http_serialize_response(ch, rs);
643 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
644 http_destroy(ch->iochan);
648 http_buf_enqueue(&ch->oqueue, hb);
649 iochan_setflag(ch->iochan, EVENT_OUTPUT);
650 ch->state = Http_Idle;
654 static void http_io(IOCHAN i, int event)
656 struct http_channel *hc = iochan_getdata(i);
661 struct http_buf *htbuf;
664 htbuf = http_buf_create();
665 res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
666 if (res == -1 && errno == EAGAIN)
668 http_buf_destroy(htbuf);
673 http_buf_destroy(htbuf);
679 htbuf->buf[res] = '\0';
681 http_buf_enqueue(&hc->iqueue, htbuf);
684 if (hc->state == Http_Busy)
686 if ((reqlen = request_check(hc->iqueue)) <= 2)
689 nmem_reset(hc->nmem);
690 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
692 yaz_log(YLOG_WARN, "Failed to parse request");
697 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
699 *hc->request->search ? "?" : "",
700 hc->request->search);
701 if (http_weshouldproxy(hc->request))
702 http_proxy(hc->request);
705 // Execute our business logic!
706 hc->state = Http_Busy;
711 yaz_log(YLOG_DEBUG, "We think we have more input to read. Forcing event");
712 iochan_setevent(i, EVENT_INPUT);
720 struct http_buf *wb = hc->oqueue;
721 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
724 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
730 hc->oqueue = hc->oqueue->next;
731 http_buf_destroy(wb);
739 if (!strcmp(hc->version, "1.0"))
746 iochan_clearflag(i, EVENT_OUTPUT);
748 iochan_setevent(hc->iochan, EVENT_INPUT);
753 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
754 http_destroy(i); // Server closed; we're done
757 yaz_log(YLOG_WARN, "Unexpected event on connection");
763 // If this hostname contains our proxy host as a prefix, replace with myurl
764 static char *sub_hostname(struct http_channel *c, char *buf)
767 if (strlen(buf) > 1023)
769 if (strncmp(buf, "http://", 7))
771 if (!strncmp(buf + 7, proxy_url, strlen(proxy_url)))
774 strcat(tmp, buf + strlen(proxy_url) + 7);
775 return nmem_strdup(c->nmem, tmp);
781 // Handles I/O on a client connection to a backend web server (proxy mode)
782 static void proxy_io(IOCHAN pi, int event)
784 struct http_proxy *pc = iochan_getdata(pi);
785 struct http_channel *hc = pc->channel;
790 struct http_buf *htbuf;
793 htbuf = http_buf_create();
794 res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
795 if (res == 0 || (res < 0 && errno != EINPROGRESS))
799 yaz_log(YLOG_WARN, "Proxy read came up short");
800 // Close channel and alert client HTTP channel that we're gone
801 http_buf_destroy(htbuf);
802 close(iochan_getfd(pi));
808 http_destroy(hc->iochan);
814 htbuf->buf[res] = '\0';
818 if (pc->first_response) // Check if this is a redirect
821 if ((len = package_check(htbuf->buf)))
823 struct http_response *res = http_parse_response_buf(hc, htbuf->buf, len);
826 struct http_header *h;
827 for (h = res->headers; h; h = h->next)
828 if (!strcmp(h->name, "Location"))
830 // We found a location header. Rewrite it.
831 struct http_buf *buf;
832 h->value = sub_hostname(hc, h->value);
833 buf = http_serialize_response(hc, res);
834 yaz_log(YLOG_LOG, "Proxy rewrite");
835 http_buf_enqueue(&hc->oqueue, buf);
841 pc->first_response = 0;
844 // Write any remaining payload
845 if (htbuf->len - htbuf->offset > 0)
846 http_buf_enqueue(&hc->oqueue, htbuf);
848 iochan_setflag(hc->iochan, EVENT_OUTPUT);
851 if (!(htbuf = pc->oqueue))
853 iochan_clearflag(pi, EVENT_OUTPUT);
856 res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
859 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
860 http_destroy(hc->iochan);
863 if (res == htbuf->len)
865 struct http_buf *np = htbuf->next;
866 http_buf_destroy(htbuf);
872 htbuf->offset += res;
876 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
880 yaz_log(YLOG_WARN, "Unexpected event on connection");
881 http_destroy(hc->iochan);
886 static void http_destroy(IOCHAN i)
888 struct http_channel *s = iochan_getdata(i);
892 if (s->proxy->iochan)
894 close(iochan_getfd(s->proxy->iochan));
895 iochan_destroy(s->proxy->iochan);
897 http_buf_destroy_queue(s->proxy->oqueue);
900 s->next = http_channel_freelist;
901 http_channel_freelist = s;
902 close(iochan_getfd(i));
906 static struct http_channel *http_create(const char *addr)
908 struct http_channel *r = http_channel_freelist;
912 http_channel_freelist = r->next;
914 wrbuf_rewind(r->wrbuf);
918 r = xmalloc(sizeof(struct http_channel));
919 r->nmem = nmem_create();
920 r->wrbuf = wrbuf_alloc();
924 r->iqueue = r->oqueue = 0;
925 r->state = Http_Idle;
930 yaz_log(YLOG_WARN, "Invalid HTTP forward address");
933 r->addr = nmem_strdup(r->nmem, addr);
938 /* Accept a new command connection */
939 static void http_accept(IOCHAN i, int event)
941 struct sockaddr_in addr;
942 int fd = iochan_getfd(i);
947 struct http_channel *ch;
950 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
952 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
955 if ((flags = fcntl(s, F_GETFL, 0)) < 0)
956 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
957 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
958 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
960 yaz_log(YLOG_DEBUG, "New command connection");
961 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
963 ch = http_create(inet_ntoa(addr.sin_addr));
965 iochan_setdata(c, ch);
967 c->next = channel_list;
971 /* Create a http-channel listener, syntax [host:]port */
972 void http_init(const char *addr)
977 struct sockaddr_in myaddr;
982 yaz_log(YLOG_LOG, "HTTP listener %s", addr);
984 memset(&myaddr, 0, sizeof myaddr);
985 myaddr.sin_family = AF_INET;
986 pp = strchr(addr, ':');
993 strncpy(hostname, addr, len);
994 hostname[len] = '\0';
995 if (!(he = gethostbyname(hostname)))
997 yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
1001 memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1002 port = atoi(pp + 1);
1004 yaz_log(YLOG_LOG, "HTTP address %s:%d",
1005 "" == he->h_addr_list[0] ? he->h_addr_list[0] : "127.0.0.1" ,
1014 myaddr.sin_addr.s_addr = INADDR_ANY;
1017 // get hostname from system - after deciding to bind to any
1018 // IP address this box might have.
1019 if (0 == gethostname(h, len)){
1021 global_parameters.server->host = nmem_strdup(nmem, h);
1023 yaz_log(YLOG_WARN, "Could not get host name");
1028 myaddr.sin_port = htons(port);
1031 if (!(p = getprotobyname("tcp"))) {
1034 if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
1035 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
1036 if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
1037 &one, sizeof(one)) < 0)
1040 if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0)
1041 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
1042 if (listen(l, SOMAXCONN) < 0)
1043 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
1045 c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
1046 c->next = channel_list;
1050 void http_set_proxyaddr(char *host, char *base_url)
1056 strcpy(myurl, base_url);
1057 strcpy(proxy_url, host);
1058 p = strchr(host, ':');
1059 yaz_log(YLOG_DEBUG, "Proxying for %s", host);
1060 yaz_log(YLOG_LOG, "HTTP backend %s", proxy_url);
1067 if (!(he = gethostbyname(host)))
1069 fprintf(stderr, "Failed to lookup '%s'\n", host);
1072 proxy_addr = xmalloc(sizeof(struct sockaddr_in));
1073 proxy_addr->sin_family = he->h_addrtype;
1074 memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1075 proxy_addr->sin_port = htons(port);
1081 * indent-tabs-mode: nil
1083 * vim: shiftwidth=4 tabstop=8 expandtab