2 * $Id: http.c,v 1.4 2006-12-21 04:27:17 quinn Exp $
6 #include <sys/socket.h>
18 #include <yaz/yaz-util.h>
19 #include <yaz/comstack.h>
27 #include "http_command.h"
29 static void proxy_io(IOCHAN i, int event);
30 static struct http_channel *http_create(void);
31 static void http_destroy(IOCHAN i);
33 extern IOCHAN channel_list;
35 static struct sockaddr_in *proxy_addr = 0; // If this is set, we proxy normal HTTP requests
36 static char proxy_url[256] = "";
37 static struct http_buf *http_buf_freelist = 0;
38 static struct http_channel *http_channel_freelist = 0;
40 static struct http_buf *http_buf_create()
44 if (http_buf_freelist)
46 r = http_buf_freelist;
47 http_buf_freelist = http_buf_freelist->next;
50 r = xmalloc(sizeof(struct http_buf));
57 static void http_buf_destroy(struct http_buf *b)
59 b->next = http_buf_freelist;
60 http_buf_freelist = b;
63 static void http_buf_destroy_queue(struct http_buf *b)
75 // Calculate length of chain
76 static int http_buf_len(struct http_buf *b)
79 for (; b; b = b->next)
85 static struct http_buf *http_buf_bybuf(char *b, int len)
87 struct http_buf *res = 0;
88 struct http_buf **p = &res;
92 *p = http_buf_create();
94 if (tocopy > HTTP_BUF_SIZE)
95 tocopy = HTTP_BUF_SIZE;
96 memcpy((*p)->buf, b, tocopy);
105 // Add a (chain of) buffers to the end of an existing queue.
106 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
109 queue = &(*queue)->next;
113 static struct http_buf *http_buf_bywrbuf(WRBUF wrbuf)
115 // Heavens to Betsy (buf)!
116 return http_buf_bybuf(wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
119 // Non-destructively collapse chain of buffers into a string (max *len)
121 static int http_buf_peek(struct http_buf *b, char *buf, int len)
124 while (b && rd < len)
126 int toread = len - rd;
129 memcpy(buf + rd, b->buf + b->offset, toread);
137 // Ddestructively munch up to len from head of queue.
138 static int http_buf_read(struct http_buf **b, char *buf, int len)
141 while ((*b) && rd < len)
143 int toread = len - rd;
144 if (toread > (*b)->len)
146 memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
148 if (toread < (*b)->len)
151 (*b)->offset += toread;
156 struct http_buf *n = (*b)->next;
157 http_buf_destroy(*b);
165 void static urldecode(char *i, char *o)
177 sscanf(i, "%2hhx", o);
187 void http_addheader(struct http_response *r, const char *name, const char *value)
189 struct http_channel *c = r->channel;
190 struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
191 h->name = nmem_strdup(c->nmem, name);
192 h->value = nmem_strdup(c->nmem, value);
193 h->next = r->headers;
197 char *http_argbyname(struct http_request *r, char *name)
199 struct http_argument *p;
202 for (p = r->arguments; p; p = p->next)
203 if (!strcmp(p->name, name))
208 char *http_headerbyname(struct http_request *r, char *name)
210 struct http_header *p;
211 for (p = r->headers; p; p = p->next)
212 if (!strcmp(p->name, name))
217 struct http_response *http_create_response(struct http_channel *c)
219 struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
220 strcpy(r->code, "200");
228 // Check if we have a complete request. Return 0 or length (including trailing newline)
229 // FIXME: Does not deal gracefully with requests carrying payload
230 // but this is kind of OK since we will reject anything other than an empty GET
231 static int request_check(struct http_buf *queue)
237 http_buf_peek(queue, tmp, 4096);
238 while (*buf) // Check if we have a sequence of lines terminated by an empty line
240 char *b = strstr(buf, "\r\n");
245 len += (b - buf) + 2;
253 struct http_request *http_parse_request(struct http_channel *c, struct http_buf **queue,
256 struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
263 if (http_buf_read(queue, buf, len) < len)
271 for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
275 yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
280 if (!(buf = strchr(buf, ' ')))
282 yaz_log(YLOG_WARN, "Syntax error in request (1)");
286 if (!(p = strchr(buf, ' ')))
288 yaz_log(YLOG_WARN, "Syntax error in request (2)");
292 if ((p2 = strchr(buf, '?'))) // Do we have arguments?
294 r->path = nmem_strdup(c->nmem, buf);
297 r->search = nmem_strdup(c->nmem, p2);
301 struct http_argument *a;
302 char *equal = strchr(p2, '=');
303 char *eoa = strchr(p2, '&');
306 yaz_log(YLOG_WARN, "Expected '=' in argument");
310 eoa = equal + strlen(equal); // last argument
313 a = nmem_malloc(c->nmem, sizeof(struct http_argument));
315 a->name = nmem_strdup(c->nmem, p2);
316 urldecode(equal, equal);
317 a->value = nmem_strdup(c->nmem, equal);
318 a->next = r->arguments;
325 if (strncmp(buf, "HTTP/", 5))
326 strcpy(r->http_version, "1.0");
330 if (!(p = strstr(buf, "\r\n")))
334 strcpy(r->http_version, buf);
337 strcpy(c->version, r->http_version);
342 if (!(p = strstr(buf, "\r\n")))
348 struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
349 if (!(p2 = strchr(buf, ':')))
352 h->name = nmem_strdup(c->nmem, buf);
355 if (p2 >= p) // Empty header?
361 h->value = nmem_strdup(c->nmem, p2);
362 h->next = r->headers;
372 static struct http_buf *http_serialize_response(struct http_channel *c,
373 struct http_response *r)
375 wrbuf_rewind(c->wrbuf);
376 struct http_header *h;
378 wrbuf_printf(c->wrbuf, "HTTP/1.1 %s %s\r\n", r->code, r->msg);
379 for (h = r->headers; h; h = h->next)
380 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
381 wrbuf_printf(c->wrbuf, "Content-length: %d\r\n", r->payload ? (int) strlen(r->payload) : 0);
382 wrbuf_printf(c->wrbuf, "Content-type: text/xml\r\n");
383 wrbuf_puts(c->wrbuf, "\r\n");
386 wrbuf_puts(c->wrbuf, r->payload);
388 return http_buf_bywrbuf(c->wrbuf);
391 // Serialize a HTTP request
392 static struct http_buf *http_serialize_request(struct http_request *r)
394 struct http_channel *c = r->channel;
395 wrbuf_rewind(c->wrbuf);
396 struct http_header *h;
397 struct http_argument *a;
399 wrbuf_printf(c->wrbuf, "%s %s", r->method, r->path);
403 wrbuf_putc(c->wrbuf, '?');
404 for (a = r->arguments; a; a = a->next) {
405 if (a != r->arguments)
406 wrbuf_putc(c->wrbuf, '&');
407 wrbuf_printf(c->wrbuf, "%s=%s", a->name, a->value);
411 wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
413 for (h = r->headers; h; h = h->next)
414 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
416 wrbuf_puts(c->wrbuf, "\r\n");
418 return http_buf_bywrbuf(c->wrbuf);
422 static int http_weshouldproxy(struct http_request *rq)
424 if (proxy_addr && !strstr(rq->path, "search.pz2"))
429 static int http_proxy(struct http_request *rq)
431 struct http_channel *c = rq->channel;
432 struct http_proxy *p = c->proxy;
433 struct http_header *hp;
434 struct http_buf *requestbuf;
436 if (!p) // This is a new connection. Create a proxy channel
443 if (!(pe = getprotobyname("tcp"))) {
446 if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
448 yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
451 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
452 &one, sizeof(one)) < 0)
454 if ((flags = fcntl(sock, F_GETFL, 0)) < 0)
455 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
456 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
457 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
458 if (connect(sock, (struct sockaddr *) proxy_addr, sizeof(*proxy_addr)) < 0)
459 if (errno != EINPROGRESS)
461 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
465 p = xmalloc(sizeof(struct http_proxy));
469 // We will add EVENT_OUTPUT below
470 p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
471 iochan_setdata(p->iochan, p);
472 p->iochan->next = channel_list;
473 channel_list = p->iochan;
476 // Modify Host: header
477 for (hp = rq->headers; hp; hp = hp->next)
478 if (!strcmp(hp->name, "Host"))
482 yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
485 hp->value = nmem_strdup(c->nmem, proxy_url);
486 requestbuf = http_serialize_request(rq);
487 http_buf_enqueue(&p->oqueue, requestbuf);
488 iochan_setflag(p->iochan, EVENT_OUTPUT);
492 void http_send_response(struct http_channel *ch)
494 struct http_response *rs = ch->response;
496 struct http_buf *hb = http_serialize_response(ch, rs);
499 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
500 http_destroy(ch->iochan);
504 http_buf_enqueue(&ch->oqueue, hb);
505 iochan_setflag(ch->iochan, EVENT_OUTPUT);
506 ch->state = Http_Idle;
510 static void http_io(IOCHAN i, int event)
512 struct http_channel *hc = iochan_getdata(i);
517 struct http_buf *htbuf;
520 htbuf = http_buf_create();
521 res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
522 if (res == -1 && errno == EAGAIN)
524 http_buf_destroy(htbuf);
529 http_buf_destroy(htbuf);
535 htbuf->buf[res] = '\0';
537 http_buf_enqueue(&hc->iqueue, htbuf);
540 if (hc->state == Http_Busy)
542 if ((reqlen = request_check(hc->iqueue)) <= 2)
545 nmem_reset(hc->nmem);
546 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
548 yaz_log(YLOG_WARN, "Failed to parse request");
553 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
555 *hc->request->search ? "?" : "",
556 hc->request->search);
557 if (http_weshouldproxy(hc->request))
558 http_proxy(hc->request);
561 // Execute our business logic!
562 hc->state = Http_Busy;
567 yaz_log(YLOG_DEBUG, "We think we have more input to read. Forcing event");
568 iochan_setevent(i, EVENT_INPUT);
576 struct http_buf *wb = hc->oqueue;
577 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
580 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
586 hc->oqueue = hc->oqueue->next;
587 http_buf_destroy(wb);
595 if (!strcmp(hc->version, "1.0"))
602 iochan_clearflag(i, EVENT_OUTPUT);
604 iochan_setevent(hc->iochan, EVENT_INPUT);
609 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
610 http_destroy(i); // Server closed; we're done
613 yaz_log(YLOG_WARN, "Unexpected event on connection");
618 // Handles I/O on a client connection to a backend web server (proxy mode)
619 static void proxy_io(IOCHAN pi, int event)
621 struct http_proxy *pc = iochan_getdata(pi);
622 struct http_channel *hc = pc->channel;
627 struct http_buf *htbuf;
630 htbuf = http_buf_create();
631 res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
632 if (res == 0 || (res < 0 && errno != EINPROGRESS))
636 yaz_log(YLOG_WARN, "Proxy read came up short");
637 // Close channel and alert client HTTP channel that we're gone
638 http_buf_destroy(htbuf);
639 close(iochan_getfd(pi));
645 http_destroy(hc->iochan);
651 htbuf->buf[res] = '\0';
653 http_buf_enqueue(&hc->oqueue, htbuf);
655 iochan_setflag(hc->iochan, EVENT_OUTPUT);
658 if (!(htbuf = pc->oqueue))
660 iochan_clearflag(pi, EVENT_OUTPUT);
663 res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
666 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
667 http_destroy(hc->iochan);
670 if (res == htbuf->len)
672 struct http_buf *np = htbuf->next;
673 http_buf_destroy(htbuf);
679 htbuf->offset += res;
683 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
687 yaz_log(YLOG_WARN, "Unexpected event on connection");
688 http_destroy(hc->iochan);
693 static void http_destroy(IOCHAN i)
695 struct http_channel *s = iochan_getdata(i);
699 if (s->proxy->iochan)
701 close(iochan_getfd(s->proxy->iochan));
702 iochan_destroy(s->proxy->iochan);
704 http_buf_destroy_queue(s->proxy->oqueue);
707 s->next = http_channel_freelist;
708 http_channel_freelist = s;
709 close(iochan_getfd(i));
713 static struct http_channel *http_create(void)
715 struct http_channel *r = http_channel_freelist;
719 http_channel_freelist = r->next;
721 wrbuf_rewind(r->wrbuf);
725 r = xmalloc(sizeof(struct http_channel));
726 r->nmem = nmem_create();
727 r->wrbuf = wrbuf_alloc();
731 r->iqueue = r->oqueue = 0;
732 r->state = Http_Idle;
739 /* Accept a new command connection */
740 static void http_accept(IOCHAN i, int event)
742 struct sockaddr_in addr;
743 int fd = iochan_getfd(i);
748 struct http_channel *ch;
751 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
753 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
756 if ((flags = fcntl(s, F_GETFL, 0)) < 0)
757 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
758 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
759 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
761 yaz_log(YLOG_DEBUG, "New command connection");
762 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
766 iochan_setdata(c, ch);
768 c->next = channel_list;
772 /* Create a http-channel listener, syntax [host:]port */
773 void http_init(const char *addr)
778 struct sockaddr_in myaddr;
783 yaz_log(YLOG_LOG, "HTTP listener is %s", addr);
785 bzero(&myaddr, sizeof myaddr);
786 myaddr.sin_family = AF_INET;
787 pp = strchr(addr, ':');
794 strncpy(hostname, addr, len);
795 hostname[len] = '\0';
796 if (!(he = gethostbyname(hostname)))
798 yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
801 memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
807 myaddr.sin_addr.s_addr = INADDR_ANY;
809 myaddr.sin_port = htons(port);
811 if (!(p = getprotobyname("tcp"))) {
814 if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
815 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
816 if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
817 &one, sizeof(one)) < 0)
820 if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0)
821 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
822 if (listen(l, SOMAXCONN) < 0)
823 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
825 c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
826 c->next = channel_list;
830 void http_set_proxyaddr(char *host)
836 strcpy(proxy_url, host);
837 p = strchr(host, ':');
838 yaz_log(YLOG_DEBUG, "Proxying for %s", host);
845 if (!(he = gethostbyname(host)))
847 fprintf(stderr, "Failed to lookup '%s'\n", host);
850 proxy_addr = xmalloc(sizeof(struct sockaddr_in));
851 proxy_addr->sin_family = he->h_addrtype;
852 memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
853 proxy_addr->sin_port = htons(port);
859 * indent-tabs-mode: nil
861 * vim: shiftwidth=4 tabstop=8 expandtab