1 /* $Id: http.c,v 1.25 2007-04-11 11:10:05 marc Exp $
2 Copyright (c) 2006-2007, Index Data.
4 This file is part of Pazpar2.
6 Pazpar2 is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 2, or (at your option) any later
11 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 You should have received a copy of the GNU General Public License
17 along with Pazpar2; see the file LICENSE. If not, write to the
18 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
23 #include <sys/socket.h>
24 #include <sys/types.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
44 #include <yaz/yaz-util.h>
45 #include <yaz/comstack.h>
53 #include "http_command.h"
55 static void proxy_io(IOCHAN i, int event);
56 static struct http_channel *http_create(const char *addr);
57 static void http_destroy(IOCHAN i);
59 extern IOCHAN channel_list;
60 extern struct parameters global_parameters;
62 // If this is set, we proxy normal HTTP requests
63 static struct sockaddr_in *proxy_addr = 0;
64 static char proxy_url[256] = "";
65 static char myurl[256] = "";
66 static struct http_buf *http_buf_freelist = 0;
67 static struct http_channel *http_channel_freelist = 0;
69 static struct http_buf *http_buf_create()
73 if (http_buf_freelist)
75 r = http_buf_freelist;
76 http_buf_freelist = http_buf_freelist->next;
79 r = xmalloc(sizeof(struct http_buf));
86 static void http_buf_destroy(struct http_buf *b)
88 b->next = http_buf_freelist;
89 http_buf_freelist = b;
92 static void http_buf_destroy_queue(struct http_buf *b)
104 // Calculate length of chain
105 static int http_buf_len(struct http_buf *b)
108 for (; b; b = b->next)
114 static struct http_buf *http_buf_bybuf(char *b, int len)
116 struct http_buf *res = 0;
117 struct http_buf **p = &res;
122 if (tocopy > HTTP_BUF_SIZE)
123 tocopy = HTTP_BUF_SIZE;
124 *p = http_buf_create();
125 memcpy((*p)->buf, b, tocopy);
134 // Add a (chain of) buffers to the end of an existing queue.
135 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
138 queue = &(*queue)->next;
142 static struct http_buf *http_buf_bywrbuf(WRBUF wrbuf)
144 // Heavens to Betsy (buf)!
145 return http_buf_bybuf(wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
148 // Non-destructively collapse chain of buffers into a string (max *len)
150 static int http_buf_peek(struct http_buf *b, char *buf, int len)
153 while (b && rd < len)
155 int toread = len - rd;
158 memcpy(buf + rd, b->buf + b->offset, toread);
166 // Ddestructively munch up to len from head of queue.
167 static int http_buf_read(struct http_buf **b, char *buf, int len)
170 while ((*b) && rd < len)
172 int toread = len - rd;
173 if (toread > (*b)->len)
175 memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
177 if (toread < (*b)->len)
180 (*b)->offset += toread;
185 struct http_buf *n = (*b)->next;
186 http_buf_destroy(*b);
194 // Buffers may overlap.
195 static void urldecode(char *i, char *o)
207 sscanf(i, "%2hhx", o);
217 // Warning: Buffers may not overlap
218 void urlencode(const char *i, char *o)
222 if (strchr(" /:", *i))
224 sprintf(o, "%%%.2X", (int) *i);
234 void http_addheader(struct http_response *r, const char *name, const char *value)
236 struct http_channel *c = r->channel;
237 struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
238 h->name = nmem_strdup(c->nmem, name);
239 h->value = nmem_strdup(c->nmem, value);
240 h->next = r->headers;
244 char *http_argbyname(struct http_request *r, char *name)
246 struct http_argument *p;
249 for (p = r->arguments; p; p = p->next)
250 if (!strcmp(p->name, name))
255 char *http_headerbyname(struct http_header *h, char *name)
257 for (; h; h = h->next)
258 if (!strcmp(h->name, name))
263 struct http_response *http_create_response(struct http_channel *c)
265 struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
266 strcpy(r->code, "200");
274 // Check if buf contains a package (minus payload)
275 static int package_check(const char *buf)
278 while (*buf) // Check if we have a sequence of lines terminated by an empty line
280 char *b = strstr(buf, "\r\n");
285 len += (b - buf) + 2;
293 // Check if we have a request. Return 0 or length
294 // (including trailing CRNL) FIXME: Does not deal gracefully with requests
295 // carrying payload but this is kind of OK since we will reject anything
296 // other than an empty GET
297 static int request_check(struct http_buf *queue)
301 http_buf_peek(queue, tmp, 4096);
302 return package_check(tmp);
305 struct http_response *http_parse_response_buf(struct http_channel *c, const char *buf, int len)
308 struct http_response *r = http_create_response(c);
310 struct http_header **hp = &r->headers;
314 memcpy(tmp, buf, len);
315 for (p = tmp; *p && *p != ' '; p++) // Skip HTTP version
319 for (p2 = p; *p2 && *p2 != ' ' && p2 - p < 3; p2++)
320 r->code[p2 - p] = *p2;
321 if (!(p = strstr(tmp, "\r\n")))
326 if (!(p2 = strstr(p, "\r\n")))
328 if (p == p2) // End of headers
332 struct http_header *h = *hp = nmem_malloc(c->nmem, sizeof(*h));
333 char *value = strchr(p, ':');
337 h->name = nmem_strdup(c->nmem, p);
338 while (isspace(*value))
340 if (value >= p2) // Empty header;
347 h->value = nmem_strdup(c->nmem, value);
356 struct http_request *http_parse_request(struct http_channel *c, struct http_buf **queue,
359 struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
366 if (http_buf_read(queue, buf, len) < len)
374 for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
378 yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
383 if (!(buf = strchr(buf, ' ')))
385 yaz_log(YLOG_WARN, "Syntax error in request (1)");
389 if (!(p = strchr(buf, ' ')))
391 yaz_log(YLOG_WARN, "Syntax error in request (2)");
395 if ((p2 = strchr(buf, '?'))) // Do we have arguments?
397 r->path = nmem_strdup(c->nmem, buf);
400 r->search = nmem_strdup(c->nmem, p2);
404 struct http_argument *a;
405 char *equal = strchr(p2, '=');
406 char *eoa = strchr(p2, '&');
409 yaz_log(YLOG_WARN, "Expected '=' in argument");
413 eoa = equal + strlen(equal); // last argument
416 a = nmem_malloc(c->nmem, sizeof(struct http_argument));
418 a->name = nmem_strdup(c->nmem, p2);
419 urldecode(equal, equal);
420 a->value = nmem_strdup(c->nmem, equal);
421 a->next = r->arguments;
428 if (strncmp(buf, "HTTP/", 5))
429 strcpy(r->http_version, "1.0");
433 if (!(p = strstr(buf, "\r\n")))
437 strcpy(r->http_version, buf);
440 strcpy(c->version, r->http_version);
445 if (!(p = strstr(buf, "\r\n")))
451 struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
452 if (!(p2 = strchr(buf, ':')))
455 h->name = nmem_strdup(c->nmem, buf);
458 if (p2 >= p) // Empty header?
464 h->value = nmem_strdup(c->nmem, p2);
465 h->next = r->headers;
474 static struct http_buf *http_serialize_response(struct http_channel *c,
475 struct http_response *r)
477 struct http_header *h;
479 wrbuf_rewind(c->wrbuf);
480 wrbuf_printf(c->wrbuf, "HTTP/1.1 %s %s\r\n", r->code, r->msg);
481 for (h = r->headers; h; h = h->next)
482 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
485 wrbuf_printf(c->wrbuf, "Content-length: %d\r\n", r->payload ?
486 (int) strlen(r->payload) : 0);
487 wrbuf_printf(c->wrbuf, "Content-type: text/xml\r\n");
489 wrbuf_puts(c->wrbuf, "\r\n");
492 wrbuf_puts(c->wrbuf, r->payload);
494 return http_buf_bywrbuf(c->wrbuf);
497 // Serialize a HTTP request
498 static struct http_buf *http_serialize_request(struct http_request *r)
500 struct http_channel *c = r->channel;
501 struct http_header *h;
502 struct http_argument *a;
504 wrbuf_rewind(c->wrbuf);
505 wrbuf_printf(c->wrbuf, "%s %s", r->method, r->path);
509 wrbuf_putc(c->wrbuf, '?');
510 for (a = r->arguments; a; a = a->next) {
511 if (a != r->arguments)
512 wrbuf_putc(c->wrbuf, '&');
513 wrbuf_printf(c->wrbuf, "%s=%s", a->name, a->value);
517 wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
519 for (h = r->headers; h; h = h->next)
520 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
522 wrbuf_puts(c->wrbuf, "\r\n");
524 return http_buf_bywrbuf(c->wrbuf);
528 static int http_weshouldproxy(struct http_request *rq)
530 if (proxy_addr && !strstr(rq->path, "search.pz2"))
536 struct http_header * http_header_append(struct http_channel *ch,
537 struct http_header * hp,
541 struct http_header *hpnew = 0;
546 while (hp && hp->next)
549 if(name && strlen(name)&& value && strlen(value)){
550 hpnew = nmem_malloc(ch->nmem, sizeof *hpnew);
551 hpnew->name = nmem_strdup(ch->nmem, name);
552 hpnew->value = nmem_strdup(ch->nmem, value);
566 static int http_proxy(struct http_request *rq)
568 struct http_channel *c = rq->channel;
569 struct http_proxy *p = c->proxy;
570 struct http_header *hp;
571 struct http_buf *requestbuf;
572 char server_via[128] = "";
573 char server_port[16] = "";
574 struct conf_server *ser = global_parameters.server;
576 if (!p) // This is a new connection. Create a proxy channel
583 if (!(pe = getprotobyname("tcp"))) {
586 if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
588 yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
591 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
592 &one, sizeof(one)) < 0)
594 if ((flags = fcntl(sock, F_GETFL, 0)) < 0)
595 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
596 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
597 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
598 if (connect(sock, (struct sockaddr *) proxy_addr,
599 sizeof(*proxy_addr)) < 0)
600 if (errno != EINPROGRESS)
602 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
606 p = xmalloc(sizeof(struct http_proxy));
609 p->first_response = 1;
611 // We will add EVENT_OUTPUT below
612 p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT);
613 iochan_setdata(p->iochan, p);
614 p->iochan->next = channel_list;
615 channel_list = p->iochan;
618 // Do _not_ modify Host: header, just checking it's existence
619 for (hp = rq->headers; hp; hp = hp->next)
620 if (!strcmp(hp->name, "Host"))
624 yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
628 // Add new header about paraz2 version, host, remote client address, etc.
631 hp = http_header_append(c, hp,
632 "X-Pazpar2-Version", PACKAGE_VERSION);
633 hp = http_header_append(c, hp,
634 "X-Pazpar2-Server-Host", ser->host);
635 sprintf(server_port, "%d", ser->port);
636 hp = http_header_append(c, hp,
637 "X-Pazpar2-Server-Port", server_port);
638 sprintf(server_via, "1.1 %s:%s (%s/%s)",
639 ser->host, server_port, PACKAGE_NAME, PACKAGE_VERSION);
640 hp = http_header_append(c, hp, "Via" , server_via);
641 hp = http_header_append(c, hp, "X-Forwarded-For", c->addr);
644 requestbuf = http_serialize_request(rq);
645 http_buf_enqueue(&p->oqueue, requestbuf);
646 iochan_setflag(p->iochan, EVENT_OUTPUT);
650 void http_send_response(struct http_channel *ch)
652 struct http_response *rs = ch->response;
656 hb = http_serialize_response(ch, rs);
659 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
660 http_destroy(ch->iochan);
664 http_buf_enqueue(&ch->oqueue, hb);
665 iochan_setflag(ch->iochan, EVENT_OUTPUT);
666 ch->state = Http_Idle;
670 static void http_io(IOCHAN i, int event)
672 struct http_channel *hc = iochan_getdata(i);
677 struct http_buf *htbuf;
680 htbuf = http_buf_create();
681 res = read(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1);
682 if (res == -1 && errno == EAGAIN)
684 http_buf_destroy(htbuf);
689 http_buf_destroy(htbuf);
695 htbuf->buf[res] = '\0';
697 http_buf_enqueue(&hc->iqueue, htbuf);
700 if (hc->state == Http_Busy)
702 if ((reqlen = request_check(hc->iqueue)) <= 2)
705 nmem_reset(hc->nmem);
706 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
708 yaz_log(YLOG_WARN, "Failed to parse request");
713 yaz_log(YLOG_LOG, "Request: %s %s%s%s", hc->request->method,
715 *hc->request->search ? "?" : "",
716 hc->request->search);
717 if (http_weshouldproxy(hc->request))
718 http_proxy(hc->request);
721 // Execute our business logic!
722 hc->state = Http_Busy;
727 yaz_log(YLOG_DEBUG, "We think we have more input to read. Forcing event");
728 iochan_setevent(i, EVENT_INPUT);
736 struct http_buf *wb = hc->oqueue;
737 res = write(iochan_getfd(hc->iochan), wb->buf + wb->offset, wb->len);
740 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
746 hc->oqueue = hc->oqueue->next;
747 http_buf_destroy(wb);
755 if (!strcmp(hc->version, "1.0"))
762 iochan_clearflag(i, EVENT_OUTPUT);
764 iochan_setevent(hc->iochan, EVENT_INPUT);
769 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
770 http_destroy(i); // Server closed; we're done
773 yaz_log(YLOG_WARN, "Unexpected event on connection");
779 // If this hostname contains our proxy host as a prefix, replace with myurl
780 static char *sub_hostname(struct http_channel *c, char *buf)
783 if (strlen(buf) > 1023)
785 if (strncmp(buf, "http://", 7))
787 if (!strncmp(buf + 7, proxy_url, strlen(proxy_url)))
790 strcat(tmp, buf + strlen(proxy_url) + 7);
791 return nmem_strdup(c->nmem, tmp);
797 // Handles I/O on a client connection to a backend web server (proxy mode)
798 static void proxy_io(IOCHAN pi, int event)
800 struct http_proxy *pc = iochan_getdata(pi);
801 struct http_channel *hc = pc->channel;
806 struct http_buf *htbuf;
809 htbuf = http_buf_create();
810 res = read(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1);
811 if (res == 0 || (res < 0 && errno != EINPROGRESS))
815 yaz_log(YLOG_WARN, "Proxy read came up short");
816 // Close channel and alert client HTTP channel that we're gone
817 http_buf_destroy(htbuf);
818 close(iochan_getfd(pi));
824 http_destroy(hc->iochan);
830 htbuf->buf[res] = '\0';
834 if (pc->first_response) // Check if this is a redirect
837 if ((len = package_check(htbuf->buf)))
839 struct http_response *res = http_parse_response_buf(hc, htbuf->buf, len);
842 struct http_header *h;
843 for (h = res->headers; h; h = h->next)
844 if (!strcmp(h->name, "Location"))
846 // We found a location header. Rewrite it.
847 struct http_buf *buf;
848 h->value = sub_hostname(hc, h->value);
849 buf = http_serialize_response(hc, res);
850 yaz_log(YLOG_LOG, "Proxy rewrite");
851 http_buf_enqueue(&hc->oqueue, buf);
857 pc->first_response = 0;
860 // Write any remaining payload
861 if (htbuf->len - htbuf->offset > 0)
862 http_buf_enqueue(&hc->oqueue, htbuf);
864 iochan_setflag(hc->iochan, EVENT_OUTPUT);
867 if (!(htbuf = pc->oqueue))
869 iochan_clearflag(pi, EVENT_OUTPUT);
872 res = write(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len);
875 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
876 http_destroy(hc->iochan);
879 if (res == htbuf->len)
881 struct http_buf *np = htbuf->next;
882 http_buf_destroy(htbuf);
888 htbuf->offset += res;
892 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
896 yaz_log(YLOG_WARN, "Unexpected event on connection");
897 http_destroy(hc->iochan);
902 static void http_destroy(IOCHAN i)
904 struct http_channel *s = iochan_getdata(i);
908 if (s->proxy->iochan)
910 close(iochan_getfd(s->proxy->iochan));
911 iochan_destroy(s->proxy->iochan);
913 http_buf_destroy_queue(s->proxy->oqueue);
916 s->next = http_channel_freelist;
917 http_channel_freelist = s;
918 close(iochan_getfd(i));
922 static struct http_channel *http_create(const char *addr)
924 struct http_channel *r = http_channel_freelist;
928 http_channel_freelist = r->next;
930 wrbuf_rewind(r->wrbuf);
934 r = xmalloc(sizeof(struct http_channel));
935 r->nmem = nmem_create();
936 r->wrbuf = wrbuf_alloc();
940 r->iqueue = r->oqueue = 0;
941 r->state = Http_Idle;
946 yaz_log(YLOG_WARN, "Invalid HTTP forward address");
949 r->addr = nmem_strdup(r->nmem, addr);
954 /* Accept a new command connection */
955 static void http_accept(IOCHAN i, int event)
957 struct sockaddr_in addr;
958 int fd = iochan_getfd(i);
963 struct http_channel *ch;
966 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
968 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
971 if ((flags = fcntl(s, F_GETFL, 0)) < 0)
972 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
973 if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
974 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
976 yaz_log(YLOG_DEBUG, "New command connection");
977 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT);
979 ch = http_create(inet_ntoa(addr.sin_addr));
981 iochan_setdata(c, ch);
983 c->next = channel_list;
987 /* Create a http-channel listener, syntax [host:]port */
988 void http_init(const char *addr)
993 struct sockaddr_in myaddr;
998 yaz_log(YLOG_LOG, "HTTP listener %s", addr);
1000 memset(&myaddr, 0, sizeof myaddr);
1001 myaddr.sin_family = AF_INET;
1002 pp = strchr(addr, ':');
1005 int len = pp - addr;
1009 strncpy(hostname, addr, len);
1010 hostname[len] = '\0';
1011 if (!(he = gethostbyname(hostname)))
1013 yaz_log(YLOG_FATAL, "Unable to resolve '%s'", hostname);
1017 memcpy(&myaddr.sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1018 port = atoi(pp + 1);
1020 yaz_log(YLOG_LOG, "HTTP address %s:%d",
1021 "" == he->h_addr_list[0] ? he->h_addr_list[0] : "127.0.0.1" ,
1028 myaddr.sin_addr.s_addr = INADDR_ANY;
1031 myaddr.sin_port = htons(port);
1033 if (!(p = getprotobyname("tcp"))) {
1036 if ((l = socket(PF_INET, SOCK_STREAM, p->p_proto)) < 0)
1037 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
1038 if (setsockopt(l, SOL_SOCKET, SO_REUSEADDR, (char*)
1039 &one, sizeof(one)) < 0)
1042 if (bind(l, (struct sockaddr *) &myaddr, sizeof myaddr) < 0)
1043 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind");
1044 if (listen(l, SOMAXCONN) < 0)
1045 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen");
1047 c = iochan_create(l, http_accept, EVENT_INPUT | EVENT_EXCEPT);
1048 c->next = channel_list;
1052 void http_set_proxyaddr(char *host, char *base_url)
1058 strcpy(myurl, base_url);
1059 strcpy(proxy_url, host);
1060 p = strchr(host, ':');
1061 yaz_log(YLOG_DEBUG, "Proxying for %s", host);
1062 yaz_log(YLOG_LOG, "HTTP backend %s", proxy_url);
1069 if (!(he = gethostbyname(host)))
1071 fprintf(stderr, "Failed to lookup '%s'\n", host);
1074 proxy_addr = xmalloc(sizeof(struct sockaddr_in));
1075 proxy_addr->sin_family = he->h_addrtype;
1076 memcpy(&proxy_addr->sin_addr.s_addr, he->h_addr_list[0], he->h_length);
1077 proxy_addr->sin_port = htons(port);
1083 * indent-tabs-mode: nil
1085 * vim: shiftwidth=4 tabstop=8 expandtab