2 * $Id: http.c,v 1.5 2007-01-06 04:54:58 quinn Exp $
6 #include <sys/socket.h>
18 #include <yaz/yaz-util.h>
19 #include <yaz/comstack.h>
26 #include "http_command.h"
28 static void proxy_io(IOCHAN i, int event);
29 static struct http_channel *http_create(void);
30 static void http_destroy(IOCHAN i);
32 extern IOCHAN channel_list;
34 static struct sockaddr_in *proxy_addr = 0; // If this is set, we proxy normal HTTP requests
35 static char proxy_url[256] = "";
36 static struct http_buf *http_buf_freelist = 0;
37 static struct http_channel *http_channel_freelist = 0;
39 static struct http_buf *http_buf_create()
43 if (http_buf_freelist)
45 r = http_buf_freelist;
46 http_buf_freelist = http_buf_freelist->next;
49 r = xmalloc(sizeof(struct http_buf));
56 static void http_buf_destroy(struct http_buf *b)
58 b->next = http_buf_freelist;
59 http_buf_freelist = b;
62 static void http_buf_destroy_queue(struct http_buf *b)
74 // Calculate length of chain
75 static int http_buf_len(struct http_buf *b)
78 for (; b; b = b->next)
84 static struct http_buf *http_buf_bybuf(char *b, int len)
86 struct http_buf *res = 0;
87 struct http_buf **p = &res;
91 *p = http_buf_create();
93 if (tocopy > HTTP_BUF_SIZE)
94 tocopy = HTTP_BUF_SIZE;
95 memcpy((*p)->buf, b, tocopy);
104 // Add a (chain of) buffers to the end of an existing queue.
105 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
108 queue = &(*queue)->next;
112 static struct http_buf *http_buf_bywrbuf(WRBUF wrbuf)
114 // Heavens to Betsy (buf)!
115 return http_buf_bybuf(wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
118 // Non-destructively collapse chain of buffers into a string (max *len)
120 static int http_buf_peek(struct http_buf *b, char *buf, int len)
123 while (b && rd < len)
125 int toread = len - rd;
128 memcpy(buf + rd, b->buf + b->offset, toread);
136 // Ddestructively munch up to len from head of queue.
137 static int http_buf_read(struct http_buf **b, char *buf, int len)
140 while ((*b) && rd < len)
142 int toread = len - rd;
143 if (toread > (*b)->len)
145 memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
147 if (toread < (*b)->len)
150 (*b)->offset += toread;
155 struct http_buf *n = (*b)->next;
156 http_buf_destroy(*b);
164 void static urldecode(char *i, char *o)
176 sscanf(i, "%2hhx", o);
186 void http_addheader(struct http_response *r, const char *name, const char *value)
188 struct http_channel *c = r->channel;
189 struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
190 h->name = nmem_strdup(c->nmem, name);
191 h->value = nmem_strdup(c->nmem, value);
192 h->next = r->headers;
196 char *http_argbyname(struct http_request *r, char *name)
198 struct http_argument *p;
201 for (p = r->arguments; p; p = p->next)
202 if (!strcmp(p->name, name))
207 char *http_headerbyname(struct http_request *r, char *name)
209 struct http_header *p;
210 for (p = r->headers; p; p = p->next)
211 if (!strcmp(p->name, name))
216 struct http_response *http_create_response(struct http_channel *c)
218 struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
219 strcpy(r->code, "200");
227 // Check if we have a complete request. Return 0 or length (including trailing newline)
228 // FIXME: Does not deal gracefully with requests carrying payload
229 // but this is kind of OK since we will reject anything other than an empty GET
230 static int request_check(struct http_buf *queue)
236 http_buf_peek(queue, tmp, 4096);
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 struct http_request *http_parse_request(struct http_channel *c, struct http_buf **queue,
255 struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
262 if (http_buf_read(queue, buf, len) < len)
270 for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
274 yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
279 if (!(buf = strchr(buf, ' ')))
281 yaz_log(YLOG_WARN, "Syntax error in request (1)");
285 if (!(p = strchr(buf, ' ')))
287 yaz_log(YLOG_WARN, "Syntax error in request (2)");
291 if ((p2 = strchr(buf, '?'))) // Do we have arguments?
293 r->path = nmem_strdup(c->nmem, buf);
296 r->search = nmem_strdup(c->nmem, p2);
300 struct http_argument *a;
301 char *equal = strchr(p2, '=');
302 char *eoa = strchr(p2, '&');
305 yaz_log(YLOG_WARN, "Expected '=' in argument");
309 eoa = equal + strlen(equal); // last argument
312 a = nmem_malloc(c->nmem, sizeof(struct http_argument));
314 a->name = nmem_strdup(c->nmem, p2);
315 urldecode(equal, equal);
316 a->value = nmem_strdup(c->nmem, equal);
317 a->next = r->arguments;
324 if (strncmp(buf, "HTTP/", 5))
325 strcpy(r->http_version, "1.0");
329 if (!(p = strstr(buf, "\r\n")))
333 strcpy(r->http_version, buf);
336 strcpy(c->version, r->http_version);
341 if (!(p = strstr(buf, "\r\n")))
347 struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
348 if (!(p2 = strchr(buf, ':')))
351 h->name = nmem_strdup(c->nmem, buf);
354 if (p2 >= p) // Empty header?
360 h->value = nmem_strdup(c->nmem, p2);
361 h->next = r->headers;
371 static struct http_buf *http_serialize_response(struct http_channel *c,
372 struct http_response *r)
374 wrbuf_rewind(c->wrbuf);
375 struct http_header *h;
377 wrbuf_printf(c->wrbuf, "HTTP/1.1 %s %s\r\n", r->code, r->msg);
378 for (h = r->headers; h; h = h->next)
379 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
380 wrbuf_printf(c->wrbuf, "Content-length: %d\r\n", r->payload ? (int) strlen(r->payload) : 0);
381 wrbuf_printf(c->wrbuf, "Content-type: text/xml\r\n");
382 wrbuf_puts(c->wrbuf, "\r\n");
385 wrbuf_puts(c->wrbuf, r->payload);
387 return http_buf_bywrbuf(c->wrbuf);
390 // Serialize a HTTP request
391 static struct http_buf *http_serialize_request(struct http_request *r)
393 struct http_channel *c = r->channel;
394 wrbuf_rewind(c->wrbuf);
395 struct http_header *h;
396 struct http_argument *a;
398 wrbuf_printf(c->wrbuf, "%s %s", r->method, r->path);
402 wrbuf_putc(c->wrbuf, '?');
403 for (a = r->arguments; a; a = a->next) {
404 if (a != r->arguments)
405 wrbuf_putc(c->wrbuf, '&');
406 wrbuf_printf(c->wrbuf, "%s=%s", a->name, a->value);
410 wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
412 for (h = r->headers; h; h = h->next)
413 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
415 wrbuf_puts(c->wrbuf, "\r\n");
417 return http_buf_bywrbuf(c->wrbuf);
421 static int http_weshouldproxy(struct http_request *rq)
423 if (proxy_addr && !strstr(rq->path, "search.pz2"))
428 static int http_proxy(struct http_request *rq)
430 struct http_channel *c = rq->channel;
431 struct http_proxy *p = c->proxy;
432 struct http_header *hp;
433 struct http_buf *requestbuf;
435 if (!p) // This is a new connection. Create a proxy channel
442 if (!(pe = getprotobyname("tcp"))) {
445 if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
447 yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
450 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
451 &one, sizeof(one)) < 0)
453 if ((flags = fcntl(sock, F_GETFL, 0)) < 0)
454 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
455 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
456 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
457 if (connect(sock, (struct sockaddr *) proxy_addr, sizeof(*proxy_addr)) < 0)
458 if (errno != EINPROGRESS)
460 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
464 p = xmalloc(sizeof(struct http_proxy));
468 // We will add EVENT_OUTPUT below
469 p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
470 iochan_setdata(p->iochan, p);
471 p->iochan->next = channel_list;
472 channel_list = p->iochan;
475 // Modify Host: header
476 for (hp = rq->headers; hp; hp = hp->next)
477 if (!strcmp(hp->name, "Host"))
481 yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
484 hp->value = nmem_strdup(c->nmem, proxy_url);
485 requestbuf = http_serialize_request(rq);
486 http_buf_enqueue(&p->oqueue, requestbuf);
487 iochan_setflag(p->iochan, EVENT_OUTPUT);
491 void http_send_response(struct http_channel *ch)
493 struct http_response *rs = ch->response;
495 struct http_buf *hb = http_serialize_response(ch, rs);
498 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
499 http_destroy(ch->iochan);
503 http_buf_enqueue(&ch->oqueue, hb);
504 iochan_setflag(ch->iochan, EVENT_OUTPUT);
505 ch->state = Http_Idle;
509 static void http_io(IOCHAN i, int event)
511 struct http_channel *hc = iochan_getdata(i);
516 struct http_buf *htbuf;
519 htbuf = http_buf_create();
520 res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
521 if (res == -1 && errno == EAGAIN)
523 http_buf_destroy(htbuf);
528 http_buf_destroy(htbuf);
534 htbuf->buf[res] = '\0';
536 http_buf_enqueue(&hc->iqueue, htbuf);
539 if (hc->state == Http_Busy)
541 if ((reqlen = request_check(hc->iqueue)) <= 2)
544 nmem_reset(hc->nmem);
545 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
547 yaz_log(YLOG_WARN, "Failed to parse request");
552 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
554 *hc->request->search ? "?" : "",
555 hc->request->search);
556 if (http_weshouldproxy(hc->request))
557 http_proxy(hc->request);
560 // Execute our business logic!
561 hc->state = Http_Busy;
566 yaz_log(YLOG_DEBUG, "We think we have more input to read. Forcing event");
567 iochan_setevent(i, EVENT_INPUT);
575 struct http_buf *wb = hc->oqueue;
576 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
579 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
585 hc->oqueue = hc->oqueue->next;
586 http_buf_destroy(wb);
594 if (!strcmp(hc->version, "1.0"))
601 iochan_clearflag(i, EVENT_OUTPUT);
603 iochan_setevent(hc->iochan, EVENT_INPUT);
608 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
609 http_destroy(i); // Server closed; we're done
612 yaz_log(YLOG_WARN, "Unexpected event on connection");
617 // Handles I/O on a client connection to a backend web server (proxy mode)
618 static void proxy_io(IOCHAN pi, int event)
620 struct http_proxy *pc = iochan_getdata(pi);
621 struct http_channel *hc = pc->channel;
626 struct http_buf *htbuf;
629 htbuf = http_buf_create();
630 res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
631 if (res == 0 || (res < 0 && errno != EINPROGRESS))
635 yaz_log(YLOG_WARN, "Proxy read came up short");
636 // Close channel and alert client HTTP channel that we're gone
637 http_buf_destroy(htbuf);
638 close(iochan_getfd(pi));
644 http_destroy(hc->iochan);
650 htbuf->buf[res] = '\0';
652 http_buf_enqueue(&hc->oqueue, htbuf);
654 iochan_setflag(hc->iochan, EVENT_OUTPUT);
657 if (!(htbuf = pc->oqueue))
659 iochan_clearflag(pi, EVENT_OUTPUT);
662 res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
665 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
666 http_destroy(hc->iochan);
669 if (res == htbuf->len)
671 struct http_buf *np = htbuf->next;
672 http_buf_destroy(htbuf);
678 htbuf->offset += res;
682 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
686 yaz_log(YLOG_WARN, "Unexpected event on connection");
687 http_destroy(hc->iochan);
692 static void http_destroy(IOCHAN i)
694 struct http_channel *s = iochan_getdata(i);
698 if (s->proxy->iochan)
700 close(iochan_getfd(s->proxy->iochan));
701 iochan_destroy(s->proxy->iochan);
703 http_buf_destroy_queue(s->proxy->oqueue);
706 s->next = http_channel_freelist;
707 http_channel_freelist = s;
708 close(iochan_getfd(i));
712 static struct http_channel *http_create(void)
714 struct http_channel *r = http_channel_freelist;
718 http_channel_freelist = r->next;
720 wrbuf_rewind(r->wrbuf);
724 r = xmalloc(sizeof(struct http_channel));
725 r->nmem = nmem_create();
726 r->wrbuf = wrbuf_alloc();
730 r->iqueue = r->oqueue = 0;
731 r->state = Http_Idle;
738 /* Accept a new command connection */
739 static void http_accept(IOCHAN i, int event)
741 struct sockaddr_in addr;
742 int fd = iochan_getfd(i);
747 struct http_channel *ch;
750 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
752 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
755 if ((flags = fcntl(s, F_GETFL, 0)) < 0)
756 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
757 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
758 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
760 yaz_log(YLOG_DEBUG, "New command connection");
761 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
765 iochan_setdata(c, ch);
767 c->next = channel_list;
771 /* Create a http-channel listener, syntax [host:]port */
772 void http_init(const char *addr)
777 struct sockaddr_in myaddr;
782 yaz_log(YLOG_LOG, "HTTP listener is %s", addr);
784 bzero(&myaddr, sizeof myaddr);
785 myaddr.sin_family = AF_INET;
786 pp = strchr(addr, ':');
793 strncpy(hostname, addr, len);
794 hostname[len] = '\0';
795 if (!(he = gethostbyname(hostname)))
797 yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
800 memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
806 myaddr.sin_addr.s_addr = INADDR_ANY;
808 myaddr.sin_port = htons(port);
810 if (!(p = getprotobyname("tcp"))) {
813 if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
814 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
815 if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
816 &one, sizeof(one)) < 0)
819 if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0)
820 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
821 if (listen(l, SOMAXCONN) < 0)
822 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
824 c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
825 c->next = channel_list;
829 void http_set_proxyaddr(char *host)
835 strcpy(proxy_url, host);
836 p = strchr(host, ':');
837 yaz_log(YLOG_DEBUG, "Proxying for %s", host);
844 if (!(he = gethostbyname(host)))
846 fprintf(stderr, "Failed to lookup '%s'\n", host);
849 proxy_addr = xmalloc(sizeof(struct sockaddr_in));
850 proxy_addr->sin_family = he->h_addrtype;
851 memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
852 proxy_addr->sin_port = htons(port);
858 * indent-tabs-mode: nil
860 * vim: shiftwidth=4 tabstop=8 expandtab