2 * $Id: http.c,v 1.10 2007-02-05 16:15:41 quinn Exp $
6 #include <sys/socket.h>
22 #include <netinet/in.h>
24 #include <yaz/yaz-util.h>
25 #include <yaz/comstack.h>
32 #include "http_command.h"
34 static void proxy_io(IOCHAN i, int event);
35 static struct http_channel *http_create(void);
36 static void http_destroy(IOCHAN i);
38 extern IOCHAN channel_list;
40 static struct sockaddr_in *proxy_addr = 0; // If this is set, we proxy normal HTTP requests
41 static char proxy_url[256] = "";
42 static char myurl[256] = "";
43 static struct http_buf *http_buf_freelist = 0;
44 static struct http_channel *http_channel_freelist = 0;
46 static struct http_buf *http_buf_create()
50 if (http_buf_freelist)
52 r = http_buf_freelist;
53 http_buf_freelist = http_buf_freelist->next;
56 r = xmalloc(sizeof(struct http_buf));
63 static void http_buf_destroy(struct http_buf *b)
65 b->next = http_buf_freelist;
66 http_buf_freelist = b;
69 static void http_buf_destroy_queue(struct http_buf *b)
81 // Calculate length of chain
82 static int http_buf_len(struct http_buf *b)
85 for (; b; b = b->next)
91 static struct http_buf *http_buf_bybuf(char *b, int len)
93 struct http_buf *res = 0;
94 struct http_buf **p = &res;
99 if (tocopy > HTTP_BUF_SIZE)
100 tocopy = HTTP_BUF_SIZE;
101 *p = http_buf_create();
102 memcpy((*p)->buf, b, tocopy);
111 // Add a (chain of) buffers to the end of an existing queue.
112 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
115 queue = &(*queue)->next;
119 static struct http_buf *http_buf_bywrbuf(WRBUF wrbuf)
121 // Heavens to Betsy (buf)!
122 return http_buf_bybuf(wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
125 // Non-destructively collapse chain of buffers into a string (max *len)
127 static int http_buf_peek(struct http_buf *b, char *buf, int len)
130 while (b && rd < len)
132 int toread = len - rd;
135 memcpy(buf + rd, b->buf + b->offset, toread);
143 // Ddestructively munch up to len from head of queue.
144 static int http_buf_read(struct http_buf **b, char *buf, int len)
147 while ((*b) && rd < len)
149 int toread = len - rd;
150 if (toread > (*b)->len)
152 memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
154 if (toread < (*b)->len)
157 (*b)->offset += toread;
162 struct http_buf *n = (*b)->next;
163 http_buf_destroy(*b);
171 void static urldecode(char *i, char *o)
183 sscanf(i, "%2hhx", o);
193 void http_addheader(struct http_response *r, const char *name, const char *value)
195 struct http_channel *c = r->channel;
196 struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
197 h->name = nmem_strdup(c->nmem, name);
198 h->value = nmem_strdup(c->nmem, value);
199 h->next = r->headers;
203 char *http_argbyname(struct http_request *r, char *name)
205 struct http_argument *p;
208 for (p = r->arguments; p; p = p->next)
209 if (!strcmp(p->name, name))
214 char *http_headerbyname(struct http_header *h, char *name)
216 for (; h; h = h->next)
217 if (!strcmp(h->name, name))
222 struct http_response *http_create_response(struct http_channel *c)
224 struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
225 strcpy(r->code, "200");
233 // Check if buf contains a package (minus payload)
234 static int package_check(const char *buf)
237 while (*buf) // Check if we have a sequence of lines terminated by an empty line
239 char *b = strstr(buf, "\r\n");
244 len += (b - buf) + 2;
252 // Check if we have a request. Return 0 or length
253 // (including trailing CRNL) FIXME: Does not deal gracefully with requests
254 // carrying payload but this is kind of OK since we will reject anything
255 // other than an empty GET
256 static int request_check(struct http_buf *queue)
260 http_buf_peek(queue, tmp, 4096);
261 return package_check(tmp);
264 struct http_response *http_parse_response_buf(struct http_channel *c, const char *buf, int len)
267 struct http_response *r = http_create_response(c);
269 struct http_header **hp = &r->headers;
273 memcpy(tmp, buf, len);
274 for (p = tmp; *p && *p != ' '; p++) // Skip HTTP version
278 for (p2 = p; *p2 && *p2 != ' ' && p2 - p < 3; p2++)
279 r->code[p2 - p] = *p2;
280 if (!(p = strstr(tmp, "\r\n")))
285 if (!(p2 = strstr(p, "\r\n")))
287 if (p == p2) // End of headers
291 struct http_header *h = *hp = nmem_malloc(c->nmem, sizeof(*h));
292 char *value = strchr(p, ':');
296 h->name = nmem_strdup(c->nmem, p);
297 while (isspace(*value))
299 if (value >= p2) // Empty header;
306 h->value = nmem_strdup(c->nmem, value);
315 struct http_request *http_parse_request(struct http_channel *c, struct http_buf **queue,
318 struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
325 if (http_buf_read(queue, buf, len) < len)
333 for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
337 yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
342 if (!(buf = strchr(buf, ' ')))
344 yaz_log(YLOG_WARN, "Syntax error in request (1)");
348 if (!(p = strchr(buf, ' ')))
350 yaz_log(YLOG_WARN, "Syntax error in request (2)");
354 if ((p2 = strchr(buf, '?'))) // Do we have arguments?
356 r->path = nmem_strdup(c->nmem, buf);
359 r->search = nmem_strdup(c->nmem, p2);
363 struct http_argument *a;
364 char *equal = strchr(p2, '=');
365 char *eoa = strchr(p2, '&');
368 yaz_log(YLOG_WARN, "Expected '=' in argument");
372 eoa = equal + strlen(equal); // last argument
375 a = nmem_malloc(c->nmem, sizeof(struct http_argument));
377 a->name = nmem_strdup(c->nmem, p2);
378 urldecode(equal, equal);
379 a->value = nmem_strdup(c->nmem, equal);
380 a->next = r->arguments;
387 if (strncmp(buf, "HTTP/", 5))
388 strcpy(r->http_version, "1.0");
392 if (!(p = strstr(buf, "\r\n")))
396 strcpy(r->http_version, buf);
399 strcpy(c->version, r->http_version);
404 if (!(p = strstr(buf, "\r\n")))
410 struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
411 if (!(p2 = strchr(buf, ':')))
414 h->name = nmem_strdup(c->nmem, buf);
417 if (p2 >= p) // Empty header?
423 h->value = nmem_strdup(c->nmem, p2);
424 h->next = r->headers;
433 static struct http_buf *http_serialize_response(struct http_channel *c,
434 struct http_response *r)
436 struct http_header *h;
438 wrbuf_rewind(c->wrbuf);
439 wrbuf_printf(c->wrbuf, "HTTP/1.1 %s %s\r\n", r->code, r->msg);
440 for (h = r->headers; h; h = h->next)
441 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
444 wrbuf_printf(c->wrbuf, "Content-length: %d\r\n", r->payload ?
445 (int) strlen(r->payload) : 0);
446 wrbuf_printf(c->wrbuf, "Content-type: text/xml\r\n");
448 wrbuf_puts(c->wrbuf, "\r\n");
451 wrbuf_puts(c->wrbuf, r->payload);
453 return http_buf_bywrbuf(c->wrbuf);
456 // Serialize a HTTP request
457 static struct http_buf *http_serialize_request(struct http_request *r)
459 struct http_channel *c = r->channel;
460 struct http_header *h;
461 struct http_argument *a;
463 wrbuf_rewind(c->wrbuf);
464 wrbuf_printf(c->wrbuf, "%s %s", r->method, r->path);
468 wrbuf_putc(c->wrbuf, '?');
469 for (a = r->arguments; a; a = a->next) {
470 if (a != r->arguments)
471 wrbuf_putc(c->wrbuf, '&');
472 wrbuf_printf(c->wrbuf, "%s=%s", a->name, a->value);
476 wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
478 for (h = r->headers; h; h = h->next)
479 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
481 wrbuf_puts(c->wrbuf, "\r\n");
483 return http_buf_bywrbuf(c->wrbuf);
487 static int http_weshouldproxy(struct http_request *rq)
489 if (proxy_addr && !strstr(rq->path, "search.pz2"))
494 static int http_proxy(struct http_request *rq)
496 struct http_channel *c = rq->channel;
497 struct http_proxy *p = c->proxy;
498 struct http_header *hp;
499 struct http_buf *requestbuf;
501 if (!p) // This is a new connection. Create a proxy channel
508 if (!(pe = getprotobyname("tcp"))) {
511 if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
513 yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
516 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
517 &one, sizeof(one)) < 0)
519 if ((flags = fcntl(sock, F_GETFL, 0)) < 0)
520 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
521 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
522 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
523 if (connect(sock, (struct sockaddr *) proxy_addr, sizeof(*proxy_addr)) < 0)
524 if (errno != EINPROGRESS)
526 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
530 p = xmalloc(sizeof(struct http_proxy));
533 p->first_response = 1;
535 // We will add EVENT_OUTPUT below
536 p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
537 iochan_setdata(p->iochan, p);
538 p->iochan->next = channel_list;
539 channel_list = p->iochan;
542 // Modify Host: header
543 for (hp = rq->headers; hp; hp = hp->next)
544 if (!strcmp(hp->name, "Host"))
548 yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
551 hp->value = nmem_strdup(c->nmem, proxy_url);
552 requestbuf = http_serialize_request(rq);
553 http_buf_enqueue(&p->oqueue, requestbuf);
554 iochan_setflag(p->iochan, EVENT_OUTPUT);
558 void http_send_response(struct http_channel *ch)
560 struct http_response *rs = ch->response;
564 hb = http_serialize_response(ch, rs);
567 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
568 http_destroy(ch->iochan);
572 http_buf_enqueue(&ch->oqueue, hb);
573 iochan_setflag(ch->iochan, EVENT_OUTPUT);
574 ch->state = Http_Idle;
578 static void http_io(IOCHAN i, int event)
580 struct http_channel *hc = iochan_getdata(i);
585 struct http_buf *htbuf;
588 htbuf = http_buf_create();
589 res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
590 if (res == -1 && errno == EAGAIN)
592 http_buf_destroy(htbuf);
597 http_buf_destroy(htbuf);
603 htbuf->buf[res] = '\0';
605 http_buf_enqueue(&hc->iqueue, htbuf);
608 if (hc->state == Http_Busy)
610 if ((reqlen = request_check(hc->iqueue)) <= 2)
613 nmem_reset(hc->nmem);
614 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
616 yaz_log(YLOG_WARN, "Failed to parse request");
621 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
623 *hc->request->search ? "?" : "",
624 hc->request->search);
625 if (http_weshouldproxy(hc->request))
626 http_proxy(hc->request);
629 // Execute our business logic!
630 hc->state = Http_Busy;
635 yaz_log(YLOG_DEBUG, "We think we have more input to read. Forcing event");
636 iochan_setevent(i, EVENT_INPUT);
644 struct http_buf *wb = hc->oqueue;
645 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
648 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
654 hc->oqueue = hc->oqueue->next;
655 http_buf_destroy(wb);
663 if (!strcmp(hc->version, "1.0"))
670 iochan_clearflag(i, EVENT_OUTPUT);
672 iochan_setevent(hc->iochan, EVENT_INPUT);
677 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
678 http_destroy(i); // Server closed; we're done
681 yaz_log(YLOG_WARN, "Unexpected event on connection");
686 // If this hostname contains our proxy host as a prefix, replace with myurl
687 static char *sub_hostname(struct http_channel *c, char *buf)
690 if (strlen(buf) > 1023)
692 if (strncmp(buf, "http://", 7))
694 if (!strncmp(buf + 7, proxy_url, strlen(proxy_url)))
697 strcat(tmp, buf + strlen(proxy_url) + 7);
698 return nmem_strdup(c->nmem, tmp);
703 // Handles I/O on a client connection to a backend web server (proxy mode)
704 static void proxy_io(IOCHAN pi, int event)
706 struct http_proxy *pc = iochan_getdata(pi);
707 struct http_channel *hc = pc->channel;
712 struct http_buf *htbuf;
715 htbuf = http_buf_create();
716 res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
717 if (res == 0 || (res < 0 && errno != EINPROGRESS))
721 yaz_log(YLOG_WARN, "Proxy read came up short");
722 // Close channel and alert client HTTP channel that we're gone
723 http_buf_destroy(htbuf);
724 close(iochan_getfd(pi));
730 http_destroy(hc->iochan);
736 htbuf->buf[res] = '\0';
739 if (pc->first_response) // Check if this is a redirect
742 if ((len = package_check(htbuf->buf)))
744 struct http_response *res = http_parse_response_buf(hc, htbuf->buf, len);
747 struct http_header *h;
748 for (h = res->headers; h; h = h->next)
749 if (!strcmp(h->name, "Location"))
751 // We found a location header. Rewrite it.
752 struct http_buf *buf;
753 h->value = sub_hostname(hc, h->value);
754 buf = http_serialize_response(hc, res);
755 http_buf_enqueue(&hc->oqueue, buf);
761 pc->first_response = 0;
763 // Write any remaining payload
764 if (htbuf->len - offset > 0)
768 memmove(htbuf->buf, htbuf->buf + offset, htbuf->len - offset);
769 htbuf->len -= offset;
771 http_buf_enqueue(&hc->oqueue, htbuf + offset);
774 iochan_setflag(hc->iochan, EVENT_OUTPUT);
777 if (!(htbuf = pc->oqueue))
779 iochan_clearflag(pi, EVENT_OUTPUT);
782 res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
785 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
786 http_destroy(hc->iochan);
789 if (res == htbuf->len)
791 struct http_buf *np = htbuf->next;
792 http_buf_destroy(htbuf);
798 htbuf->offset += res;
802 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
806 yaz_log(YLOG_WARN, "Unexpected event on connection");
807 http_destroy(hc->iochan);
812 static void http_destroy(IOCHAN i)
814 struct http_channel *s = iochan_getdata(i);
818 if (s->proxy->iochan)
820 close(iochan_getfd(s->proxy->iochan));
821 iochan_destroy(s->proxy->iochan);
823 http_buf_destroy_queue(s->proxy->oqueue);
826 s->next = http_channel_freelist;
827 http_channel_freelist = s;
828 close(iochan_getfd(i));
832 static struct http_channel *http_create(void)
834 struct http_channel *r = http_channel_freelist;
838 http_channel_freelist = r->next;
840 wrbuf_rewind(r->wrbuf);
844 r = xmalloc(sizeof(struct http_channel));
845 r->nmem = nmem_create();
846 r->wrbuf = wrbuf_alloc();
850 r->iqueue = r->oqueue = 0;
851 r->state = Http_Idle;
858 /* Accept a new command connection */
859 static void http_accept(IOCHAN i, int event)
861 struct sockaddr_in addr;
862 int fd = iochan_getfd(i);
867 struct http_channel *ch;
870 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
872 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
875 if ((flags = fcntl(s, F_GETFL, 0)) < 0)
876 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
877 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
878 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
880 yaz_log(YLOG_DEBUG, "New command connection");
881 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
885 iochan_setdata(c, ch);
887 c->next = channel_list;
891 /* Create a http-channel listener, syntax [host:]port */
892 void http_init(const char *addr)
897 struct sockaddr_in myaddr;
902 yaz_log(YLOG_LOG, "HTTP listener is %s", addr);
904 memset(&myaddr, 0, sizeof myaddr);
905 myaddr.sin_family = AF_INET;
906 pp = strchr(addr, ':');
913 strncpy(hostname, addr, len);
914 hostname[len] = '\0';
915 if (!(he = gethostbyname(hostname)))
917 yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
920 memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
926 myaddr.sin_addr.s_addr = INADDR_ANY;
928 myaddr.sin_port = htons(port);
930 if (!(p = getprotobyname("tcp"))) {
933 if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
934 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
935 if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
936 &one, sizeof(one)) < 0)
939 if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0)
940 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
941 if (listen(l, SOMAXCONN) < 0)
942 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
944 c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
945 c->next = channel_list;
949 void http_set_proxyaddr(char *host, char *base_url)
955 strcpy(myurl, base_url);
956 strcpy(proxy_url, host);
957 p = strchr(host, ':');
958 yaz_log(YLOG_DEBUG, "Proxying for %s", host);
965 if (!(he = gethostbyname(host)))
967 fprintf(stderr, "Failed to lookup '%s'\n", host);
970 proxy_addr = xmalloc(sizeof(struct sockaddr_in));
971 proxy_addr->sin_family = he->h_addrtype;
972 memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
973 proxy_addr->sin_port = htons(port);
979 * indent-tabs-mode: nil
981 * vim: shiftwidth=4 tabstop=8 expandtab