2 * copyright (c) 2001-2012 Emil Mikulic.
4 * http.c: embedded webserver.
5 * This borrows a lot of code from darkhttpd.
7 * You may use, modify and redistribute this file under the terms of the
8 * GNU General Public License version 2. (see COPYING.GPL)
23 #include <sys/socket.h>
24 #include <arpa/inet.h>
25 #include <netinet/in.h>
40 static const char mime_type_xml
[] = "text/xml";
41 static const char mime_type_html
[] = "text/html; charset=us-ascii";
42 static const char mime_type_css
[] = "text/css";
43 static const char mime_type_js
[] = "text/javascript";
44 static const char encoding_identity
[] = "identity";
45 static const char encoding_gzip
[] = "gzip";
47 static const char server
[] = PACKAGE_NAME
"/" PACKAGE_VERSION
;
48 static int idletime
= 60;
49 #define MAX_REQUEST_LENGTH 4000
51 static int *insocks
= NULL
;
52 static unsigned int insock_num
= 0;
55 LIST_ENTRY(connection
) entries
;
58 struct sockaddr_storage client
;
59 long last_active_mono
;
61 RECV_REQUEST
, /* receiving request */
62 SEND_HEADER_AND_REPLY
, /* try to send header+reply together */
63 SEND_HEADER
, /* sending generated header */
64 SEND_REPLY
, /* sending reply */
65 DONE
/* conn closed, need to remove from queue */
68 /* char request[request_length+1] is null-terminated */
70 size_t request_length
;
74 char *method
, *uri
, *query
; /* query can be NULL */
77 const char *mime_type
, *encoding
, *header_extra
;
78 size_t header_length
, header_sent
;
79 int header_dont_free
, header_only
, http_code
;
83 size_t reply_length
, reply_sent
;
85 unsigned int total_sent
; /* header + body = total, for logging */
88 static LIST_HEAD(conn_list_head
, connection
) connlist
=
89 LIST_HEAD_INITIALIZER(conn_list_head
);
91 struct bindaddr_entry
{
92 STAILQ_ENTRY(bindaddr_entry
) entries
;
95 static STAILQ_HEAD(bindaddrs_head
, bindaddr_entry
) bindaddrs
=
96 STAILQ_HEAD_INITIALIZER(bindaddrs
);
98 /* ---------------------------------------------------------------------------
99 * Decode URL by converting %XX (where XX are hexadecimal digits) to the
100 * character it represents. Don't forget to free the return value.
102 static char *urldecode(const char *url
)
104 size_t i
, len
= strlen(url
);
105 char *out
= xmalloc(len
+1);
108 for (i
=0, pos
=0; i
<len
; i
++)
110 if (url
[i
] == '%' && i
+2 < len
&&
111 isxdigit(url
[i
+1]) && isxdigit(url
[i
+2]))
114 #define HEX_TO_DIGIT(hex) ( \
115 ((hex) >= 'A' && (hex) <= 'F') ? ((hex)-'A'+10): \
116 ((hex) >= 'a' && (hex) <= 'f') ? ((hex)-'a'+10): \
119 out
[pos
++] = HEX_TO_DIGIT(url
[i
+1]) * 16 +
120 HEX_TO_DIGIT(url
[i
+2]);
133 /* don't really need to realloc here - it's probably a performance hit */
134 out
= xrealloc(out
, strlen(out
)+1); /* dealloc what we don't need */
141 /* ---------------------------------------------------------------------------
142 * Consolidate slashes in-place by shifting parts of the string over repeated
145 static void consolidate_slashes(char *s
)
147 size_t left
= 0, right
= 0;
152 while (s
[right
] != '\0')
156 if (s
[right
] == '/') right
++;
160 s
[left
++] = s
[right
++];
165 if (s
[right
] == '/') saw_slash
++;
166 s
[left
++] = s
[right
++];
174 /* ---------------------------------------------------------------------------
175 * Resolve /./ and /../ in a URI, returing a new, safe URI, or NULL if the URI
176 * is invalid/unsafe. Returned buffer needs to be deallocated.
178 static char *make_safe_uri(char *uri
)
181 unsigned int slashes
= 0, elements
= 0;
182 size_t urilen
, i
, j
, pos
;
187 consolidate_slashes(uri
);
188 urilen
= strlen(uri
);
190 /* count the slashes */
191 for (i
=0, slashes
=0; i
<urilen
; i
++)
192 if (uri
[i
] == '/') slashes
++;
194 /* make an array for the URI elements */
195 elem
= xmalloc(sizeof(*elem
) * slashes
);
196 for (i
=0; i
<slashes
; i
++)
199 /* split by slashes and build elem[] array */
202 /* look for the next slash */
203 for (j
=i
; j
<urilen
&& uri
[j
] != '/'; j
++)
206 /* process uri[i,j) */
207 if ((j
== i
+1) && (uri
[i
] == '.'))
209 else if ((j
== i
+2) && (uri
[i
] == '.') && (uri
[i
+1] == '.'))
215 * Unsafe string so free elem[]. All its elements are free
224 free(elem
[elements
]);
227 else elem
[elements
++] = split_string(uri
, i
, j
);
229 i
= j
+ 1; /* uri[j] is a slash - move along one */
233 out
= xmalloc(urilen
+1); /* it won't expand */
235 for (i
=0; i
<elements
; i
++)
237 size_t delta
= strlen(elem
[i
]);
239 assert(pos
<= urilen
);
242 assert(pos
+delta
<= urilen
);
243 memcpy(out
+pos
, elem
[i
], delta
);
249 if ((elements
== 0) || (uri
[urilen
-1] == '/')) out
[pos
++] = '/';
250 assert(pos
<= urilen
);
254 /* don't really need to do this and it's probably a performance hit: */
255 /* shorten buffer if necessary */
256 if (pos
!= urilen
) out
= xrealloc(out
, strlen(out
)+1);
261 /* ---------------------------------------------------------------------------
262 * Allocate and initialize an empty connection.
264 static struct connection
*new_connection(void)
266 struct connection
*conn
= xmalloc(sizeof(*conn
));
269 memset(&conn
->client
, 0, sizeof(conn
->client
));
270 conn
->last_active_mono
= now_mono();
271 conn
->request
= NULL
;
272 conn
->request_length
= 0;
273 conn
->accept_gzip
= 0;
278 conn
->mime_type
= NULL
;
279 conn
->encoding
= NULL
;
280 conn
->header_extra
= "";
281 conn
->header_length
= 0;
282 conn
->header_sent
= 0;
283 conn
->header_dont_free
= 0;
284 conn
->header_only
= 0;
287 conn
->reply_dont_free
= 0;
288 conn
->reply_length
= 0;
289 conn
->reply_sent
= 0;
290 conn
->total_sent
= 0;
292 /* Make it harmless so it gets garbage-collected if it should, for some
293 * reason, fail to be correctly filled out.
302 /* ---------------------------------------------------------------------------
303 * Accept a connection from sockin and add it to the connection queue.
305 static void accept_connection(const int sockin
)
307 struct sockaddr_storage addrin
;
309 struct connection
*conn
;
310 char ipaddr
[INET6_ADDRSTRLEN
], portstr
[12];
313 sin_size
= (socklen_t
)sizeof(addrin
);
314 sock
= accept(sockin
, (struct sockaddr
*)&addrin
, &sin_size
);
317 if (errno
== ECONNABORTED
|| errno
== EINTR
)
319 verbosef("accept() failed: %s", strerror(errno
));
322 /* else */ err(1, "accept()");
325 fd_set_nonblock(sock
);
327 /* allocate and initialise struct connection */
328 conn
= new_connection();
330 conn
->state
= RECV_REQUEST
;
331 memcpy(&conn
->client
, &addrin
, sizeof(conn
->client
));
332 LIST_INSERT_HEAD(&connlist
, conn
, entries
);
334 getnameinfo((struct sockaddr
*) &addrin
, sin_size
,
335 ipaddr
, sizeof(ipaddr
), portstr
, sizeof(portstr
),
336 NI_NUMERICHOST
| NI_NUMERICSERV
);
337 verbosef("accepted connection from %s:%s", ipaddr
, portstr
);
342 /* ---------------------------------------------------------------------------
343 * Log a connection, then cleanly deallocate its internals.
345 static void free_connection(struct connection
*conn
)
347 dverbosef("free_connection(%d)", conn
->socket
);
348 if (conn
->socket
!= -1)
354 if (!conn
->header_dont_free
)
356 if (!conn
->reply_dont_free
)
362 /* ---------------------------------------------------------------------------
363 * Format [when] as an RFC1123 date, stored in the specified buffer. The same
364 * buffer is returned for convenience.
366 #define DATE_LEN 30 /* strlen("Fri, 28 Feb 2003 00:02:08 GMT")+1 */
367 static char *rfc1123_date(char *dest
, time_t when
) {
368 if (strftime(dest
, DATE_LEN
,
369 "%a, %d %b %Y %H:%M:%S %Z", gmtime(&when
) ) == 0)
370 errx(1, "strftime() failed [%s]", dest
);
374 static void generate_header(struct connection
*conn
,
375 const int code
, const char *text
)
379 assert(conn
->header
== NULL
);
380 assert(conn
->mime_type
!= NULL
);
381 if (conn
->encoding
== NULL
)
382 conn
->encoding
= encoding_identity
;
384 verbosef("http: %d %s (%s: %zu bytes)", code
, text
,
385 conn
->encoding
, conn
->reply_length
);
386 conn
->header_length
= xasprintf(&(conn
->header
),
390 "Vary: Accept-Encoding\r\n"
391 "Content-Type: %s\r\n"
392 "Content-Length: %d\r\n"
393 "Content-Encoding: %s\r\n"
394 "X-Robots-Tag: noindex, noarchive\r\n"
399 rfc1123_date(date
, now_real()), server
,
400 conn
->mime_type
, conn
->reply_length
, conn
->encoding
,
402 conn
->http_code
= code
;
407 /* ---------------------------------------------------------------------------
408 * A default reply for any (erroneous) occasion.
410 static void default_reply(struct connection
*conn
,
411 const int errcode
, const char *errname
, const char *format
, ...)
416 va_start(va
, format
);
417 xvasprintf(&reason
, format
, va
);
420 conn
->reply_length
= xasprintf(&(conn
->reply
),
421 "<html><head><title>%d %s</title></head><body>\n"
422 "<h1>%s</h1>\n" /* errname */
427 errcode
, errname
, errname
, reason
, server
);
430 /* forget any dangling metadata */
431 conn
->mime_type
= mime_type_html
;
432 conn
->encoding
= encoding_identity
;
434 generate_header(conn
, errcode
, errname
);
439 /* ---------------------------------------------------------------------------
440 * Parses a single HTTP request field. Returns string from end of [field] to
441 * first \r, \n or end of request string. Returns NULL if [field] can't be
444 * You need to remember to deallocate the result.
445 * example: parse_field(conn, "Referer: ");
447 static char *parse_field(const struct connection
*conn
, const char *field
)
449 size_t bound1
, bound2
;
453 pos
= strstr(conn
->request
, field
);
456 bound1
= pos
- conn
->request
+ strlen(field
);
459 for (bound2
= bound1
;
460 conn
->request
[bound2
] != '\r' &&
461 bound2
< conn
->request_length
; bound2
++)
465 return (split_string(conn
->request
, bound1
, bound2
));
470 /* ---------------------------------------------------------------------------
471 * Parse an HTTP request like "GET /hosts/?sort=in HTTP/1.1" to get the method
472 * (GET), the uri (/hosts/), the query (sort=in) and whether the UA will
473 * accept gzip encoding. Remember to deallocate all these buffers. Query
474 * can be NULL. The method will be returned in uppercase.
476 static int parse_request(struct connection
*conn
)
478 size_t bound1
, bound2
, mid
;
482 for (bound1
= 0; bound1
< conn
->request_length
&&
483 conn
->request
[bound1
] != ' '; bound1
++)
486 conn
->method
= split_string(conn
->request
, 0, bound1
);
487 strntoupper(conn
->method
, bound1
);
490 for (; bound1
< conn
->request_length
&&
491 conn
->request
[bound1
] == ' '; bound1
++)
494 if (bound1
== conn
->request_length
)
495 return (0); /* fail */
497 for (bound2
=bound1
+1; bound2
< conn
->request_length
&&
498 conn
->request
[bound2
] != ' ' &&
499 conn
->request
[bound2
] != '\r'; bound2
++)
502 /* find query string */
503 for (mid
=bound1
; mid
<bound2
&& conn
->request
[mid
] != '?'; mid
++)
506 if (conn
->request
[mid
] == '?') {
507 conn
->query
= split_string(conn
->request
, mid
+1, bound2
);
511 conn
->uri
= split_string(conn
->request
, bound1
, bound2
);
513 /* parse important fields */
514 accept_enc
= parse_field(conn
, "Accept-Encoding: ");
515 if (accept_enc
!= NULL
) {
516 if (strstr(accept_enc
, "gzip") != NULL
)
517 conn
->accept_gzip
= 1;
523 /* FIXME: maybe we need a smarter way of doing static pages: */
525 /* ---------------------------------------------------------------------------
526 * Web interface: static stylesheet.
529 static_style_css(struct connection
*conn
)
531 #include "stylecss.h"
533 conn
->reply
= style_css
;
534 conn
->reply_length
= style_css_len
;
535 conn
->reply_dont_free
= 1;
536 conn
->mime_type
= mime_type_css
;
539 /* ---------------------------------------------------------------------------
540 * Web interface: static JavaScript.
543 static_graph_js(struct connection
*conn
)
547 conn
->reply
= graph_js
;
548 conn
->reply_length
= graph_js_len
;
549 conn
->reply_dont_free
= 1;
550 conn
->mime_type
= mime_type_js
;
553 /* ---------------------------------------------------------------------------
554 * gzip a reply, if requested and possible. Don't bother with a minimum
555 * length requirement, I've never seen a page fail to compress.
558 process_gzip(struct connection
*conn
)
564 if (!conn
->accept_gzip
)
567 buf
= xmalloc(conn
->reply_length
);
568 len
= conn
->reply_length
;
574 if (deflateInit2(&zs
, Z_BEST_COMPRESSION
, Z_DEFLATED
,
575 15+16, /* 15 = biggest window, 16 = add gzip header+trailer */
577 Z_DEFAULT_STRATEGY
) != Z_OK
)
580 zs
.avail_in
= conn
->reply_length
;
581 zs
.next_in
= (unsigned char *)conn
->reply
;
583 zs
.avail_out
= conn
->reply_length
;
584 zs
.next_out
= (unsigned char *)buf
;
586 if (deflate(&zs
, Z_FINISH
) != Z_STREAM_END
) {
589 verbosef("failed to compress %u bytes", (unsigned int)len
);
593 if (conn
->reply_dont_free
)
594 conn
->reply_dont_free
= 0;
598 conn
->reply_length
-= zs
.avail_out
;
599 conn
->encoding
= encoding_gzip
;
603 /* ---------------------------------------------------------------------------
604 * Process a GET/HEAD request
606 static void process_get(struct connection
*conn
)
608 char *decoded_url
, *safe_url
;
610 verbosef("http: %s \"%s\" %s", conn
->method
, conn
->uri
,
611 (conn
->query
== NULL
)?"":conn
->query
);
613 /* work out path of file being requested */
614 decoded_url
= urldecode(conn
->uri
);
616 /* make sure it's safe */
617 safe_url
= make_safe_uri(decoded_url
);
619 if (safe_url
== NULL
)
621 default_reply(conn
, 400, "Bad Request",
622 "You requested an invalid URI: %s", conn
->uri
);
626 if (strcmp(safe_url
, "/") == 0) {
627 struct str
*buf
= html_front_page();
628 str_extract(buf
, &(conn
->reply_length
), &(conn
->reply
));
629 conn
->mime_type
= mime_type_html
;
631 else if (str_starts_with(safe_url
, "/hosts/")) {
632 /* FIXME here - make this saner */
633 struct str
*buf
= html_hosts(safe_url
, conn
->query
);
635 default_reply(conn
, 404, "Not Found",
636 "The page you requested could not be found.");
640 str_extract(buf
, &(conn
->reply_length
), &(conn
->reply
));
641 conn
->mime_type
= mime_type_html
;
643 else if (str_starts_with(safe_url
, "/graphs.xml")) {
644 struct str
*buf
= xml_graphs();
645 str_extract(buf
, &(conn
->reply_length
), &(conn
->reply
));
646 conn
->mime_type
= mime_type_xml
;
647 /* hack around Opera caching the XML */
648 conn
->header_extra
= "Pragma: no-cache\r\n";
650 else if (strcmp(safe_url
, "/style.css") == 0)
651 static_style_css(conn
);
652 else if (strcmp(safe_url
, "/graph.js") == 0)
653 static_graph_js(conn
);
655 default_reply(conn
, 404, "Not Found",
656 "The page you requested could not be found.");
663 assert(conn
->mime_type
!= NULL
);
664 generate_header(conn
, 200, "OK");
669 /* ---------------------------------------------------------------------------
670 * Process a request: build the header and reply, advance state.
672 static void process_request(struct connection
*conn
)
674 if (!parse_request(conn
))
676 default_reply(conn
, 400, "Bad Request",
677 "You sent a request that the server couldn't understand.");
679 else if (strcmp(conn
->method
, "GET") == 0)
683 else if (strcmp(conn
->method
, "HEAD") == 0)
686 conn
->header_only
= 1;
690 default_reply(conn
, 501, "Not Implemented",
691 "The method you specified (%s) is not implemented.",
696 if (conn
->header_only
)
697 conn
->state
= SEND_HEADER
;
699 conn
->state
= SEND_HEADER_AND_REPLY
;
704 /* ---------------------------------------------------------------------------
707 static void poll_recv_request(struct connection
*conn
)
712 recvd
= recv(conn
->socket
, buf
, sizeof(buf
), 0);
713 dverbosef("poll_recv_request(%d) got %d bytes", conn
->socket
, (int)recvd
);
717 verbosef("recv(%d) error: %s", conn
->socket
, strerror(errno
));
721 conn
->last_active_mono
= now_mono();
723 /* append to conn->request */
724 conn
->request
= xrealloc(conn
->request
, conn
->request_length
+recvd
+1);
725 memcpy(conn
->request
+conn
->request_length
, buf
, (size_t)recvd
);
726 conn
->request_length
+= recvd
;
727 conn
->request
[conn
->request_length
] = 0;
729 /* die if it's too long */
730 if (conn
->request_length
> MAX_REQUEST_LENGTH
)
732 default_reply(conn
, 413, "Request Entity Too Large",
733 "Your request was dropped because it was too long.");
734 conn
->state
= SEND_HEADER
;
738 /* process request if we have all of it */
739 if (conn
->request_length
> 4 &&
740 memcmp(conn
->request
+conn
->request_length
-4, "\r\n\r\n", 4) == 0)
742 process_request(conn
);
744 /* request not needed anymore */
746 conn
->request
= NULL
; /* important: don't free it again later */
752 /* ---------------------------------------------------------------------------
753 * Try to send header and [a part of the] reply in one packet.
755 static void poll_send_header_and_reply(struct connection
*conn
)
760 assert(!conn
->header_only
);
761 assert(conn
->reply_length
> 0);
762 assert(conn
->header_sent
== 0);
764 assert(conn
->reply_sent
== 0);
767 iov
[0].iov_base
= conn
->header
;
768 iov
[0].iov_len
= conn
->header_length
;
770 iov
[1].iov_base
= conn
->reply
;
771 iov
[1].iov_len
= conn
->reply_length
;
773 sent
= writev(conn
->socket
, iov
, 2);
774 conn
->last_active_mono
= now_mono();
776 /* handle any errors (-1) or closure (0) in send() */
779 verbosef("writev(%d) error: %s", conn
->socket
, strerror(errno
));
784 /* Figure out what we've sent. */
785 conn
->total_sent
+= (unsigned int)sent
;
786 if (sent
< (ssize_t
)conn
->header_length
) {
787 verbosef("partially sent header");
788 conn
->header_sent
= sent
;
789 conn
->state
= SEND_HEADER
;
793 conn
->header_sent
= conn
->header_length
;
794 sent
-= conn
->header_length
;
796 if (sent
< (ssize_t
)conn
->reply_length
) {
797 verbosef("partially sent reply");
798 conn
->reply_sent
+= sent
;
799 conn
->state
= SEND_REPLY
;
803 conn
->reply_sent
= conn
->reply_length
;
807 /* ---------------------------------------------------------------------------
808 * Sending header. Assumes conn->header is not NULL.
810 static void poll_send_header(struct connection
*conn
)
814 sent
= send(conn
->socket
, conn
->header
+ conn
->header_sent
,
815 conn
->header_length
- conn
->header_sent
, 0);
816 conn
->last_active_mono
= now_mono();
817 dverbosef("poll_send_header(%d) sent %d bytes", conn
->socket
, (int)sent
);
819 /* handle any errors (-1) or closure (0) in send() */
823 verbosef("send(%d) error: %s", conn
->socket
, strerror(errno
));
827 conn
->header_sent
+= (unsigned int)sent
;
828 conn
->total_sent
+= (unsigned int)sent
;
830 /* check if we're done sending */
831 if (conn
->header_sent
== conn
->header_length
)
833 if (conn
->header_only
)
836 conn
->state
= SEND_REPLY
;
842 /* ---------------------------------------------------------------------------
845 static void poll_send_reply(struct connection
*conn
)
849 sent
= send(conn
->socket
,
850 conn
->reply
+ conn
->reply_sent
,
851 conn
->reply_length
- conn
->reply_sent
, 0);
852 conn
->last_active_mono
= now_mono();
853 dverbosef("poll_send_reply(%d) sent %d: [%d-%d] of %d",
854 conn
->socket
, (int)sent
,
855 (int)conn
->reply_sent
,
856 (int)(conn
->reply_sent
+ sent
- 1),
857 (int)conn
->reply_length
);
859 /* handle any errors (-1) or closure (0) in send() */
863 verbosef("send(%d) error: %s", conn
->socket
, strerror(errno
));
865 verbosef("send(%d) closure", conn
->socket
);
869 conn
->reply_sent
+= (unsigned int)sent
;
870 conn
->total_sent
+= (unsigned int)sent
;
872 /* check if we're done sending */
873 if (conn
->reply_sent
== conn
->reply_length
) conn
->state
= DONE
;
876 /* Use getaddrinfo to figure out what type of socket to create and
877 * what to bind it to. "bindaddr" can be NULL. Remember to freeaddrinfo()
880 static struct addrinfo
*get_bind_addr(
881 const char *bindaddr
, const unsigned short bindport
)
883 struct addrinfo hints
, *ai
;
887 memset(&hints
, 0, sizeof(hints
));
888 hints
.ai_family
= AF_UNSPEC
;
889 hints
.ai_socktype
= SOCK_STREAM
;
890 hints
.ai_flags
= AI_PASSIVE
;
892 snprintf(portstr
, sizeof(portstr
), "%u", bindport
);
893 if ((ret
= getaddrinfo(bindaddr
, portstr
, &hints
, &ai
)))
894 err(1, "getaddrinfo(%s, %s) failed: %s",
895 bindaddr
? bindaddr
: "NULL", portstr
, gai_strerror(ret
));
897 err(1, "getaddrinfo() returned NULL pointer");
901 void http_add_bindaddr(const char *bindaddr
)
903 struct bindaddr_entry
*ent
;
905 ent
= xmalloc(sizeof(*ent
));
907 STAILQ_INSERT_TAIL(&bindaddrs
, ent
, entries
);
910 static void http_listen_one(struct addrinfo
*ai
,
911 const unsigned short bindport
)
913 char ipaddr
[INET6_ADDRSTRLEN
];
914 int sockin
, sockopt
, ret
;
916 /* format address into ipaddr string */
917 if ((ret
= getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, ipaddr
,
918 sizeof(ipaddr
), NULL
, 0, NI_NUMERICHOST
)) != 0)
919 err(1, "getnameinfo failed: %s", gai_strerror(ret
));
921 /* create incoming socket */
922 if ((sockin
= socket(ai
->ai_family
, ai
->ai_socktype
,
923 ai
->ai_protocol
)) == -1) {
924 warn("http_listen_one(%s, %u): socket(%d (%s), %d, %d) failed",
925 ipaddr
, (unsigned int)bindport
,
927 (ai
->ai_family
== AF_INET6
) ? "AF_INET6" :
928 (ai
->ai_family
== AF_INET
) ? "AF_INET" :
930 ai
->ai_socktype
, ai
->ai_protocol
);
934 fd_set_nonblock(sockin
);
938 if (setsockopt(sockin
, SOL_SOCKET
, SO_REUSEADDR
,
939 &sockopt
, sizeof(sockopt
)) == -1)
940 err(1, "can't set SO_REUSEADDR");
943 /* explicitly disallow IPv4 mapped addresses since OpenBSD doesn't allow
944 * dual stack sockets under any circumstances
946 if (ai
->ai_family
== AF_INET6
) {
948 if (setsockopt(sockin
, IPPROTO_IPV6
, IPV6_V6ONLY
,
949 &sockopt
, sizeof(sockopt
)) == -1)
950 err(1, "can't set IPV6_V6ONLY");
955 if (bind(sockin
, ai
->ai_addr
, ai
->ai_addrlen
) == -1) {
956 warn("bind(\"%s\") failed", ipaddr
);
961 /* listen on socket */
962 if (listen(sockin
, 128) == -1)
963 err(1, "listen() failed");
965 verbosef("listening on http://%s%s%s:%u/",
966 (ai
->ai_family
== AF_INET6
) ? "[" : "",
968 (ai
->ai_family
== AF_INET6
) ? "]" : "",
972 insocks
= xrealloc(insocks
, sizeof(*insocks
) * (insock_num
+ 1));
973 insocks
[insock_num
++] = sockin
;
976 /* Initialize the http sockets and listen on them. */
977 void http_listen(const unsigned short bindport
)
979 /* If the user didn't specify any bind addresses, add a NULL.
980 * This will become a wildcard.
982 if (STAILQ_EMPTY(&bindaddrs
))
983 http_add_bindaddr(NULL
);
985 /* Listen on every specified interface. */
986 while (!STAILQ_EMPTY(&bindaddrs
)) {
987 struct bindaddr_entry
*bindaddr
= STAILQ_FIRST(&bindaddrs
);
988 struct addrinfo
*ai
, *ais
= get_bind_addr(bindaddr
->s
, bindport
);
990 /* There could be multiple addresses returned, handle them all. */
991 for (ai
= ais
; ai
; ai
= ai
->ai_next
)
992 http_listen_one(ai
, bindport
);
996 STAILQ_REMOVE_HEAD(&bindaddrs
, entries
);
1000 if (insocks
== NULL
)
1001 errx(1, "was not able to bind any ports for http interface");
1003 /* ignore SIGPIPE */
1004 if (signal(SIGPIPE
, SIG_IGN
) == SIG_ERR
)
1005 err(1, "can't ignore SIGPIPE");
1010 /* ---------------------------------------------------------------------------
1011 * Set recv/send fd_sets and calculate timeout length.
1014 http_fd_set(fd_set
*recv_set
, fd_set
*send_set
, int *max_fd
,
1015 struct timeval
*timeout
, int *need_timeout
)
1017 struct connection
*conn
, *next
;
1018 int minidle
= idletime
+ 1;
1021 #define MAX_FD_SET(sock, fdset) do { \
1022 FD_SET(sock, fdset); *max_fd = MAX(*max_fd, sock); } while(0)
1024 for (i
=0; i
<insock_num
; i
++)
1025 MAX_FD_SET(insocks
[i
], recv_set
);
1027 LIST_FOREACH_SAFE(conn
, &connlist
, entries
, next
)
1029 int idlefor
= now_mono() - conn
->last_active_mono
;
1031 /* Time out dead connections. */
1032 if (idlefor
>= idletime
) {
1033 char ipaddr
[INET6_ADDRSTRLEN
];
1034 /* FIXME: this is too late on FreeBSD, socket is invalid */
1035 int ret
= getnameinfo((struct sockaddr
*)&conn
->client
,
1036 sizeof(conn
->client
), ipaddr
, sizeof(ipaddr
),
1037 NULL
, 0, NI_NUMERICHOST
);
1039 verbosef("http socket timeout from %s (fd %d)",
1040 ipaddr
, conn
->socket
);
1042 warn("http socket timeout: getnameinfo error: %s",
1047 /* Connections that need a timeout. */
1048 if (conn
->state
!= DONE
)
1049 minidle
= MIN(minidle
, (idletime
- idlefor
));
1051 switch (conn
->state
)
1054 /* clean out stale connection */
1055 LIST_REMOVE(conn
, entries
);
1056 free_connection(conn
);
1061 MAX_FD_SET(conn
->socket
, recv_set
);
1064 case SEND_HEADER_AND_REPLY
:
1067 MAX_FD_SET(conn
->socket
, send_set
);
1070 default: errx(1, "invalid state");
1075 /* Only set timeout if cap hasn't already. */
1076 if ((*need_timeout
== 0) && (minidle
<= idletime
)) {
1078 timeout
->tv_sec
= minidle
;
1079 timeout
->tv_usec
= 0;
1085 /* ---------------------------------------------------------------------------
1086 * poll connections that select() says need attention
1088 void http_poll(fd_set
*recv_set
, fd_set
*send_set
)
1090 struct connection
*conn
;
1093 for (i
=0; i
<insock_num
; i
++)
1094 if (FD_ISSET(insocks
[i
], recv_set
))
1095 accept_connection(insocks
[i
]);
1097 LIST_FOREACH(conn
, &connlist
, entries
)
1098 switch (conn
->state
)
1101 if (FD_ISSET(conn
->socket
, recv_set
)) poll_recv_request(conn
);
1104 case SEND_HEADER_AND_REPLY
:
1105 if (FD_ISSET(conn
->socket
, send_set
)) poll_send_header_and_reply(conn
);
1109 if (FD_ISSET(conn
->socket
, send_set
)) poll_send_header(conn
);
1113 if (FD_ISSET(conn
->socket
, send_set
)) poll_send_reply(conn
);
1116 case DONE
: /* fallthrough */
1117 default: errx(1, "invalid state");
1121 void http_stop(void) {
1122 struct connection
*conn
;
1125 /* Close listening sockets. */
1126 for (i
=0; i
<insock_num
; i
++)
1131 /* Close in-flight connections. */
1132 LIST_FOREACH(conn
, &connlist
, entries
) {
1133 LIST_REMOVE(conn
, entries
);
1134 free_connection(conn
);
1139 /* vim:set ts=4 sw=4 et tw=78: */