1 /* This file is part of Pazpar2.
2 Copyright (C) Index Data
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
32 typedef int socklen_t;
36 #include <sys/socket.h>
39 #include <sys/types.h>
41 #include <yaz/snprintf.h>
58 #include <yaz/yaz-util.h>
59 #include <yaz/comstack.h>
61 #include <yaz/mutex.h>
66 #include "parameters.h"
68 #define MAX_HTTP_HEADER 4096
71 #define strncasecmp _strnicmp
72 #define strcasecmp _stricmp
77 #define HTTP_BUF_SIZE 4096
81 struct http_buf *next;
85 static void proxy_io(IOCHAN i, int event);
86 static struct http_channel *http_channel_create(http_server_t http_server,
88 struct conf_server *server);
89 static void http_channel_destroy(IOCHAN i);
90 static http_server_t http_server_create(void);
91 static void http_server_incref(http_server_t hs);
94 #define CLOSESOCKET(x) closesocket(x)
96 #define CLOSESOCKET(x) close(x)
104 http_sessions_t http_sessions;
105 struct sockaddr_in *proxy_addr;
109 struct http_channel_observer_s {
112 http_channel_destroy_t destroy;
113 struct http_channel_observer_s *next;
114 struct http_channel *chan;
118 const char *http_lookup_header(struct http_header *header,
121 for (; header; header = header->next)
122 if (!strcasecmp(name, header->name))
123 return header->value;
127 static struct http_buf *http_buf_create(http_server_t hs)
129 struct http_buf *r = xmalloc(sizeof(*r));
136 static void http_buf_destroy(http_server_t hs, struct http_buf *b)
141 static void http_buf_destroy_queue(http_server_t hs, struct http_buf *b)
147 http_buf_destroy(hs, b);
152 static struct http_buf *http_buf_bybuf(http_server_t hs, char *b, int len)
154 struct http_buf *res = 0;
155 struct http_buf **p = &res;
160 if (tocopy > HTTP_BUF_SIZE)
161 tocopy = HTTP_BUF_SIZE;
162 *p = http_buf_create(hs);
163 memcpy((*p)->buf, b, tocopy);
172 // Add a (chain of) buffers to the end of an existing queue.
173 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
176 queue = &(*queue)->next;
180 static struct http_buf *http_buf_bywrbuf(http_server_t hs, WRBUF wrbuf)
182 // Heavens to Betsy (buf)!
183 return http_buf_bybuf(hs, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
186 // Non-destructively collapse chain of buffers into a string (max *len)
188 static void http_buf_peek(struct http_buf *b, char *buf, int len)
191 while (b && rd < len)
193 int toread = len - rd;
196 memcpy(buf + rd, b->buf + b->offset, toread);
203 static int http_buf_size(struct http_buf *b)
206 for (; b; b = b->next)
211 // Ddestructively munch up to len from head of queue.
212 static int http_buf_read(http_server_t hs,
213 struct http_buf **b, char *buf, int len)
216 while ((*b) && rd < len)
218 int toread = len - rd;
219 if (toread > (*b)->len)
221 memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
223 if (toread < (*b)->len)
226 (*b)->offset += toread;
231 struct http_buf *n = (*b)->next;
232 http_buf_destroy(hs, *b);
240 // Buffers may overlap.
241 static void urldecode(char *i, char *o)
250 else if (*i == '%' && i[1] && i[2])
254 sscanf(i, "%2x", &v);
264 // Warning: Buffers may not overlap
265 void urlencode(const char *i, char *o)
269 if (strchr(" /:", *i))
271 sprintf(o, "%%%.2X", (int) *i);
281 void http_addheader(struct http_response *r, const char *name, const char *value)
283 struct http_channel *c = r->channel;
284 struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
285 h->name = nmem_strdup(c->nmem, name);
286 h->value = nmem_strdup(c->nmem, value);
287 h->next = r->headers;
291 const char *http_argbyname(struct http_request *r, const char *name)
293 struct http_argument *p;
296 for (p = r->arguments; p; p = p->next)
297 if (!strcmp(p->name, name))
302 const char *http_headerbyname(struct http_header *h, const char *name)
304 for (; h; h = h->next)
305 if (!strcmp(h->name, name))
310 struct http_response *http_create_response(struct http_channel *c)
312 struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
313 strcpy(r->code, "200");
318 r->content_type = "text/xml";
323 static const char *next_crlf(const char *cp, size_t *skipped)
325 const char *next_cp = strchr(cp, '\n');
328 if (next_cp > cp && next_cp[-1] == '\r')
329 *skipped = next_cp - cp - 1;
331 *skipped = next_cp - cp;
337 // Check if buf contains a package (minus payload)
338 static int package_check(const char *buf, int sz)
346 const char *b = next_crlf(buf, &skipped);
350 // we did not find CRLF.. See if buffer is too large..
351 if (sz >= MAX_HTTP_HEADER-1)
352 return MAX_HTTP_HEADER-1; // yes. Return that (will fail later)
358 // CRLF CRLF , i.e. end of header
359 if (len + content_len <= sz)
360 return len + content_len;
364 // following first skip of \r\n so that we don't consider Method
365 if (!strncasecmp(buf, "Content-Length:", 15))
367 const char *cp = buf+15;
371 while (*cp && isdigit(*(const unsigned char *)cp))
372 content_len = content_len*10 + (*cp++ - '0');
373 if (content_len < 0) /* prevent negative offsets */
377 return 0; // incomplete request
380 // Check if we have a request. Return 0 or length
381 static int request_check(struct http_buf *queue)
383 char tmp[MAX_HTTP_HEADER];
385 // only peek at the header..
386 http_buf_peek(queue, tmp, MAX_HTTP_HEADER-1);
387 // still we only return non-zero if the complete request is received..
388 return package_check(tmp, http_buf_size(queue));
391 struct http_response *http_parse_response_buf(struct http_channel *c, const char *buf, int len)
393 char tmp[MAX_HTTP_HEADER];
394 struct http_response *r = http_create_response(c);
396 struct http_header **hp = &r->headers;
398 if (len >= MAX_HTTP_HEADER)
400 memcpy(tmp, buf, len);
401 for (p = tmp; *p && *p != ' '; p++) // Skip HTTP version
405 for (p2 = p; *p2 && *p2 != ' ' && p2 - p < 3; p2++)
406 r->code[p2 - p] = *p2;
407 if (!(p = strstr(tmp, "\r\n")))
412 if (!(p2 = strstr(p, "\r\n")))
414 if (p == p2) // End of headers
418 struct http_header *h = *hp = nmem_malloc(c->nmem, sizeof(*h));
419 char *value = strchr(p, ':');
423 h->name = nmem_strdup(c->nmem, p);
424 while (isspace(*(const unsigned char *) value))
426 if (value >= p2) // Empty header;
433 h->value = nmem_strdup(c->nmem, value);
442 static int http_parse_arguments(struct http_request *r, NMEM nmem,
445 const char *p2 = args;
449 struct http_argument *a;
450 const char *equal = strchr(p2, '=');
451 const char *eoa = strchr(p2, '&');
454 yaz_log(YLOG_WARN, "Expected '=' in argument");
458 eoa = equal + strlen(equal); // last argument
459 else if (equal > eoa)
461 yaz_log(YLOG_WARN, "Missing '&' in argument");
464 a = nmem_malloc(nmem, sizeof(struct http_argument));
465 a->name = nmem_strdupn(nmem, p2, equal - p2);
466 a->value = nmem_strdupn(nmem, equal+1, eoa - equal - 1);
467 urldecode(a->name, a->name);
468 urldecode(a->value, a->value);
469 a->next = r->arguments;
478 struct http_request *http_parse_request(struct http_channel *c,
479 struct http_buf **queue,
482 struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
484 char *start = nmem_malloc(c->nmem, len+1);
487 if (http_buf_read(c->http_server, queue, buf, len) < len)
489 yaz_log(YLOG_WARN, "http_buf_read < len (%d)", len);
499 for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
503 yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
508 if (!(buf = strchr(buf, ' ')))
510 yaz_log(YLOG_WARN, "Missing Request-URI in HTTP request");
514 if (!(p = strchr(buf, ' ')))
516 yaz_log(YLOG_WARN, "HTTP Request-URI not terminated (too long?)");
520 if ((p2 = strchr(buf, '?'))) // Do we have arguments?
522 r->path = nmem_strdup(c->nmem, buf);
525 r->search = nmem_strdup(c->nmem, p2);
527 http_parse_arguments(r, c->nmem, p2);
531 if (strncmp(buf, "HTTP/", 5))
532 strcpy(r->http_version, "1.0");
536 buf += 5; // strlen("HTTP/")
538 p = (char*) next_crlf(buf, &skipped);
539 if (!p || skipped < 3 || skipped > 5)
542 memcpy(r->http_version, buf, skipped);
543 r->http_version[skipped] = '\0';
546 strcpy(c->version, r->http_version);
553 p = (char *) next_crlf(buf, &skipped);
558 else if (skipped == 0)
566 char *n_v = nmem_malloc(c->nmem, skipped+1);
567 struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
569 memcpy(n_v, buf, skipped);
572 if (!(cp = strchr(n_v, ':')))
574 h->name = nmem_strdupn(c->nmem, n_v, cp - n_v);
578 h->value = nmem_strdup(c->nmem, cp);
579 h->next = r->headers;
585 // determine if we do keep alive
586 if (!strcmp(c->version, "1.0"))
588 const char *v = http_lookup_header(r->headers, "Connection");
589 if (v && !strcmp(v, "Keep-Alive"))
596 const char *v = http_lookup_header(r->headers, "Connection");
597 if (v && !strcmp(v, "close"))
602 if (buf < start + len)
604 const char *content_type = http_lookup_header(r->headers,
606 r->content_len = start + len - buf;
607 r->content_buf = buf;
609 if (!yaz_strcmp_del("application/x-www-form-urlencoded",
612 http_parse_arguments(r, c->nmem, r->content_buf);
618 static struct http_buf *http_serialize_response(struct http_channel *c,
619 struct http_response *r)
621 struct http_header *h;
623 wrbuf_rewind(c->wrbuf);
625 wrbuf_printf(c->wrbuf, "HTTP/%s %s %s\r\n", c->version, r->code, r->msg);
626 for (h = r->headers; h; h = h->next)
627 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
630 wrbuf_printf(c->wrbuf, "Content-Length: %d\r\n", r->payload ?
631 (int) strlen(r->payload) : 0);
632 wrbuf_printf(c->wrbuf, "Content-Type: %s\r\n", r->content_type);
633 if (!strcmp(r->content_type, "text/xml"))
635 xmlDoc *doc = xmlParseMemory(r->payload, strlen(r->payload));
642 yaz_log(YLOG_WARN, "Sending non-wellformed "
643 "response (bug #1162");
644 yaz_log(YLOG_WARN, "payload: %s", r->payload);
648 wrbuf_puts(c->wrbuf, "\r\n");
651 wrbuf_puts(c->wrbuf, r->payload);
653 if (global_parameters.dump_records > 1)
655 FILE *lf = yaz_log_file();
656 yaz_log(YLOG_LOG, "Response:");
657 fwrite(wrbuf_buf(c->wrbuf), 1, wrbuf_len(c->wrbuf), lf);
660 return http_buf_bywrbuf(c->http_server, c->wrbuf);
663 // Serialize a HTTP request
664 static struct http_buf *http_serialize_request(struct http_request *r)
666 struct http_channel *c = r->channel;
667 struct http_header *h;
669 wrbuf_rewind(c->wrbuf);
670 wrbuf_printf(c->wrbuf, "%s %s%s%s", r->method, r->path,
671 *r->search ? "?" : "", r->search);
673 wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
675 for (h = r->headers; h; h = h->next)
676 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
678 wrbuf_puts(c->wrbuf, "\r\n");
681 wrbuf_write(c->wrbuf, r->content_buf, r->content_len);
684 yaz_log(YLOG_LOG, "WRITING TO PROXY:\n%s\n----",
685 wrbuf_cstr(c->wrbuf));
687 return http_buf_bywrbuf(c->http_server, c->wrbuf);
691 static int http_weshouldproxy(struct http_request *rq)
693 struct http_channel *c = rq->channel;
694 if (c->server->http_server->proxy_addr && !strstr(rq->path, "search.pz2"))
700 struct http_header * http_header_append(struct http_channel *ch,
701 struct http_header * hp,
705 struct http_header *hpnew = 0;
710 while (hp && hp->next)
713 if(name && strlen(name)&& value && strlen(value)){
714 hpnew = nmem_malloc(ch->nmem, sizeof *hpnew);
715 hpnew->name = nmem_strdup(ch->nmem, name);
716 hpnew->value = nmem_strdup(ch->nmem, value);
729 static int is_inprogress(void)
732 if (WSAGetLastError() == WSAEWOULDBLOCK)
735 if (errno == EINPROGRESS)
741 static void enable_nonblock(int sock)
745 flags = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
746 if (ioctlsocket(sock, FIONBIO, &flags) < 0)
747 yaz_log(YLOG_FATAL|YLOG_ERRNO, "ioctlsocket");
749 if ((flags = fcntl(sock, F_GETFL, 0)) < 0)
750 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
751 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
752 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
756 static int http_proxy(struct http_request *rq)
758 struct http_channel *c = rq->channel;
759 struct http_proxy *p = c->proxy;
760 struct http_header *hp;
761 struct http_buf *requestbuf;
762 struct conf_server *ser = c->server;
764 if (!p) // This is a new connection. Create a proxy channel
770 if (!(pe = getprotobyname("tcp"))) {
773 if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
775 yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
778 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
779 &one, sizeof(one)) < 0)
781 enable_nonblock(sock);
782 if (connect(sock, (struct sockaddr *)
783 c->server->http_server->proxy_addr,
784 sizeof(*c->server->http_server->proxy_addr)) < 0)
786 if (!is_inprogress())
788 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
792 p = xmalloc(sizeof(struct http_proxy));
795 p->first_response = 1;
797 // We will add EVENT_OUTPUT below
798 p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT, "http_proxy");
799 iochan_setdata(p->iochan, p);
801 iochan_add(ser->iochan_man, p->iochan);
804 // Do _not_ modify Host: header, just checking it's existence
806 if (!http_lookup_header(rq->headers, "Host"))
808 yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
812 // Add new header about paraz2 version, host, remote client address, etc.
814 char server_via[128];
817 hp = http_header_append(c, hp,
818 "X-Pazpar2-Version", PACKAGE_VERSION);
819 hp = http_header_append(c, hp,
820 "X-Pazpar2-Server-Host", ser->host);
821 hp = http_header_append(c, hp,
822 "X-Pazpar2-Server-Port", ser->port);
823 yaz_snprintf(server_via, sizeof(server_via),
825 ser->host, ser->port,
826 PACKAGE_NAME, PACKAGE_VERSION);
827 hp = http_header_append(c, hp, "Via" , server_via);
828 hp = http_header_append(c, hp, "X-Forwarded-For", c->addr);
831 requestbuf = http_serialize_request(rq);
833 http_buf_enqueue(&p->oqueue, requestbuf);
834 iochan_setflag(p->iochan, EVENT_OUTPUT);
838 void http_send_response(struct http_channel *ch)
840 struct http_response *rs = ch->response;
843 yaz_timing_stop(ch->yt);
846 yaz_log(YLOG_LOG, "Response: %6.5f %d %s%s%s ",
847 yaz_timing_get_real(ch->yt),
848 iochan_getfd(ch->iochan),
850 *ch->request->search ? "?" : "",
851 ch->request->search);
854 hb = http_serialize_response(ch, rs);
857 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
858 http_channel_destroy(ch->iochan);
862 http_buf_enqueue(&ch->oqueue, hb);
863 iochan_setflag(ch->iochan, EVENT_OUTPUT);
864 ch->state = Http_Idle;
868 static void http_error(struct http_channel *hc, int no, const char *msg)
870 struct http_response *rs = http_create_response(hc);
873 hc->keep_alive = 0; // not keeping this HTTP session alive
875 sprintf(rs->code, "%d", no);
877 rs->msg = nmem_strdup(hc->nmem, msg);
878 rs->payload = nmem_malloc(hc->nmem, 100);
879 yaz_snprintf(rs->payload, 99, "<error>HTTP Error %d: %s</error>\n",
881 http_send_response(hc);
884 static void http_io(IOCHAN i, int event)
886 struct http_channel *hc = iochan_getdata(i);
889 if (event == EVENT_INPUT)
892 struct http_buf *htbuf;
894 htbuf = http_buf_create(hc->http_server);
895 res = recv(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1, 0);
896 if (res == -1 && errno == EAGAIN)
898 http_buf_destroy(hc->http_server, htbuf);
904 if (hc->http_server->record_file)
907 gettimeofday(&tv, 0);
908 fprintf(hc->http_server->record_file, "r %lld %lld %lld 0\n",
909 (long long) tv.tv_sec, (long long) tv.tv_usec,
910 (long long) iochan_getfd(i));
913 http_buf_destroy(hc->http_server, htbuf);
914 fflush(hc->http_server->record_file);
915 http_channel_destroy(i);
918 htbuf->buf[res] = '\0';
920 http_buf_enqueue(&hc->iqueue, htbuf);
924 if (hc->state == Http_Busy)
926 reqlen = request_check(hc->iqueue);
929 // we have a complete HTTP request
930 nmem_reset(hc->nmem);
932 if (hc->http_server->record_file)
937 for (hb = hc->iqueue; hb; hb = hb->next)
939 gettimeofday(&tv, 0);
940 fprintf(hc->http_server->record_file, "r %lld %lld %lld %d\n",
941 (long long) tv.tv_sec, (long long) tv.tv_usec,
942 (long long) iochan_getfd(i), sz);
943 for (hb = hc->iqueue; hb; hb = hb->next)
944 fwrite(hb->buf, 1, hb->len, hc->http_server->record_file);
945 fflush(hc->http_server->record_file);
948 yaz_timing_start(hc->yt);
949 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
951 yaz_log(YLOG_WARN, "Failed to parse request");
952 http_error(hc, 400, "Bad Request");
956 yaz_log(YLOG_LOG, "Request: - %d %s %s%s%s",
960 *hc->request->search ? "?" : "",
961 hc->request->search);
962 if (hc->request->content_buf)
963 yaz_log(YLOG_LOG, "%s", hc->request->content_buf);
964 if (http_weshouldproxy(hc->request))
965 http_proxy(hc->request);
968 // Execute our business logic!
969 hc->state = Http_Busy;
974 else if (event == EVENT_OUTPUT)
979 struct http_buf *wb = hc->oqueue;
981 res = send(iochan_getfd(hc->iochan),
982 wb->buf + wb->offset, wb->len, 0);
985 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
986 http_channel_destroy(i);
992 if (hc->http_server->record_file)
995 int sz = wb->offset + wb->len;
996 gettimeofday(&tv, 0);
997 fprintf(hc->http_server->record_file, "w %lld %lld %lld %d\n",
998 (long long) tv.tv_sec, (long long) tv.tv_usec,
999 (long long) iochan_getfd(i), sz);
1000 fwrite(wb->buf, 1, wb->offset + wb->len,
1001 hc->http_server->record_file);
1002 fputc('\n', hc->http_server->record_file);
1003 fflush(hc->http_server->record_file);
1006 hc->oqueue = hc->oqueue->next;
1007 http_buf_destroy(hc->http_server, wb);
1016 if (!hc->keep_alive)
1018 http_channel_destroy(i);
1023 iochan_clearflag(i, EVENT_OUTPUT);
1025 event = EVENT_INPUT;
1029 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
1030 http_channel_destroy(i); // Server closed; we're done
1034 yaz_log(YLOG_WARN, "Unexpected event on connection");
1035 http_channel_destroy(i);
1041 // Handles I/O on a client connection to a backend web server (proxy mode)
1042 static void proxy_io(IOCHAN pi, int event)
1044 struct http_proxy *pc = iochan_getdata(pi);
1045 struct http_channel *hc = pc->channel;
1050 struct http_buf *htbuf;
1053 htbuf = http_buf_create(hc->http_server);
1054 res = recv(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1, 0);
1055 if (res == 0 || (res < 0 && !is_inprogress()))
1059 yaz_log(YLOG_WARN, "Proxy read came up short");
1060 // Close channel and alert client HTTP channel that we're gone
1061 http_buf_destroy(hc->http_server, htbuf);
1062 CLOSESOCKET(iochan_getfd(pi));
1068 http_channel_destroy(hc->iochan);
1074 htbuf->buf[res] = '\0';
1077 // Write any remaining payload
1078 if (htbuf->len - htbuf->offset > 0)
1079 http_buf_enqueue(&hc->oqueue, htbuf);
1081 iochan_setflag(hc->iochan, EVENT_OUTPUT);
1084 if (!(htbuf = pc->oqueue))
1086 iochan_clearflag(pi, EVENT_OUTPUT);
1089 res = send(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len, 0);
1092 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
1093 http_channel_destroy(hc->iochan);
1096 if (res == htbuf->len)
1098 struct http_buf *np = htbuf->next;
1099 http_buf_destroy(hc->http_server, htbuf);
1105 htbuf->offset += res;
1109 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
1113 yaz_log(YLOG_WARN, "Unexpected event on connection");
1114 http_channel_destroy(hc->iochan);
1119 static void http_fire_observers(struct http_channel *c);
1120 static void http_destroy_observers(struct http_channel *c);
1123 static void http_channel_destroy(IOCHAN i)
1125 struct http_channel *s = iochan_getdata(i);
1126 http_server_t http_server;
1130 if (s->proxy->iochan)
1132 CLOSESOCKET(iochan_getfd(s->proxy->iochan));
1133 iochan_destroy(s->proxy->iochan);
1135 http_buf_destroy_queue(s->http_server, s->proxy->oqueue);
1138 yaz_timing_destroy(&s->yt);
1139 http_buf_destroy_queue(s->http_server, s->iqueue);
1140 http_buf_destroy_queue(s->http_server, s->oqueue);
1141 http_fire_observers(s);
1142 http_destroy_observers(s);
1144 http_server = s->http_server; /* save it for destroy (decref) */
1146 http_server_destroy(http_server);
1148 CLOSESOCKET(iochan_getfd(i));
1151 nmem_destroy(s->nmem);
1152 wrbuf_destroy(s->wrbuf);
1156 static struct http_channel *http_channel_create(http_server_t hs,
1158 struct conf_server *server)
1160 struct http_channel *r;
1162 r = xmalloc(sizeof(struct http_channel));
1163 r->nmem = nmem_create();
1164 r->wrbuf = wrbuf_alloc();
1166 http_server_incref(hs);
1167 r->http_server = hs;
1168 r->http_sessions = hs->http_sessions;
1169 assert(r->http_sessions);
1173 r->iqueue = r->oqueue = 0;
1174 r->state = Http_Idle;
1178 strcpy(r->version, "1.0");
1181 yaz_log(YLOG_WARN, "Invalid HTTP forward address");
1184 strcpy(r->addr, addr);
1186 r->yt = yaz_timing_create();
1191 /* Accept a new command connection */
1192 static void http_accept(IOCHAN i, int event)
1195 struct sockaddr_storage addr;
1196 int fd = iochan_getfd(i);
1197 socklen_t len = sizeof addr;
1200 struct http_channel *ch;
1201 struct conf_server *server = iochan_getdata(i);
1203 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
1205 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
1208 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1, 0, 0,
1211 yaz_log(YLOG_WARN|YLOG_ERRNO, "getnameinfo");
1217 yaz_log(YLOG_DEBUG, "New command connection");
1218 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT,
1219 "http_session_socket");
1222 ch = http_channel_create(server->http_server, host, server);
1224 iochan_setdata(c, ch);
1225 iochan_add(server->iochan_man, c);
1228 /* Create a http-channel listener, syntax [host:]port */
1229 int http_init(struct conf_server *server, const char *record_fname)
1234 FILE *record_file = 0;
1235 struct addrinfo hints, *af = 0, *ai;
1239 yaz_log(YLOG_LOG, "HTTP listener %s:%s", server->host, server->port);
1242 hints.ai_family = AF_UNSPEC;
1243 hints.ai_socktype = SOCK_STREAM;
1244 hints.ai_protocol = 0;
1245 hints.ai_addrlen = 0;
1246 hints.ai_addr = NULL;
1247 hints.ai_canonname = NULL;
1248 hints.ai_next = NULL;
1250 if (!strcmp(server->host, "@"))
1253 hints.ai_flags = AI_PASSIVE;
1254 error = getaddrinfo(0, server->port, &hints, &af);
1257 error = getaddrinfo(server->host, server->port, &hints, &af);
1261 yaz_log(YLOG_FATAL, "Failed to resolve %s: %s", server->host,
1262 gai_strerror(error));
1265 for (ai = af; ai; ai = ai->ai_next)
1267 if (ai->ai_family == AF_INET6)
1269 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1276 for (ai = af; ai; ai = ai->ai_next)
1278 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1285 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
1289 if (ipv6_only >= 0 && ai->ai_family == AF_INET6 &&
1290 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_only, sizeof(ipv6_only)))
1292 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setsockopt IPV6_V6ONLY %s:%s %d",
1293 server->host, server->port, ipv6_only);
1298 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
1300 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setsockopt SO_REUSEADDR %s:%s",
1301 server->host, server->port);
1306 if (bind(s, ai->ai_addr, ai->ai_addrlen) < 0)
1308 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind %s:%s",
1309 server->host, server->port);
1315 if (listen(s, SOMAXCONN) < 0)
1317 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen %s:%s",
1318 server->host, server->port);
1325 record_file = fopen(record_fname, "wb");
1328 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fopen %s", record_fname);
1333 server->http_server = http_server_create();
1335 server->http_server->record_file = record_file;
1336 server->http_server->listener_socket = s;
1338 c = iochan_create(s, http_accept, EVENT_INPUT | EVENT_EXCEPT, "http_server");
1339 iochan_setdata(c, server);
1341 iochan_add(server->iochan_man, c);
1345 void http_close_server(struct conf_server *server)
1347 /* break the event_loop (select) by closing down the HTTP listener sock */
1348 if (server->http_server->listener_socket)
1351 closesocket(server->http_server->listener_socket);
1353 close(server->http_server->listener_socket);
1358 void http_set_proxyaddr(const char *host, struct conf_server *server)
1363 WRBUF w = wrbuf_alloc();
1365 yaz_log(YLOG_LOG, "HTTP backend %s", host);
1367 p = strchr(host, ':');
1371 wrbuf_write(w, host, p - host);
1377 wrbuf_puts(w, host);
1379 if (!(he = gethostbyname(wrbuf_cstr(w))))
1381 fprintf(stderr, "Failed to lookup '%s'\n", wrbuf_cstr(w));
1386 server->http_server->proxy_addr = xmalloc(sizeof(struct sockaddr_in));
1387 server->http_server->proxy_addr->sin_family = he->h_addrtype;
1388 memcpy(&server->http_server->proxy_addr->sin_addr.s_addr,
1389 he->h_addr_list[0], he->h_length);
1390 server->http_server->proxy_addr->sin_port = htons(port);
1393 static void http_fire_observers(struct http_channel *c)
1395 http_channel_observer_t p = c->observers;
1398 p->destroy(p->data, c, p->data2);
1403 static void http_destroy_observers(struct http_channel *c)
1405 while (c->observers)
1407 http_channel_observer_t obs = c->observers;
1408 c->observers = obs->next;
1413 http_channel_observer_t http_add_observer(struct http_channel *c, void *data,
1414 http_channel_destroy_t des)
1416 http_channel_observer_t obs = xmalloc(sizeof(*obs));
1421 obs->next = c->observers;
1426 void http_remove_observer(http_channel_observer_t obs)
1428 struct http_channel *c = obs->chan;
1429 http_channel_observer_t found, *p = &c->observers;
1438 struct http_channel *http_channel_observer_chan(http_channel_observer_t obs)
1443 void http_observer_set_data2(http_channel_observer_t obs, void *data2)
1448 http_server_t http_server_create(void)
1450 http_server_t hs = xmalloc(sizeof(*hs));
1454 hs->http_sessions = 0;
1456 hs->record_file = 0;
1460 void http_server_destroy(http_server_t hs)
1466 yaz_mutex_enter(hs->mutex); /* OK: hs->mutex may be NULL */
1467 r = --(hs->ref_count);
1468 yaz_mutex_leave(hs->mutex);
1472 http_sessions_destroy(hs->http_sessions);
1473 xfree(hs->proxy_addr);
1474 yaz_mutex_destroy(&hs->mutex);
1475 if (hs->record_file)
1476 fclose(hs->record_file);
1482 void http_server_incref(http_server_t hs)
1485 yaz_mutex_enter(hs->mutex);
1487 yaz_mutex_leave(hs->mutex);
1490 void http_mutex_init(struct conf_server *server)
1494 assert(server->http_server->mutex == 0);
1495 pazpar2_mutex_create(&server->http_server->mutex, "http_server");
1496 server->http_server->http_sessions = http_sessions_create();
1502 * c-file-style: "Stroustrup"
1503 * indent-tabs-mode: nil
1505 * vim: shiftwidth=4 tabstop=8 expandtab