2 * $Id: http.c,v 1.6 2007-01-08 12:43:41 adam Exp $
6 #include <sys/socket.h>
22 #include <yaz/yaz-util.h>
23 #include <yaz/comstack.h>
30 #include "http_command.h"
32 static void proxy_io(IOCHAN i, int event);
33 static struct http_channel *http_create(void);
34 static void http_destroy(IOCHAN i);
36 extern IOCHAN channel_list;
38 static struct sockaddr_in *proxy_addr = 0; // If this is set, we proxy normal HTTP requests
39 static char proxy_url[256] = "";
40 static struct http_buf *http_buf_freelist = 0;
41 static struct http_channel *http_channel_freelist = 0;
43 static struct http_buf *http_buf_create()
47 if (http_buf_freelist)
49 r = http_buf_freelist;
50 http_buf_freelist = http_buf_freelist->next;
53 r = xmalloc(sizeof(struct http_buf));
60 static void http_buf_destroy(struct http_buf *b)
62 b->next = http_buf_freelist;
63 http_buf_freelist = b;
66 static void http_buf_destroy_queue(struct http_buf *b)
78 // Calculate length of chain
79 static int http_buf_len(struct http_buf *b)
82 for (; b; b = b->next)
88 static struct http_buf *http_buf_bybuf(char *b, int len)
90 struct http_buf *res = 0;
91 struct http_buf **p = &res;
95 *p = http_buf_create();
97 if (tocopy > HTTP_BUF_SIZE)
98 tocopy = HTTP_BUF_SIZE;
99 memcpy((*p)->buf, b, tocopy);
108 // Add a (chain of) buffers to the end of an existing queue.
109 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
112 queue = &(*queue)->next;
116 static struct http_buf *http_buf_bywrbuf(WRBUF wrbuf)
118 // Heavens to Betsy (buf)!
119 return http_buf_bybuf(wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
122 // Non-destructively collapse chain of buffers into a string (max *len)
124 static int http_buf_peek(struct http_buf *b, char *buf, int len)
127 while (b && rd < len)
129 int toread = len - rd;
132 memcpy(buf + rd, b->buf + b->offset, toread);
140 // Ddestructively munch up to len from head of queue.
141 static int http_buf_read(struct http_buf **b, char *buf, int len)
144 while ((*b) && rd < len)
146 int toread = len - rd;
147 if (toread > (*b)->len)
149 memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
151 if (toread < (*b)->len)
154 (*b)->offset += toread;
159 struct http_buf *n = (*b)->next;
160 http_buf_destroy(*b);
168 void static urldecode(char *i, char *o)
180 sscanf(i, "%2hhx", o);
190 void http_addheader(struct http_response *r, const char *name, const char *value)
192 struct http_channel *c = r->channel;
193 struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
194 h->name = nmem_strdup(c->nmem, name);
195 h->value = nmem_strdup(c->nmem, value);
196 h->next = r->headers;
200 char *http_argbyname(struct http_request *r, char *name)
202 struct http_argument *p;
205 for (p = r->arguments; p; p = p->next)
206 if (!strcmp(p->name, name))
211 char *http_headerbyname(struct http_request *r, char *name)
213 struct http_header *p;
214 for (p = r->headers; p; p = p->next)
215 if (!strcmp(p->name, name))
220 struct http_response *http_create_response(struct http_channel *c)
222 struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
223 strcpy(r->code, "200");
231 // Check if we have a complete request. Return 0 or length (including trailing newline)
232 // FIXME: Does not deal gracefully with requests carrying payload
233 // but this is kind of OK since we will reject anything other than an empty GET
234 static int request_check(struct http_buf *queue)
240 http_buf_peek(queue, tmp, 4096);
241 while (*buf) // Check if we have a sequence of lines terminated by an empty line
243 char *b = strstr(buf, "\r\n");
248 len += (b - buf) + 2;
256 struct http_request *http_parse_request(struct http_channel *c, struct http_buf **queue,
259 struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
266 if (http_buf_read(queue, buf, len) < len)
274 for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
278 yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
283 if (!(buf = strchr(buf, ' ')))
285 yaz_log(YLOG_WARN, "Syntax error in request (1)");
289 if (!(p = strchr(buf, ' ')))
291 yaz_log(YLOG_WARN, "Syntax error in request (2)");
295 if ((p2 = strchr(buf, '?'))) // Do we have arguments?
297 r->path = nmem_strdup(c->nmem, buf);
300 r->search = nmem_strdup(c->nmem, p2);
304 struct http_argument *a;
305 char *equal = strchr(p2, '=');
306 char *eoa = strchr(p2, '&');
309 yaz_log(YLOG_WARN, "Expected '=' in argument");
313 eoa = equal + strlen(equal); // last argument
316 a = nmem_malloc(c->nmem, sizeof(struct http_argument));
318 a->name = nmem_strdup(c->nmem, p2);
319 urldecode(equal, equal);
320 a->value = nmem_strdup(c->nmem, equal);
321 a->next = r->arguments;
328 if (strncmp(buf, "HTTP/", 5))
329 strcpy(r->http_version, "1.0");
333 if (!(p = strstr(buf, "\r\n")))
337 strcpy(r->http_version, buf);
340 strcpy(c->version, r->http_version);
345 if (!(p = strstr(buf, "\r\n")))
351 struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
352 if (!(p2 = strchr(buf, ':')))
355 h->name = nmem_strdup(c->nmem, buf);
358 if (p2 >= p) // Empty header?
364 h->value = nmem_strdup(c->nmem, p2);
365 h->next = r->headers;
375 static struct http_buf *http_serialize_response(struct http_channel *c,
376 struct http_response *r)
378 wrbuf_rewind(c->wrbuf);
379 struct http_header *h;
381 wrbuf_printf(c->wrbuf, "HTTP/1.1 %s %s\r\n", r->code, r->msg);
382 for (h = r->headers; h; h = h->next)
383 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
384 wrbuf_printf(c->wrbuf, "Content-length: %d\r\n", r->payload ? (int) strlen(r->payload) : 0);
385 wrbuf_printf(c->wrbuf, "Content-type: text/xml\r\n");
386 wrbuf_puts(c->wrbuf, "\r\n");
389 wrbuf_puts(c->wrbuf, r->payload);
391 return http_buf_bywrbuf(c->wrbuf);
394 // Serialize a HTTP request
395 static struct http_buf *http_serialize_request(struct http_request *r)
397 struct http_channel *c = r->channel;
398 wrbuf_rewind(c->wrbuf);
399 struct http_header *h;
400 struct http_argument *a;
402 wrbuf_printf(c->wrbuf, "%s %s", r->method, r->path);
406 wrbuf_putc(c->wrbuf, '?');
407 for (a = r->arguments; a; a = a->next) {
408 if (a != r->arguments)
409 wrbuf_putc(c->wrbuf, '&');
410 wrbuf_printf(c->wrbuf, "%s=%s", a->name, a->value);
414 wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
416 for (h = r->headers; h; h = h->next)
417 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
419 wrbuf_puts(c->wrbuf, "\r\n");
421 return http_buf_bywrbuf(c->wrbuf);
425 static int http_weshouldproxy(struct http_request *rq)
427 if (proxy_addr && !strstr(rq->path, "search.pz2"))
432 static int http_proxy(struct http_request *rq)
434 struct http_channel *c = rq->channel;
435 struct http_proxy *p = c->proxy;
436 struct http_header *hp;
437 struct http_buf *requestbuf;
439 if (!p) // This is a new connection. Create a proxy channel
446 if (!(pe = getprotobyname("tcp"))) {
449 if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
451 yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
454 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
455 &one, sizeof(one)) < 0)
457 if ((flags = fcntl(sock, F_GETFL, 0)) < 0)
458 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
459 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
460 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
461 if (connect(sock, (struct sockaddr *) proxy_addr, sizeof(*proxy_addr)) < 0)
462 if (errno != EINPROGRESS)
464 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
468 p = xmalloc(sizeof(struct http_proxy));
472 // We will add EVENT_OUTPUT below
473 p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
474 iochan_setdata(p->iochan, p);
475 p->iochan->next = channel_list;
476 channel_list = p->iochan;
479 // Modify Host: header
480 for (hp = rq->headers; hp; hp = hp->next)
481 if (!strcmp(hp->name, "Host"))
485 yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
488 hp->value = nmem_strdup(c->nmem, proxy_url);
489 requestbuf = http_serialize_request(rq);
490 http_buf_enqueue(&p->oqueue, requestbuf);
491 iochan_setflag(p->iochan, EVENT_OUTPUT);
495 void http_send_response(struct http_channel *ch)
497 struct http_response *rs = ch->response;
499 struct http_buf *hb = http_serialize_response(ch, rs);
502 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
503 http_destroy(ch->iochan);
507 http_buf_enqueue(&ch->oqueue, hb);
508 iochan_setflag(ch->iochan, EVENT_OUTPUT);
509 ch->state = Http_Idle;
513 static void http_io(IOCHAN i, int event)
515 struct http_channel *hc = iochan_getdata(i);
520 struct http_buf *htbuf;
523 htbuf = http_buf_create();
524 res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
525 if (res == -1 && errno == EAGAIN)
527 http_buf_destroy(htbuf);
532 http_buf_destroy(htbuf);
538 htbuf->buf[res] = '\0';
540 http_buf_enqueue(&hc->iqueue, htbuf);
543 if (hc->state == Http_Busy)
545 if ((reqlen = request_check(hc->iqueue)) <= 2)
548 nmem_reset(hc->nmem);
549 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
551 yaz_log(YLOG_WARN, "Failed to parse request");
556 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
558 *hc->request->search ? "?" : "",
559 hc->request->search);
560 if (http_weshouldproxy(hc->request))
561 http_proxy(hc->request);
564 // Execute our business logic!
565 hc->state = Http_Busy;
570 yaz_log(YLOG_DEBUG, "We think we have more input to read. Forcing event");
571 iochan_setevent(i, EVENT_INPUT);
579 struct http_buf *wb = hc->oqueue;
580 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
583 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
589 hc->oqueue = hc->oqueue->next;
590 http_buf_destroy(wb);
598 if (!strcmp(hc->version, "1.0"))
605 iochan_clearflag(i, EVENT_OUTPUT);
607 iochan_setevent(hc->iochan, EVENT_INPUT);
612 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
613 http_destroy(i); // Server closed; we're done
616 yaz_log(YLOG_WARN, "Unexpected event on connection");
621 // Handles I/O on a client connection to a backend web server (proxy mode)
622 static void proxy_io(IOCHAN pi, int event)
624 struct http_proxy *pc = iochan_getdata(pi);
625 struct http_channel *hc = pc->channel;
630 struct http_buf *htbuf;
633 htbuf = http_buf_create();
634 res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
635 if (res == 0 || (res < 0 && errno != EINPROGRESS))
639 yaz_log(YLOG_WARN, "Proxy read came up short");
640 // Close channel and alert client HTTP channel that we're gone
641 http_buf_destroy(htbuf);
642 close(iochan_getfd(pi));
648 http_destroy(hc->iochan);
654 htbuf->buf[res] = '\0';
656 http_buf_enqueue(&hc->oqueue, htbuf);
658 iochan_setflag(hc->iochan, EVENT_OUTPUT);
661 if (!(htbuf = pc->oqueue))
663 iochan_clearflag(pi, EVENT_OUTPUT);
666 res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
669 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
670 http_destroy(hc->iochan);
673 if (res == htbuf->len)
675 struct http_buf *np = htbuf->next;
676 http_buf_destroy(htbuf);
682 htbuf->offset += res;
686 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
690 yaz_log(YLOG_WARN, "Unexpected event on connection");
691 http_destroy(hc->iochan);
696 static void http_destroy(IOCHAN i)
698 struct http_channel *s = iochan_getdata(i);
702 if (s->proxy->iochan)
704 close(iochan_getfd(s->proxy->iochan));
705 iochan_destroy(s->proxy->iochan);
707 http_buf_destroy_queue(s->proxy->oqueue);
710 s->next = http_channel_freelist;
711 http_channel_freelist = s;
712 close(iochan_getfd(i));
716 static struct http_channel *http_create(void)
718 struct http_channel *r = http_channel_freelist;
722 http_channel_freelist = r->next;
724 wrbuf_rewind(r->wrbuf);
728 r = xmalloc(sizeof(struct http_channel));
729 r->nmem = nmem_create();
730 r->wrbuf = wrbuf_alloc();
734 r->iqueue = r->oqueue = 0;
735 r->state = Http_Idle;
742 /* Accept a new command connection */
743 static void http_accept(IOCHAN i, int event)
745 struct sockaddr_in addr;
746 int fd = iochan_getfd(i);
751 struct http_channel *ch;
754 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
756 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
759 if ((flags = fcntl(s, F_GETFL, 0)) < 0)
760 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
761 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
762 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
764 yaz_log(YLOG_DEBUG, "New command connection");
765 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
769 iochan_setdata(c, ch);
771 c->next = channel_list;
775 /* Create a http-channel listener, syntax [host:]port */
776 void http_init(const char *addr)
781 struct sockaddr_in myaddr;
786 yaz_log(YLOG_LOG, "HTTP listener is %s", addr);
788 bzero(&myaddr, sizeof myaddr);
789 myaddr.sin_family = AF_INET;
790 pp = strchr(addr, ':');
797 strncpy(hostname, addr, len);
798 hostname[len] = '\0';
799 if (!(he = gethostbyname(hostname)))
801 yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
804 memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
810 myaddr.sin_addr.s_addr = INADDR_ANY;
812 myaddr.sin_port = htons(port);
814 if (!(p = getprotobyname("tcp"))) {
817 if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
818 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
819 if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
820 &one, sizeof(one)) < 0)
823 if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0)
824 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
825 if (listen(l, SOMAXCONN) < 0)
826 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
828 c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
829 c->next = channel_list;
833 void http_set_proxyaddr(char *host)
839 strcpy(proxy_url, host);
840 p = strchr(host, ':');
841 yaz_log(YLOG_DEBUG, "Proxying for %s", host);
848 if (!(he = gethostbyname(host)))
850 fprintf(stderr, "Failed to lookup '%s'\n", host);
853 proxy_addr = xmalloc(sizeof(struct sockaddr_in));
854 proxy_addr->sin_family = he->h_addrtype;
855 memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
856 proxy_addr->sin_port = htons(port);
862 * indent-tabs-mode: nil
864 * vim: shiftwidth=4 tabstop=8 expandtab