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;
84 static int log_level_post = 0;
86 static void proxy_io(IOCHAN i, int event);
87 static struct http_channel *http_channel_create(http_server_t http_server,
89 struct conf_server *server);
90 static void http_channel_destroy(IOCHAN i);
91 static http_server_t http_server_create(void);
92 static void http_server_incref(http_server_t hs);
95 #define CLOSESOCKET(x) closesocket(x)
97 #define CLOSESOCKET(x) close(x)
105 http_sessions_t http_sessions;
106 struct sockaddr_in *proxy_addr;
110 struct http_channel_observer_s {
113 http_channel_destroy_t destroy;
114 struct http_channel_observer_s *next;
115 struct http_channel *chan;
119 const char *http_lookup_header(struct http_header *header,
122 for (; header; header = header->next)
123 if (!strcasecmp(name, header->name))
124 return header->value;
128 static struct http_buf *http_buf_create(http_server_t hs)
130 struct http_buf *r = xmalloc(sizeof(*r));
137 static void http_buf_destroy(http_server_t hs, struct http_buf *b)
142 static void http_buf_destroy_queue(http_server_t hs, struct http_buf *b)
148 http_buf_destroy(hs, b);
153 static struct http_buf *http_buf_bybuf(http_server_t hs, char *b, int len)
155 struct http_buf *res = 0;
156 struct http_buf **p = &res;
161 if (tocopy > HTTP_BUF_SIZE)
162 tocopy = HTTP_BUF_SIZE;
163 *p = http_buf_create(hs);
164 memcpy((*p)->buf, b, tocopy);
173 // Add a (chain of) buffers to the end of an existing queue.
174 static void http_buf_enqueue(struct http_buf **queue, struct http_buf *b)
177 queue = &(*queue)->next;
181 static struct http_buf *http_buf_bywrbuf(http_server_t hs, WRBUF wrbuf)
183 // Heavens to Betsy (buf)!
184 return http_buf_bybuf(hs, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
187 // Non-destructively collapse chain of buffers into a string (max *len)
189 static void http_buf_peek(struct http_buf *b, char *buf, int len)
192 while (b && rd < len)
194 int toread = len - rd;
197 memcpy(buf + rd, b->buf + b->offset, toread);
204 static int http_buf_size(struct http_buf *b)
207 for (; b; b = b->next)
212 // Ddestructively munch up to len from head of queue.
213 static int http_buf_read(http_server_t hs,
214 struct http_buf **b, char *buf, int len)
217 while ((*b) && rd < len)
219 int toread = len - rd;
220 if (toread > (*b)->len)
222 memcpy(buf + rd, (*b)->buf + (*b)->offset, toread);
224 if (toread < (*b)->len)
227 (*b)->offset += toread;
232 struct http_buf *n = (*b)->next;
233 http_buf_destroy(hs, *b);
241 // Buffers may overlap.
242 static void urldecode(char *i, char *o)
251 else if (*i == '%' && i[1] && i[2])
255 sscanf(i, "%2x", &v);
265 // Warning: Buffers may not overlap
266 void urlencode(const char *i, char *o)
270 if (strchr(" /:", *i))
272 sprintf(o, "%%%.2X", (int) *i);
282 void http_addheader(struct http_response *r, const char *name, const char *value)
284 struct http_channel *c = r->channel;
285 struct http_header *h = nmem_malloc(c->nmem, sizeof *h);
286 h->name = nmem_strdup(c->nmem, name);
287 h->value = nmem_strdup(c->nmem, value);
288 h->next = r->headers;
292 const char *http_argbyname(struct http_request *r, const char *name)
294 struct http_argument *p;
297 for (p = r->arguments; p; p = p->next)
298 if (!strcmp(p->name, name))
303 const char *http_headerbyname(struct http_header *h, const char *name)
305 for (; h; h = h->next)
306 if (!strcmp(h->name, name))
311 struct http_response *http_create_response(struct http_channel *c)
313 struct http_response *r = nmem_malloc(c->nmem, sizeof(*r));
314 strcpy(r->code, "200");
319 r->content_type = "text/xml";
324 static const char *next_crlf(const char *cp, size_t *skipped)
326 const char *next_cp = strchr(cp, '\n');
329 if (next_cp > cp && next_cp[-1] == '\r')
330 *skipped = next_cp - cp - 1;
332 *skipped = next_cp - cp;
338 // Check if buf contains a package (minus payload)
339 static int package_check(const char *buf, int sz)
347 const char *b = next_crlf(buf, &skipped);
351 // we did not find CRLF.. See if buffer is too large..
352 if (sz >= MAX_HTTP_HEADER-1)
353 return MAX_HTTP_HEADER-1; // yes. Return that (will fail later)
359 // CRLF CRLF , i.e. end of header
360 if (len + content_len <= sz)
361 return len + content_len;
365 // following first skip of \r\n so that we don't consider Method
366 if (!strncasecmp(buf, "Content-Length:", 15))
368 const char *cp = buf+15;
372 while (*cp && isdigit(*(const unsigned char *)cp))
373 content_len = content_len*10 + (*cp++ - '0');
374 if (content_len < 0) /* prevent negative offsets */
378 return 0; // incomplete request
381 // Check if we have a request. Return 0 or length
382 static int request_check(struct http_buf *queue)
384 char tmp[MAX_HTTP_HEADER];
386 // only peek at the header..
387 http_buf_peek(queue, tmp, MAX_HTTP_HEADER-1);
388 // still we only return non-zero if the complete request is received..
389 return package_check(tmp, http_buf_size(queue));
392 struct http_response *http_parse_response_buf(struct http_channel *c, const char *buf, int len)
394 char tmp[MAX_HTTP_HEADER];
395 struct http_response *r = http_create_response(c);
397 struct http_header **hp = &r->headers;
399 if (len >= MAX_HTTP_HEADER)
401 memcpy(tmp, buf, len);
402 for (p = tmp; *p && *p != ' '; p++) // Skip HTTP version
406 for (p2 = p; *p2 && *p2 != ' ' && p2 - p < 3; p2++)
407 r->code[p2 - p] = *p2;
408 if (!(p = strstr(tmp, "\r\n")))
413 if (!(p2 = strstr(p, "\r\n")))
415 if (p == p2) // End of headers
419 struct http_header *h = *hp = nmem_malloc(c->nmem, sizeof(*h));
420 char *value = strchr(p, ':');
424 h->name = nmem_strdup(c->nmem, p);
425 while (isspace(*(const unsigned char *) value))
427 if (value >= p2) // Empty header;
434 h->value = nmem_strdup(c->nmem, value);
443 static int http_parse_arguments(struct http_request *r, NMEM nmem,
446 const char *p2 = args;
450 struct http_argument *a;
451 const char *equal = strchr(p2, '=');
452 const char *eoa = strchr(p2, '&');
455 yaz_log(YLOG_WARN, "Expected '=' in argument");
459 eoa = equal + strlen(equal); // last argument
460 else if (equal > eoa)
462 yaz_log(YLOG_WARN, "Missing '&' in argument");
465 a = nmem_malloc(nmem, sizeof(struct http_argument));
466 a->name = nmem_strdupn(nmem, p2, equal - p2);
467 a->value = nmem_strdupn(nmem, equal+1, eoa - equal - 1);
468 urldecode(a->name, a->name);
469 urldecode(a->value, a->value);
470 a->next = r->arguments;
479 struct http_request *http_parse_request(struct http_channel *c,
480 struct http_buf **queue,
483 struct http_request *r = nmem_malloc(c->nmem, sizeof(*r));
485 char *start = nmem_malloc(c->nmem, len+1);
488 if (http_buf_read(c->http_server, queue, buf, len) < len)
490 yaz_log(YLOG_WARN, "http_buf_read < len (%d)", len);
500 for (p = buf, p2 = r->method; *p && *p != ' ' && p - buf < 19; p++)
504 yaz_log(YLOG_WARN, "Unexpected HTTP method in request");
509 if (!(buf = strchr(buf, ' ')))
511 yaz_log(YLOG_WARN, "Missing Request-URI in HTTP request");
515 if (!(p = strchr(buf, ' ')))
517 yaz_log(YLOG_WARN, "HTTP Request-URI not terminated (too long?)");
521 if ((p2 = strchr(buf, '?'))) // Do we have arguments?
523 r->path = nmem_strdup(c->nmem, buf);
526 r->search = nmem_strdup(c->nmem, p2);
528 http_parse_arguments(r, c->nmem, p2);
532 if (strncmp(buf, "HTTP/", 5))
533 strcpy(r->http_version, "1.0");
537 buf += 5; // strlen("HTTP/")
539 p = (char*) next_crlf(buf, &skipped);
540 if (!p || skipped < 3 || skipped > 5)
543 memcpy(r->http_version, buf, skipped);
544 r->http_version[skipped] = '\0';
547 strcpy(c->version, r->http_version);
554 p = (char *) next_crlf(buf, &skipped);
559 else if (skipped == 0)
567 char *n_v = nmem_malloc(c->nmem, skipped+1);
568 struct http_header *h = nmem_malloc(c->nmem, sizeof(*h));
570 memcpy(n_v, buf, skipped);
573 if (!(cp = strchr(n_v, ':')))
575 h->name = nmem_strdupn(c->nmem, n_v, cp - n_v);
579 h->value = nmem_strdup(c->nmem, cp);
580 h->next = r->headers;
586 // determine if we do keep alive
587 if (!strcmp(c->version, "1.0"))
589 const char *v = http_lookup_header(r->headers, "Connection");
590 if (v && !strcmp(v, "Keep-Alive"))
597 const char *v = http_lookup_header(r->headers, "Connection");
598 if (v && !strcmp(v, "close"))
603 if (buf < start + len)
605 const char *content_type = http_lookup_header(r->headers,
607 r->content_len = start + len - buf;
608 r->content_buf = buf;
611 !yaz_strcmp_del("application/x-www-form-urlencoded",
614 http_parse_arguments(r, c->nmem, r->content_buf);
620 static struct http_buf *http_serialize_response(struct http_channel *c,
621 struct http_response *r)
623 struct http_header *h;
625 wrbuf_rewind(c->wrbuf);
627 wrbuf_printf(c->wrbuf, "HTTP/%s %s %s\r\n", c->version, r->code, r->msg);
628 for (h = r->headers; h; h = h->next)
629 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
632 wrbuf_printf(c->wrbuf, "Content-Length: %d\r\n", r->payload ?
633 (int) strlen(r->payload) : 0);
634 wrbuf_printf(c->wrbuf, "Content-Type: %s\r\n", r->content_type);
635 if (!strcmp(r->content_type, "text/xml"))
637 xmlDoc *doc = xmlParseMemory(r->payload, strlen(r->payload));
644 yaz_log(YLOG_WARN, "Sending non-wellformed "
645 "response (bug #1162");
646 yaz_log(YLOG_WARN, "payload: %s", r->payload);
650 wrbuf_puts(c->wrbuf, "\r\n");
653 wrbuf_puts(c->wrbuf, r->payload);
655 if (global_parameters.dump_records > 1)
657 FILE *lf = yaz_log_file();
658 yaz_log(YLOG_LOG, "Response:");
659 fwrite(wrbuf_buf(c->wrbuf), 1, wrbuf_len(c->wrbuf), lf);
662 return http_buf_bywrbuf(c->http_server, c->wrbuf);
665 // Serialize a HTTP request
666 static struct http_buf *http_serialize_request(struct http_request *r)
668 struct http_channel *c = r->channel;
669 struct http_header *h;
671 wrbuf_rewind(c->wrbuf);
672 wrbuf_printf(c->wrbuf, "%s %s%s%s", r->method, r->path,
673 *r->search ? "?" : "", r->search);
675 wrbuf_printf(c->wrbuf, " HTTP/%s\r\n", r->http_version);
677 for (h = r->headers; h; h = h->next)
678 wrbuf_printf(c->wrbuf, "%s: %s\r\n", h->name, h->value);
680 wrbuf_puts(c->wrbuf, "\r\n");
683 wrbuf_write(c->wrbuf, r->content_buf, r->content_len);
686 yaz_log(YLOG_LOG, "WRITING TO PROXY:\n%s\n----",
687 wrbuf_cstr(c->wrbuf));
689 return http_buf_bywrbuf(c->http_server, c->wrbuf);
693 static int http_weshouldproxy(struct http_request *rq)
695 struct http_channel *c = rq->channel;
696 if (c->server->http_server->proxy_addr && !strstr(rq->path, "search.pz2"))
702 struct http_header * http_header_append(struct http_channel *ch,
703 struct http_header * hp,
707 struct http_header *hpnew = 0;
712 while (hp && hp->next)
715 if(name && strlen(name)&& value && strlen(value)){
716 hpnew = nmem_malloc(ch->nmem, sizeof *hpnew);
717 hpnew->name = nmem_strdup(ch->nmem, name);
718 hpnew->value = nmem_strdup(ch->nmem, value);
731 static int is_inprogress(void)
734 if (WSAGetLastError() == WSAEWOULDBLOCK)
737 if (errno == EINPROGRESS)
743 static void enable_nonblock(int sock)
747 flags = (flags & CS_FLAGS_BLOCKING) ? 0 : 1;
748 if (ioctlsocket(sock, FIONBIO, &flags) < 0)
749 yaz_log(YLOG_FATAL|YLOG_ERRNO, "ioctlsocket");
751 if ((flags = fcntl(sock, F_GETFL, 0)) < 0)
752 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl");
753 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0)
754 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fcntl2");
758 static int http_proxy(struct http_request *rq)
760 struct http_channel *c = rq->channel;
761 struct http_proxy *p = c->proxy;
762 struct http_header *hp;
763 struct http_buf *requestbuf;
764 struct conf_server *ser = c->server;
766 if (!p) // This is a new connection. Create a proxy channel
772 if (!(pe = getprotobyname("tcp"))) {
775 if ((sock = socket(PF_INET, SOCK_STREAM, pe->p_proto)) < 0)
777 yaz_log(YLOG_WARN|YLOG_ERRNO, "socket");
780 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)
781 &one, sizeof(one)) < 0)
783 enable_nonblock(sock);
784 if (connect(sock, (struct sockaddr *)
785 c->server->http_server->proxy_addr,
786 sizeof(*c->server->http_server->proxy_addr)) < 0)
788 if (!is_inprogress())
790 yaz_log(YLOG_WARN|YLOG_ERRNO, "Proxy connect");
794 p = xmalloc(sizeof(struct http_proxy));
797 p->first_response = 1;
799 p->iochan = iochan_create(sock, proxy_io, EVENT_INPUT, "http_proxy");
800 iochan_setdata(p->iochan, p);
802 if (iochan_add(ser->iochan_man, p->iochan))
804 iochan_destroy(p->iochan);
810 // Do _not_ modify Host: header, just checking it's existence
812 if (!http_lookup_header(rq->headers, "Host"))
814 yaz_log(YLOG_WARN, "Failed to find Host header in proxy");
818 // Add new header about paraz2 version, host, remote client address, etc.
820 char server_via[128];
823 hp = http_header_append(c, hp,
824 "X-Pazpar2-Version", PACKAGE_VERSION);
825 hp = http_header_append(c, hp,
826 "X-Pazpar2-Server-Host", ser->host);
827 hp = http_header_append(c, hp,
828 "X-Pazpar2-Server-Port", ser->port);
829 yaz_snprintf(server_via, sizeof(server_via),
831 ser->host, ser->port,
832 PACKAGE_NAME, PACKAGE_VERSION);
833 hp = http_header_append(c, hp, "Via" , server_via);
834 hp = http_header_append(c, hp, "X-Forwarded-For", c->addr);
837 requestbuf = http_serialize_request(rq);
839 http_buf_enqueue(&p->oqueue, requestbuf);
840 iochan_setflag(p->iochan, EVENT_OUTPUT);
844 void http_send_response(struct http_channel *ch)
846 struct http_response *rs = ch->response;
849 yaz_timing_stop(ch->yt);
852 yaz_log(YLOG_LOG, "Response: %6.5f %d %s%s%s ",
853 yaz_timing_get_real(ch->yt),
854 iochan_getfd(ch->iochan),
856 *ch->request->search ? "?" : "",
857 ch->request->search);
860 hb = http_serialize_response(ch, rs);
863 yaz_log(YLOG_WARN, "Failed to serialize HTTP response");
864 http_channel_destroy(ch->iochan);
868 http_buf_enqueue(&ch->oqueue, hb);
869 iochan_setflag(ch->iochan, EVENT_OUTPUT);
870 ch->state = Http_Idle;
874 static void http_error(struct http_channel *hc, int no, const char *msg)
876 struct http_response *rs = http_create_response(hc);
879 hc->keep_alive = 0; // not keeping this HTTP session alive
881 sprintf(rs->code, "%d", no);
883 rs->msg = nmem_strdup(hc->nmem, msg);
884 rs->payload = nmem_malloc(hc->nmem, 100);
885 yaz_snprintf(rs->payload, 99, "<error>HTTP Error %d: %s</error>\n",
887 http_send_response(hc);
890 static void http_io(IOCHAN i, int event)
892 struct http_channel *hc = iochan_getdata(i);
895 if (event == EVENT_INPUT)
898 struct http_buf *htbuf;
900 htbuf = http_buf_create(hc->http_server);
901 res = recv(iochan_getfd(i), htbuf->buf, HTTP_BUF_SIZE -1, 0);
902 if (res == -1 && errno == EAGAIN)
904 http_buf_destroy(hc->http_server, htbuf);
910 if (hc->http_server->record_file)
913 gettimeofday(&tv, 0);
914 fprintf(hc->http_server->record_file, "r %lld %lld %lld 0\n",
915 (long long) tv.tv_sec, (long long) tv.tv_usec,
916 (long long) iochan_getfd(i));
919 http_buf_destroy(hc->http_server, htbuf);
920 fflush(hc->http_server->record_file);
921 http_channel_destroy(i);
924 htbuf->buf[res] = '\0';
926 http_buf_enqueue(&hc->iqueue, htbuf);
930 if (hc->state == Http_Busy)
932 reqlen = request_check(hc->iqueue);
935 // we have a complete HTTP request
936 nmem_reset(hc->nmem);
938 if (hc->http_server->record_file)
943 for (hb = hc->iqueue; hb; hb = hb->next)
945 gettimeofday(&tv, 0);
946 fprintf(hc->http_server->record_file, "r %lld %lld %lld %d\n",
947 (long long) tv.tv_sec, (long long) tv.tv_usec,
948 (long long) iochan_getfd(i), sz);
949 for (hb = hc->iqueue; hb; hb = hb->next)
950 fwrite(hb->buf, 1, hb->len, hc->http_server->record_file);
951 fflush(hc->http_server->record_file);
954 yaz_timing_start(hc->yt);
955 if (!(hc->request = http_parse_request(hc, &hc->iqueue, reqlen)))
957 yaz_log(YLOG_WARN, "Failed to parse request");
958 http_error(hc, 400, "Bad Request");
962 yaz_log(YLOG_LOG, "Request: - %d %s %s%s%s",
966 *hc->request->search ? "?" : "",
967 hc->request->search);
968 if (hc->request->content_buf && log_level_post)
969 yaz_log(log_level_post, "%s", hc->request->content_buf);
970 if (http_weshouldproxy(hc->request))
971 http_proxy(hc->request);
974 // Execute our business logic!
975 hc->state = Http_Busy;
980 else if (event == EVENT_OUTPUT)
985 struct http_buf *wb = hc->oqueue;
987 res = send(iochan_getfd(hc->iochan),
988 wb->buf + wb->offset, wb->len, 0);
991 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
992 http_channel_destroy(i);
998 if (hc->http_server->record_file)
1001 int sz = wb->offset + wb->len;
1002 gettimeofday(&tv, 0);
1003 fprintf(hc->http_server->record_file, "w %lld %lld %lld %d\n",
1004 (long long) tv.tv_sec, (long long) tv.tv_usec,
1005 (long long) iochan_getfd(i), sz);
1006 fwrite(wb->buf, 1, wb->offset + wb->len,
1007 hc->http_server->record_file);
1008 fflush(hc->http_server->record_file);
1011 hc->oqueue = hc->oqueue->next;
1012 http_buf_destroy(hc->http_server, wb);
1021 if (!hc->keep_alive)
1023 http_channel_destroy(i);
1028 iochan_clearflag(i, EVENT_OUTPUT);
1030 event = EVENT_INPUT;
1034 if (!hc->oqueue && hc->proxy && !hc->proxy->iochan)
1035 http_channel_destroy(i); // Server closed; we're done
1039 yaz_log(YLOG_WARN, "Unexpected event on connection");
1040 http_channel_destroy(i);
1046 // Handles I/O on a client connection to a backend web server (proxy mode)
1047 static void proxy_io(IOCHAN pi, int event)
1049 struct http_proxy *pc = iochan_getdata(pi);
1050 struct http_channel *hc = pc->channel;
1055 struct http_buf *htbuf;
1058 htbuf = http_buf_create(hc->http_server);
1059 res = recv(iochan_getfd(pi), htbuf->buf, HTTP_BUF_SIZE -1, 0);
1060 if (res == 0 || (res < 0 && !is_inprogress()))
1064 yaz_log(YLOG_WARN, "Proxy read came up short");
1065 // Close channel and alert client HTTP channel that we're gone
1066 http_buf_destroy(hc->http_server, htbuf);
1067 CLOSESOCKET(iochan_getfd(pi));
1073 http_channel_destroy(hc->iochan);
1079 htbuf->buf[res] = '\0';
1082 // Write any remaining payload
1083 if (htbuf->len - htbuf->offset > 0)
1084 http_buf_enqueue(&hc->oqueue, htbuf);
1086 iochan_setflag(hc->iochan, EVENT_OUTPUT);
1089 if (!(htbuf = pc->oqueue))
1091 iochan_clearflag(pi, EVENT_OUTPUT);
1094 res = send(iochan_getfd(pi), htbuf->buf + htbuf->offset, htbuf->len, 0);
1097 yaz_log(YLOG_WARN|YLOG_ERRNO, "write");
1098 http_channel_destroy(hc->iochan);
1101 if (res == htbuf->len)
1103 struct http_buf *np = htbuf->next;
1104 http_buf_destroy(hc->http_server, htbuf);
1110 htbuf->offset += res;
1114 iochan_setflags(pi, EVENT_INPUT); // Turns off output flag
1118 yaz_log(YLOG_WARN, "Unexpected event on connection");
1119 http_channel_destroy(hc->iochan);
1124 static void http_fire_observers(struct http_channel *c);
1125 static void http_destroy_observers(struct http_channel *c);
1128 static void http_channel_destroy(IOCHAN i)
1130 struct http_channel *s = iochan_getdata(i);
1131 http_server_t http_server;
1135 if (s->proxy->iochan)
1137 CLOSESOCKET(iochan_getfd(s->proxy->iochan));
1138 iochan_destroy(s->proxy->iochan);
1140 http_buf_destroy_queue(s->http_server, s->proxy->oqueue);
1143 yaz_timing_destroy(&s->yt);
1144 http_buf_destroy_queue(s->http_server, s->iqueue);
1145 http_buf_destroy_queue(s->http_server, s->oqueue);
1146 http_fire_observers(s);
1147 http_destroy_observers(s);
1149 http_server = s->http_server; /* save it for destroy (decref) */
1151 http_server_destroy(http_server);
1153 CLOSESOCKET(iochan_getfd(i));
1156 nmem_destroy(s->nmem);
1157 wrbuf_destroy(s->wrbuf);
1161 static struct http_channel *http_channel_create(http_server_t hs,
1163 struct conf_server *server)
1165 struct http_channel *r;
1167 r = xmalloc(sizeof(struct http_channel));
1168 r->nmem = nmem_create();
1169 r->wrbuf = wrbuf_alloc();
1171 http_server_incref(hs);
1172 r->http_server = hs;
1173 r->http_sessions = hs->http_sessions;
1174 assert(r->http_sessions);
1178 r->iqueue = r->oqueue = 0;
1179 r->state = Http_Idle;
1183 strcpy(r->version, "1.0");
1186 yaz_log(YLOG_WARN, "Invalid HTTP forward address");
1189 strcpy(r->addr, addr);
1191 r->yt = yaz_timing_create();
1196 /* Accept a new command connection */
1197 static void http_accept(IOCHAN i, int event)
1200 struct sockaddr_storage addr;
1201 int fd = iochan_getfd(i);
1202 socklen_t len = sizeof addr;
1205 struct http_channel *ch;
1206 struct conf_server *server = iochan_getdata(i);
1208 if ((s = accept(fd, (struct sockaddr *) &addr, &len)) < 0)
1210 yaz_log(YLOG_WARN|YLOG_ERRNO, "accept");
1213 if (getnameinfo((struct sockaddr *) &addr, len, host, sizeof(host)-1, 0, 0,
1216 yaz_log(YLOG_WARN|YLOG_ERRNO, "getnameinfo");
1222 yaz_log(YLOG_DEBUG, "New command connection");
1223 c = iochan_create(s, http_io, EVENT_INPUT | EVENT_EXCEPT,
1224 "http_session_socket");
1226 ch = http_channel_create(server->http_server, host, server);
1228 iochan_setdata(c, ch);
1229 if (iochan_add(server->iochan_man, c))
1231 http_channel_destroy(c);
1235 /* Create a http-channel listener, syntax [host:]port */
1236 int http_init(struct conf_server *server, const char *record_fname)
1241 FILE *record_file = 0;
1242 struct addrinfo hints, *af = 0, *ai;
1246 yaz_log(YLOG_LOG, "HTTP listener %s:%s", server->host, server->port);
1249 hints.ai_family = AF_UNSPEC;
1250 hints.ai_socktype = SOCK_STREAM;
1251 hints.ai_protocol = 0;
1252 hints.ai_addrlen = 0;
1253 hints.ai_addr = NULL;
1254 hints.ai_canonname = NULL;
1255 hints.ai_next = NULL;
1257 if (!strcmp(server->host, "@"))
1260 hints.ai_flags = AI_PASSIVE;
1261 error = getaddrinfo(0, server->port, &hints, &af);
1264 error = getaddrinfo(server->host, server->port, &hints, &af);
1268 yaz_log(YLOG_FATAL, "Failed to resolve %s: %s", server->host,
1269 gai_strerror(error));
1272 for (ai = af; ai; ai = ai->ai_next)
1274 if (ai->ai_family == AF_INET6)
1276 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1283 for (ai = af; ai; ai = ai->ai_next)
1285 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1292 yaz_log(YLOG_FATAL|YLOG_ERRNO, "socket");
1296 if (ipv6_only >= 0 && ai->ai_family == AF_INET6 &&
1297 setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_only, sizeof(ipv6_only)))
1299 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setsockopt IPV6_V6ONLY %s:%s %d",
1300 server->host, server->port, ipv6_only);
1305 if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)))
1307 yaz_log(YLOG_FATAL|YLOG_ERRNO, "setsockopt SO_REUSEADDR %s:%s",
1308 server->host, server->port);
1313 if (bind(s, ai->ai_addr, ai->ai_addrlen) < 0)
1315 yaz_log(YLOG_FATAL|YLOG_ERRNO, "bind %s:%s",
1316 server->host, server->port);
1322 if (listen(s, SOMAXCONN) < 0)
1324 yaz_log(YLOG_FATAL|YLOG_ERRNO, "listen %s:%s",
1325 server->host, server->port);
1332 record_file = fopen(record_fname, "wb");
1335 yaz_log(YLOG_FATAL|YLOG_ERRNO, "fopen %s", record_fname);
1341 c = iochan_create(s, http_accept, EVENT_INPUT|EVENT_EXCEPT, "http_server");
1342 if (iochan_add(server->iochan_man, c))
1348 server->http_server = http_server_create();
1349 server->http_server->record_file = record_file;
1350 server->http_server->listener_socket = s;
1351 iochan_setdata(c, server);
1356 void http_close_server(struct conf_server *server)
1358 /* break the event_loop (select) by closing down the HTTP listener sock */
1359 if (server->http_server->listener_socket)
1362 closesocket(server->http_server->listener_socket);
1364 close(server->http_server->listener_socket);
1369 void http_set_proxyaddr(const char *host, struct conf_server *server)
1374 WRBUF w = wrbuf_alloc();
1376 yaz_log(YLOG_LOG, "HTTP backend %s", host);
1378 p = strchr(host, ':');
1382 wrbuf_write(w, host, p - host);
1388 wrbuf_puts(w, host);
1390 if (!(he = gethostbyname(wrbuf_cstr(w))))
1392 fprintf(stderr, "Failed to lookup '%s'\n", wrbuf_cstr(w));
1397 server->http_server->proxy_addr = xmalloc(sizeof(struct sockaddr_in));
1398 server->http_server->proxy_addr->sin_family = he->h_addrtype;
1399 memcpy(&server->http_server->proxy_addr->sin_addr.s_addr,
1400 he->h_addr_list[0], he->h_length);
1401 server->http_server->proxy_addr->sin_port = htons(port);
1404 static void http_fire_observers(struct http_channel *c)
1406 http_channel_observer_t p = c->observers;
1409 p->destroy(p->data, c, p->data2);
1414 static void http_destroy_observers(struct http_channel *c)
1416 while (c->observers)
1418 http_channel_observer_t obs = c->observers;
1419 c->observers = obs->next;
1424 http_channel_observer_t http_add_observer(struct http_channel *c, void *data,
1425 http_channel_destroy_t des)
1427 http_channel_observer_t obs = xmalloc(sizeof(*obs));
1432 obs->next = c->observers;
1437 void http_remove_observer(http_channel_observer_t obs)
1439 struct http_channel *c = obs->chan;
1440 http_channel_observer_t found, *p = &c->observers;
1449 struct http_channel *http_channel_observer_chan(http_channel_observer_t obs)
1454 void http_observer_set_data2(http_channel_observer_t obs, void *data2)
1459 http_server_t http_server_create(void)
1461 http_server_t hs = xmalloc(sizeof(*hs));
1465 hs->http_sessions = 0;
1466 hs->record_file = 0;
1468 log_level_post = yaz_log_module_level("post");
1473 void http_server_destroy(http_server_t hs)
1479 yaz_mutex_enter(hs->mutex); /* OK: hs->mutex may be NULL */
1480 r = --(hs->ref_count);
1481 yaz_mutex_leave(hs->mutex);
1485 http_sessions_destroy(hs->http_sessions);
1486 xfree(hs->proxy_addr);
1487 yaz_mutex_destroy(&hs->mutex);
1488 if (hs->record_file)
1489 fclose(hs->record_file);
1495 void http_server_incref(http_server_t hs)
1498 yaz_mutex_enter(hs->mutex);
1500 yaz_mutex_leave(hs->mutex);
1503 void http_mutex_init(struct conf_server *server)
1507 assert(server->http_server->mutex == 0);
1508 pazpar2_mutex_create(&server->http_server->mutex, "http_server");
1509 server->http_server->http_sessions = http_sessions_create();
1515 * c-file-style: "Stroustrup"
1516 * indent-tabs-mode: nil
1518 * vim: shiftwidth=4 tabstop=8 expandtab