2 * $Id: http.c,v 1.8 2007-01-10 10:04:23 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;
96 if (tocopy > HTTP_BUF_SIZE)
97 tocopy = HTTP_BUF_SIZE;
98 *p = http_buf_create();
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 struct http_header *h;
380 wrbuf_rewind(c->wrbuf);
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 struct http_header *h;
399 struct http_argument *a;
401 wrbuf_rewind(c->wrbuf);
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;
501 hb = http_serialize_response(ch, rs);
504 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
505 http_destroy(ch->iochan);
509 http_buf_enqueue(&ch->oqueue, hb);
510 iochan_setflag(ch->iochan, EVENT_OUTPUT);
511 ch->state = Http_Idle;
515 static void http_io(IOCHAN i, int event)
517 struct http_channel *hc = iochan_getdata(i);
522 struct http_buf *htbuf;
525 htbuf = http_buf_create();
526 res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
527 if (res == -1 && errno == EAGAIN)
529 http_buf_destroy(htbuf);
534 http_buf_destroy(htbuf);
540 htbuf->buf[res] = '\0';
542 http_buf_enqueue(&hc->iqueue, htbuf);
545 if (hc->state == Http_Busy)
547 if ((reqlen = request_check(hc->iqueue)) <= 2)
550 nmem_reset(hc->nmem);
551 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
553 yaz_log(YLOG_WARN, "Failed to parse request");
558 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
560 *hc->request->search ? "?" : "",
561 hc->request->search);
562 if (http_weshouldproxy(hc->request))
563 http_proxy(hc->request);
566 // Execute our business logic!
567 hc->state = Http_Busy;
572 yaz_log(YLOG_DEBUG, "We think we have more input to read. Forcing event");
573 iochan_setevent(i, EVENT_INPUT);
581 struct http_buf *wb = hc->oqueue;
582 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
585 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
591 hc->oqueue = hc->oqueue->next;
592 http_buf_destroy(wb);
600 if (!strcmp(hc->version, "1.0"))
607 iochan_clearflag(i, EVENT_OUTPUT);
609 iochan_setevent(hc->iochan, EVENT_INPUT);
614 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
615 http_destroy(i); // Server closed; we're done
618 yaz_log(YLOG_WARN, "Unexpected event on connection");
623 // Handles I/O on a client connection to a backend web server (proxy mode)
624 static void proxy_io(IOCHAN pi, int event)
626 struct http_proxy *pc = iochan_getdata(pi);
627 struct http_channel *hc = pc->channel;
632 struct http_buf *htbuf;
635 htbuf = http_buf_create();
636 res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
637 if (res == 0 || (res < 0 && errno != EINPROGRESS))
641 yaz_log(YLOG_WARN, "Proxy read came up short");
642 // Close channel and alert client HTTP channel that we're gone
643 http_buf_destroy(htbuf);
644 close(iochan_getfd(pi));
650 http_destroy(hc->iochan);
656 htbuf->buf[res] = '\0';
658 http_buf_enqueue(&hc->oqueue, htbuf);
660 iochan_setflag(hc->iochan, EVENT_OUTPUT);
663 if (!(htbuf = pc->oqueue))
665 iochan_clearflag(pi, EVENT_OUTPUT);
668 res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
671 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
672 http_destroy(hc->iochan);
675 if (res == htbuf->len)
677 struct http_buf *np = htbuf->next;
678 http_buf_destroy(htbuf);
684 htbuf->offset += res;
688 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
692 yaz_log(YLOG_WARN, "Unexpected event on connection");
693 http_destroy(hc->iochan);
698 static void http_destroy(IOCHAN i)
700 struct http_channel *s = iochan_getdata(i);
704 if (s->proxy->iochan)
706 close(iochan_getfd(s->proxy->iochan));
707 iochan_destroy(s->proxy->iochan);
709 http_buf_destroy_queue(s->proxy->oqueue);
712 s->next = http_channel_freelist;
713 http_channel_freelist = s;
714 close(iochan_getfd(i));
718 static struct http_channel *http_create(void)
720 struct http_channel *r = http_channel_freelist;
724 http_channel_freelist = r->next;
726 wrbuf_rewind(r->wrbuf);
730 r = xmalloc(sizeof(struct http_channel));
731 r->nmem = nmem_create();
732 r->wrbuf = wrbuf_alloc();
736 r->iqueue = r->oqueue = 0;
737 r->state = Http_Idle;
744 /* Accept a new command connection */
745 static void http_accept(IOCHAN i, int event)
747 struct sockaddr_in addr;
748 int fd = iochan_getfd(i);
753 struct http_channel *ch;
756 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
758 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
761 if ((flags = fcntl(s, F_GETFL, 0)) < 0)
762 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
763 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
764 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
766 yaz_log(YLOG_DEBUG, "New command connection");
767 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
771 iochan_setdata(c, ch);
773 c->next = channel_list;
777 /* Create a http-channel listener, syntax [host:]port */
778 void http_init(const char *addr)
783 struct sockaddr_in myaddr;
788 yaz_log(YLOG_LOG, "HTTP listener is %s", addr);
790 memset(&myaddr, 0, sizeof myaddr);
791 myaddr.sin_family = AF_INET;
792 pp = strchr(addr, ':');
799 strncpy(hostname, addr, len);
800 hostname[len] = '\0';
801 if (!(he = gethostbyname(hostname)))
803 yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
806 memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
812 myaddr.sin_addr.s_addr = INADDR_ANY;
814 myaddr.sin_port = htons(port);
816 if (!(p = getprotobyname("tcp"))) {
819 if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
820 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
821 if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
822 &one, sizeof(one)) < 0)
825 if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0)
826 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
827 if (listen(l, SOMAXCONN) < 0)
828 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
830 c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
831 c->next = channel_list;
835 void http_set_proxyaddr(char *host)
841 strcpy(proxy_url, host);
842 p = strchr(host, ':');
843 yaz_log(YLOG_DEBUG, "Proxying for %s", host);
850 if (!(he = gethostbyname(host)))
852 fprintf(stderr, "Failed to lookup '%s'\n", host);
855 proxy_addr = xmalloc(sizeof(struct sockaddr_in));
856 proxy_addr->sin_family = he->h_addrtype;
857 memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
858 proxy_addr->sin_port = htons(port);
864 * indent-tabs-mode: nil
866 * vim: shiftwidth=4 tabstop=8 expandtab