2 * copyright (c) 2001-2011 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>
39 static const char mime_type_xml
[] = "text/xml";
40 static const char mime_type_html
[] = "text/html; charset=us-ascii";
41 static const char mime_type_css
[] = "text/css";
42 static const char mime_type_js
[] = "text/javascript";
43 static const char encoding_identity
[] = "identity";
44 static const char encoding_gzip
[] = "gzip";
46 static const char server
[] = PACKAGE_NAME
"/" PACKAGE_VERSION
;
47 static int idletime
= 60;
48 #define MAX_REQUEST_LENGTH 4000
50 static int *insocks
= NULL
;
51 static unsigned int insock_num
= 0;
54 LIST_ENTRY(connection
) entries
;
57 struct sockaddr_storage client
;
60 RECV_REQUEST
, /* receiving request */
61 SEND_HEADER_AND_REPLY
, /* try to send header+reply together */
62 SEND_HEADER
, /* sending generated header */
63 SEND_REPLY
, /* sending reply */
64 DONE
/* conn closed, need to remove from queue */
67 /* char request[request_length+1] is null-terminated */
69 size_t request_length
;
73 char *method
, *uri
, *query
; /* query can be NULL */
76 const char *mime_type
, *encoding
, *header_extra
;
77 size_t header_length
, header_sent
;
78 int header_dont_free
, header_only
, http_code
;
82 size_t reply_length
, reply_sent
;
84 unsigned int total_sent
; /* header + body = total, for logging */
87 static LIST_HEAD(conn_list_head
, connection
) connlist
=
88 LIST_HEAD_INITIALIZER(conn_list_head
);
90 struct bindaddr_entry
{
91 STAILQ_ENTRY(bindaddr_entry
) entries
;
94 static STAILQ_HEAD(bindaddrs_head
, bindaddr_entry
) bindaddrs
=
95 STAILQ_HEAD_INITIALIZER(bindaddrs
);
97 /* ---------------------------------------------------------------------------
98 * Decode URL by converting %XX (where XX are hexadecimal digits) to the
99 * character it represents. Don't forget to free the return value.
101 static char *urldecode(const char *url
)
103 size_t i
, len
= strlen(url
);
104 char *out
= xmalloc(len
+1);
107 for (i
=0, pos
=0; i
<len
; i
++)
109 if (url
[i
] == '%' && i
+2 < len
&&
110 isxdigit(url
[i
+1]) && isxdigit(url
[i
+2]))
113 #define HEX_TO_DIGIT(hex) ( \
114 ((hex) >= 'A' && (hex) <= 'F') ? ((hex)-'A'+10): \
115 ((hex) >= 'a' && (hex) <= 'f') ? ((hex)-'a'+10): \
118 out
[pos
++] = HEX_TO_DIGIT(url
[i
+1]) * 16 +
119 HEX_TO_DIGIT(url
[i
+2]);
132 /* don't really need to realloc here - it's probably a performance hit */
133 out
= xrealloc(out
, strlen(out
)+1); /* dealloc what we don't need */
140 /* ---------------------------------------------------------------------------
141 * Consolidate slashes in-place by shifting parts of the string over repeated
144 static void consolidate_slashes(char *s
)
146 size_t left
= 0, right
= 0;
151 while (s
[right
] != '\0')
155 if (s
[right
] == '/') right
++;
159 s
[left
++] = s
[right
++];
164 if (s
[right
] == '/') saw_slash
++;
165 s
[left
++] = s
[right
++];
173 /* ---------------------------------------------------------------------------
174 * Resolve /./ and /../ in a URI, returing a new, safe URI, or NULL if the URI
175 * is invalid/unsafe. Returned buffer needs to be deallocated.
177 static char *make_safe_uri(char *uri
)
180 unsigned int slashes
= 0, elements
= 0;
181 size_t urilen
, i
, j
, pos
;
186 consolidate_slashes(uri
);
187 urilen
= strlen(uri
);
189 /* count the slashes */
190 for (i
=0, slashes
=0; i
<urilen
; i
++)
191 if (uri
[i
] == '/') slashes
++;
193 /* make an array for the URI elements */
194 elem
= xmalloc(sizeof(*elem
) * slashes
);
195 for (i
=0; i
<slashes
; i
++)
198 /* split by slashes and build elem[] array */
201 /* look for the next slash */
202 for (j
=i
; j
<urilen
&& uri
[j
] != '/'; j
++)
205 /* process uri[i,j) */
206 if ((j
== i
+1) && (uri
[i
] == '.'))
208 else if ((j
== i
+2) && (uri
[i
] == '.') && (uri
[i
+1] == '.'))
214 * Unsafe string so free elem[]. All its elements are free
223 free(elem
[elements
]);
226 else elem
[elements
++] = split_string(uri
, i
, j
);
228 i
= j
+ 1; /* uri[j] is a slash - move along one */
232 out
= xmalloc(urilen
+1); /* it won't expand */
234 for (i
=0; i
<elements
; i
++)
236 size_t delta
= strlen(elem
[i
]);
238 assert(pos
<= urilen
);
241 assert(pos
+delta
<= urilen
);
242 memcpy(out
+pos
, elem
[i
], delta
);
248 if ((elements
== 0) || (uri
[urilen
-1] == '/')) out
[pos
++] = '/';
249 assert(pos
<= urilen
);
253 /* don't really need to do this and it's probably a performance hit: */
254 /* shorten buffer if necessary */
255 if (pos
!= urilen
) out
= xrealloc(out
, strlen(out
)+1);
260 /* ---------------------------------------------------------------------------
261 * Allocate and initialize an empty connection.
263 static struct connection
*new_connection(void)
265 struct connection
*conn
= xmalloc(sizeof(*conn
));
268 memset(&conn
->client
, 0, sizeof(conn
->client
));
269 conn
->last_active
= now
;
270 conn
->request
= NULL
;
271 conn
->request_length
= 0;
272 conn
->accept_gzip
= 0;
277 conn
->mime_type
= NULL
;
278 conn
->encoding
= NULL
;
279 conn
->header_extra
= "";
280 conn
->header_length
= 0;
281 conn
->header_sent
= 0;
282 conn
->header_dont_free
= 0;
283 conn
->header_only
= 0;
286 conn
->reply_dont_free
= 0;
287 conn
->reply_length
= 0;
288 conn
->reply_sent
= 0;
289 conn
->total_sent
= 0;
291 /* Make it harmless so it gets garbage-collected if it should, for some
292 * reason, fail to be correctly filled out.
301 /* ---------------------------------------------------------------------------
302 * Accept a connection from sockin and add it to the connection queue.
304 static void accept_connection(const int sockin
)
306 struct sockaddr_storage addrin
;
308 struct connection
*conn
;
309 char ipaddr
[INET6_ADDRSTRLEN
], portstr
[12];
312 sin_size
= (socklen_t
)sizeof(addrin
);
313 sock
= accept(sockin
, (struct sockaddr
*)&addrin
, &sin_size
);
316 if (errno
== ECONNABORTED
|| errno
== EINTR
)
318 verbosef("accept() failed: %s", strerror(errno
));
321 /* else */ err(1, "accept()");
324 fd_set_nonblock(sock
);
326 /* allocate and initialise struct connection */
327 conn
= new_connection();
329 conn
->state
= RECV_REQUEST
;
330 memcpy(&conn
->client
, &addrin
, sizeof(conn
->client
));
331 LIST_INSERT_HEAD(&connlist
, conn
, entries
);
333 getnameinfo((struct sockaddr
*) &addrin
, sin_size
,
334 ipaddr
, sizeof(ipaddr
), portstr
, sizeof(portstr
),
335 NI_NUMERICHOST
| NI_NUMERICSERV
);
336 verbosef("accepted connection from %s:%s", ipaddr
, portstr
);
341 /* ---------------------------------------------------------------------------
342 * Log a connection, then cleanly deallocate its internals.
344 static void free_connection(struct connection
*conn
)
346 dverbosef("free_connection(%d)", conn
->socket
);
347 if (conn
->socket
!= -1) close(conn
->socket
);
348 if (conn
->request
!= NULL
) free(conn
->request
);
349 if (conn
->method
!= NULL
) free(conn
->method
);
350 if (conn
->uri
!= NULL
) free(conn
->uri
);
351 if (conn
->query
!= NULL
) free(conn
->query
);
352 if (conn
->header
!= NULL
&& !conn
->header_dont_free
) free(conn
->header
);
353 if (conn
->reply
!= NULL
&& !conn
->reply_dont_free
) free(conn
->reply
);
358 /* ---------------------------------------------------------------------------
359 * Format [when] as an RFC1123 date, stored in the specified buffer. The same
360 * buffer is returned for convenience.
362 #define DATE_LEN 30 /* strlen("Fri, 28 Feb 2003 00:02:08 GMT")+1 */
363 static char *rfc1123_date(char *dest
, const time_t when
)
366 if (strftime(dest
, DATE_LEN
,
367 "%a, %d %b %Y %H:%M:%S %Z", gmtime(&tmp
) ) == 0)
368 errx(1, "strftime() failed [%s]", dest
);
372 static void generate_header(struct connection
*conn
,
373 const int code
, const char *text
)
377 assert(conn
->header
== NULL
);
378 assert(conn
->mime_type
!= NULL
);
379 if (conn
->encoding
== NULL
)
380 conn
->encoding
= encoding_identity
;
382 verbosef("http: %d %s (%s: %d bytes)", code
, text
,
383 conn
->encoding
, conn
->reply_length
);
384 conn
->header_length
= xasprintf(&(conn
->header
),
388 "Vary: Accept-Encoding\r\n"
389 "Content-Type: %s\r\n"
390 "Content-Length: %d\r\n"
391 "Content-Encoding: %s\r\n"
392 "X-Robots-Tag: noindex, noarchive\r\n"
397 rfc1123_date(date
, now
), server
,
398 conn
->mime_type
, conn
->reply_length
, conn
->encoding
,
400 conn
->http_code
= code
;
405 /* ---------------------------------------------------------------------------
406 * A default reply for any (erroneous) occasion.
408 static void default_reply(struct connection
*conn
,
409 const int errcode
, const char *errname
, const char *format
, ...)
414 va_start(va
, format
);
415 xvasprintf(&reason
, format
, va
);
418 conn
->reply_length
= xasprintf(&(conn
->reply
),
419 "<html><head><title>%d %s</title></head><body>\n"
420 "<h1>%s</h1>\n" /* errname */
425 errcode
, errname
, errname
, reason
, server
);
428 /* forget any dangling metadata */
429 conn
->mime_type
= mime_type_html
;
430 conn
->encoding
= encoding_identity
;
432 generate_header(conn
, errcode
, errname
);
437 /* ---------------------------------------------------------------------------
438 * Parses a single HTTP request field. Returns string from end of [field] to
439 * first \r, \n or end of request string. Returns NULL if [field] can't be
442 * You need to remember to deallocate the result.
443 * example: parse_field(conn, "Referer: ");
445 static char *parse_field(const struct connection
*conn
, const char *field
)
447 size_t bound1
, bound2
;
451 pos
= strstr(conn
->request
, field
);
454 bound1
= pos
- conn
->request
+ strlen(field
);
457 for (bound2
= bound1
;
458 conn
->request
[bound2
] != '\r' &&
459 bound2
< conn
->request_length
; bound2
++)
463 return (split_string(conn
->request
, bound1
, bound2
));
468 /* ---------------------------------------------------------------------------
469 * Parse an HTTP request like "GET /hosts/?sort=in HTTP/1.1" to get the method
470 * (GET), the uri (/hosts/), the query (sort=in) and whether the UA will
471 * accept gzip encoding. Remember to deallocate all these buffers. Query
472 * can be NULL. The method will be returned in uppercase.
474 static int parse_request(struct connection
*conn
)
476 size_t bound1
, bound2
, mid
;
480 for (bound1
= 0; bound1
< conn
->request_length
&&
481 conn
->request
[bound1
] != ' '; bound1
++)
484 conn
->method
= split_string(conn
->request
, 0, bound1
);
485 strntoupper(conn
->method
, bound1
);
488 for (; bound1
< conn
->request_length
&&
489 conn
->request
[bound1
] == ' '; bound1
++)
492 if (bound1
== conn
->request_length
)
493 return (0); /* fail */
495 for (bound2
=bound1
+1; bound2
< conn
->request_length
&&
496 conn
->request
[bound2
] != ' ' &&
497 conn
->request
[bound2
] != '\r'; bound2
++)
500 /* find query string */
501 for (mid
=bound1
; mid
<bound2
&& conn
->request
[mid
] != '?'; mid
++)
504 if (conn
->request
[mid
] == '?') {
505 conn
->query
= split_string(conn
->request
, mid
+1, bound2
);
509 conn
->uri
= split_string(conn
->request
, bound1
, bound2
);
511 /* parse important fields */
512 accept_enc
= parse_field(conn
, "Accept-Encoding: ");
513 if (accept_enc
!= NULL
) {
514 if (strstr(accept_enc
, "gzip") != NULL
)
515 conn
->accept_gzip
= 1;
521 /* FIXME: maybe we need a smarter way of doing static pages: */
523 /* ---------------------------------------------------------------------------
524 * Web interface: static stylesheet.
527 static_style_css(struct connection
*conn
)
529 #include "stylecss.h"
531 conn
->reply
= style_css
;
532 conn
->reply_length
= style_css_len
;
533 conn
->reply_dont_free
= 1;
534 conn
->mime_type
= mime_type_css
;
537 /* ---------------------------------------------------------------------------
538 * Web interface: static JavaScript.
541 static_graph_js(struct connection
*conn
)
545 conn
->reply
= graph_js
;
546 conn
->reply_length
= graph_js_len
;
547 conn
->reply_dont_free
= 1;
548 conn
->mime_type
= mime_type_js
;
551 /* ---------------------------------------------------------------------------
552 * gzip a reply, if requested and possible. Don't bother with a minimum
553 * length requirement, I've never seen a page fail to compress.
556 process_gzip(struct connection
*conn
)
562 if (!conn
->accept_gzip
)
565 buf
= xmalloc(conn
->reply_length
);
566 len
= conn
->reply_length
;
572 if (deflateInit2(&zs
, Z_BEST_COMPRESSION
, Z_DEFLATED
,
573 15+16, /* 15 = biggest window, 16 = add gzip header+trailer */
575 Z_DEFAULT_STRATEGY
) != Z_OK
)
578 zs
.avail_in
= conn
->reply_length
;
579 zs
.next_in
= (unsigned char *)conn
->reply
;
581 zs
.avail_out
= conn
->reply_length
;
582 zs
.next_out
= (unsigned char *)buf
;
584 if (deflate(&zs
, Z_FINISH
) != Z_STREAM_END
) {
587 verbosef("failed to compress %u bytes", (unsigned int)len
);
591 if (conn
->reply_dont_free
)
592 conn
->reply_dont_free
= 0;
597 conn
->reply_length
-= zs
.avail_out
;
598 conn
->encoding
= encoding_gzip
;
602 /* ---------------------------------------------------------------------------
603 * Process a GET/HEAD request
605 static void process_get(struct connection
*conn
)
607 char *decoded_url
, *safe_url
;
609 verbosef("http: %s \"%s\" %s", conn
->method
, conn
->uri
,
610 (conn
->query
== NULL
)?"":conn
->query
);
612 /* work out path of file being requested */
613 decoded_url
= urldecode(conn
->uri
);
615 /* make sure it's safe */
616 safe_url
= make_safe_uri(decoded_url
);
618 if (safe_url
== NULL
)
620 default_reply(conn
, 400, "Bad Request",
621 "You requested an invalid URI: %s", conn
->uri
);
625 if (strcmp(safe_url
, "/") == 0) {
626 struct str
*buf
= html_front_page();
627 str_extract(buf
, &(conn
->reply_length
), &(conn
->reply
));
628 conn
->mime_type
= mime_type_html
;
630 else if (str_starts_with(safe_url
, "/hosts/")) {
631 /* FIXME here - make this saner */
632 struct str
*buf
= html_hosts(safe_url
, conn
->query
);
634 default_reply(conn
, 404, "Not Found",
635 "The page you requested could not be found.");
639 str_extract(buf
, &(conn
->reply_length
), &(conn
->reply
));
640 conn
->mime_type
= mime_type_html
;
642 else if (str_starts_with(safe_url
, "/graphs.xml")) {
643 struct str
*buf
= xml_graphs();
644 str_extract(buf
, &(conn
->reply_length
), &(conn
->reply
));
645 conn
->mime_type
= mime_type_xml
;
646 /* hack around Opera caching the XML */
647 conn
->header_extra
= "Pragma: no-cache\r\n";
649 else if (strcmp(safe_url
, "/style.css") == 0)
650 static_style_css(conn
);
651 else if (strcmp(safe_url
, "/graph.js") == 0)
652 static_graph_js(conn
);
654 default_reply(conn
, 404, "Not Found",
655 "The page you requested could not be found.");
662 assert(conn
->mime_type
!= NULL
);
663 generate_header(conn
, 200, "OK");
668 /* ---------------------------------------------------------------------------
669 * Process a request: build the header and reply, advance state.
671 static void process_request(struct connection
*conn
)
673 if (!parse_request(conn
))
675 default_reply(conn
, 400, "Bad Request",
676 "You sent a request that the server couldn't understand.");
678 else if (strcmp(conn
->method
, "GET") == 0)
682 else if (strcmp(conn
->method
, "HEAD") == 0)
685 conn
->header_only
= 1;
689 default_reply(conn
, 501, "Not Implemented",
690 "The method you specified (%s) is not implemented.",
695 if (conn
->header_only
)
696 conn
->state
= SEND_HEADER
;
698 conn
->state
= SEND_HEADER_AND_REPLY
;
700 /* request not needed anymore */
702 conn
->request
= NULL
; /* important: don't free it again later */
707 /* ---------------------------------------------------------------------------
710 static void poll_recv_request(struct connection
*conn
)
712 #define BUFSIZE 65536
716 recvd
= recv(conn
->socket
, buf
, BUFSIZE
, 0);
717 dverbosef("poll_recv_request(%d) got %d bytes", conn
->socket
, (int)recvd
);
721 verbosef("recv(%d) error: %s", conn
->socket
, strerror(errno
));
725 conn
->last_active
= now
;
728 /* append to conn->request */
729 conn
->request
= xrealloc(conn
->request
, conn
->request_length
+recvd
+1);
730 memcpy(conn
->request
+conn
->request_length
, buf
, (size_t)recvd
);
731 conn
->request_length
+= recvd
;
732 conn
->request
[conn
->request_length
] = 0;
734 /* process request if we have all of it */
735 if (conn
->request_length
> 4 &&
736 memcmp(conn
->request
+conn
->request_length
-4, "\r\n\r\n", 4) == 0)
737 process_request(conn
);
739 /* die if it's too long */
740 if (conn
->request_length
> MAX_REQUEST_LENGTH
)
742 default_reply(conn
, 413, "Request Entity Too Large",
743 "Your request was dropped because it was too long.");
744 conn
->state
= SEND_HEADER
;
750 /* ---------------------------------------------------------------------------
751 * Try to send header and [a part of the] reply in one packet.
753 static void poll_send_header_and_reply(struct connection
*conn
)
758 assert(!conn
->header_only
);
759 assert(conn
->reply_length
> 0);
760 assert(conn
->header_sent
== 0);
762 assert(conn
->reply_sent
== 0);
765 iov
[0].iov_base
= conn
->header
;
766 iov
[0].iov_len
= conn
->header_length
;
768 iov
[1].iov_base
= conn
->reply
;
769 iov
[1].iov_len
= conn
->reply_length
;
771 sent
= writev(conn
->socket
, iov
, 2);
772 conn
->last_active
= now
;
774 /* handle any errors (-1) or closure (0) in send() */
777 verbosef("writev(%d) error: %s", conn
->socket
, strerror(errno
));
782 /* Figure out what we've sent. */
783 conn
->total_sent
+= (unsigned int)sent
;
784 if (sent
< (ssize_t
)conn
->header_length
) {
785 verbosef("partially sent header");
786 conn
->header_sent
= sent
;
787 conn
->state
= SEND_HEADER
;
791 conn
->header_sent
= conn
->header_length
;
792 sent
-= conn
->header_length
;
794 if (sent
< (ssize_t
)conn
->reply_length
) {
795 verbosef("partially sent reply");
796 conn
->reply_sent
+= sent
;
797 conn
->state
= SEND_REPLY
;
801 conn
->reply_sent
= conn
->reply_length
;
805 /* ---------------------------------------------------------------------------
806 * Sending header. Assumes conn->header is not NULL.
808 static void poll_send_header(struct connection
*conn
)
812 sent
= send(conn
->socket
, conn
->header
+ conn
->header_sent
,
813 conn
->header_length
- conn
->header_sent
, 0);
814 conn
->last_active
= now
;
815 dverbosef("poll_send_header(%d) sent %d bytes", conn
->socket
, (int)sent
);
817 /* handle any errors (-1) or closure (0) in send() */
821 verbosef("send(%d) error: %s", conn
->socket
, strerror(errno
));
825 conn
->header_sent
+= (unsigned int)sent
;
826 conn
->total_sent
+= (unsigned int)sent
;
828 /* check if we're done sending */
829 if (conn
->header_sent
== conn
->header_length
)
831 if (conn
->header_only
)
834 conn
->state
= SEND_REPLY
;
840 /* ---------------------------------------------------------------------------
843 static void poll_send_reply(struct connection
*conn
)
847 sent
= send(conn
->socket
,
848 conn
->reply
+ conn
->reply_sent
,
849 conn
->reply_length
- conn
->reply_sent
, 0);
850 conn
->last_active
= now
;
851 dverbosef("poll_send_reply(%d) sent %d: [%d-%d] of %d",
852 conn
->socket
, (int)sent
,
853 (int)conn
->reply_sent
,
854 (int)(conn
->reply_sent
+ sent
- 1),
855 (int)conn
->reply_length
);
857 /* handle any errors (-1) or closure (0) in send() */
861 verbosef("send(%d) error: %s", conn
->socket
, strerror(errno
));
863 verbosef("send(%d) closure", conn
->socket
);
867 conn
->reply_sent
+= (unsigned int)sent
;
868 conn
->total_sent
+= (unsigned int)sent
;
870 /* check if we're done sending */
871 if (conn
->reply_sent
== conn
->reply_length
) conn
->state
= DONE
;
874 /* Use getaddrinfo to figure out what type of socket to create and
875 * what to bind it to. "bindaddr" can be NULL. Remember to freeaddrinfo()
878 static struct addrinfo
*get_bind_addr(
879 const char *bindaddr
, const unsigned short bindport
)
881 struct addrinfo hints
, *ai
;
885 memset(&hints
, 0, sizeof(hints
));
886 hints
.ai_family
= AF_UNSPEC
;
887 hints
.ai_socktype
= SOCK_STREAM
;
888 hints
.ai_flags
= AI_PASSIVE
;
890 snprintf(portstr
, sizeof(portstr
), "%u", bindport
);
891 if ((ret
= getaddrinfo(bindaddr
, portstr
, &hints
, &ai
)))
892 err(1, "getaddrinfo(%s,%s) failed: %s",
893 bindaddr
? bindaddr
: "NULL", portstr
, gai_strerror(ret
));
895 err(1, "getaddrinfo() returned NULL pointer");
899 void http_add_bindaddr(const char *bindaddr
)
901 struct bindaddr_entry
*ent
;
903 ent
= xmalloc(sizeof(*ent
));
905 STAILQ_INSERT_TAIL(&bindaddrs
, ent
, entries
);
908 static void http_listen_one(struct addrinfo
*ai
,
909 const unsigned short bindport
)
911 char ipaddr
[INET6_ADDRSTRLEN
];
912 int sockin
, sockopt
, ret
;
914 /* create incoming socket */
915 if ((sockin
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
)) == -1)
916 err(1, "socket() failed");
920 if (setsockopt(sockin
, SOL_SOCKET
, SO_REUSEADDR
,
921 &sockopt
, sizeof(sockopt
)) == -1)
922 err(1, "can't set SO_REUSEADDR");
924 /* explicitly disallow IPv4 mapped addresses since OpenBSD doesn't allow
925 * dual stack sockets under any circumstances
928 if (ai
->ai_family
== AF_INET6
) {
930 if (setsockopt(sockin
, IPPROTO_IPV6
, IPV6_V6ONLY
,
931 &sockopt
, sizeof(sockopt
)) == -1)
932 err(1, "can't set IPV6_V6ONLY");
937 if (bind(sockin
, ai
->ai_addr
, ai
->ai_addrlen
) == -1)
938 err(1, "bind(\"%s\") failed", ipaddr
);
940 /* listen on socket */
941 if (listen(sockin
, -1) == -1)
942 err(1, "listen() failed");
944 /* format address into ipaddr string */
945 if ((ret
= getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, ipaddr
,
946 sizeof(ipaddr
), NULL
, 0, NI_NUMERICHOST
)) != 0)
947 err(1, "getnameinfo failed: %s", gai_strerror(ret
));
948 verbosef("listening on http://%s%s%s:%u/",
949 (ai
->ai_family
== AF_INET6
) ? "[" : "",
951 (ai
->ai_family
== AF_INET6
) ? "]" : "",
955 insocks
= xrealloc(insocks
, sizeof(*insocks
) * (insock_num
+ 1));
956 insocks
[insock_num
++] = sockin
;
959 /* Initialize the http sockets and listen on them. */
960 void http_listen(const unsigned short bindport
)
962 /* If the user didn't specify any bind addresses, add a NULL.
963 * This will become a wildcard.
965 if (STAILQ_EMPTY(&bindaddrs
))
966 http_add_bindaddr(NULL
);
968 /* Listen on every specified interface. */
969 while (!STAILQ_EMPTY(&bindaddrs
)) {
970 struct bindaddr_entry
*bindaddr
= STAILQ_FIRST(&bindaddrs
);
971 struct addrinfo
*ai
, *ais
= get_bind_addr(bindaddr
->s
, bindport
);
973 /* There could be multiple addresses returned, handle them all. */
974 for (ai
= ais
; ai
; ai
= ai
->ai_next
)
975 http_listen_one(ai
, bindport
);
979 STAILQ_REMOVE_HEAD(&bindaddrs
, entries
);
984 if (signal(SIGPIPE
, SIG_IGN
) == SIG_ERR
)
985 err(1, "can't ignore SIGPIPE");
990 /* ---------------------------------------------------------------------------
991 * Set recv/send fd_sets and calculate timeout length.
994 http_fd_set(fd_set
*recv_set
, fd_set
*send_set
, int *max_fd
,
995 struct timeval
*timeout
, int *need_timeout
)
997 struct connection
*conn
, *next
;
998 int minidle
= idletime
+ 1;
1001 #define MAX_FD_SET(sock, fdset) do { \
1002 FD_SET(sock, fdset); *max_fd = MAX(*max_fd, sock); } while(0)
1004 for (i
=0; i
<insock_num
; i
++)
1005 MAX_FD_SET(insocks
[i
], recv_set
);
1007 LIST_FOREACH_SAFE(conn
, &connlist
, entries
, next
)
1009 int idlefor
= now
- conn
->last_active
;
1011 /* Time out dead connections. */
1012 if (idlefor
>= idletime
) {
1013 char ipaddr
[INET6_ADDRSTRLEN
];
1014 /* FIXME: this is too late on FreeBSD, socket is invalid */
1015 int ret
= getnameinfo((struct sockaddr
*)&conn
->client
,
1016 sizeof(conn
->client
), ipaddr
, sizeof(ipaddr
),
1017 NULL
, 0, NI_NUMERICHOST
);
1019 verbosef("http socket timeout from %s (fd %d)",
1020 ipaddr
, conn
->socket
);
1022 warn("http socket timeout: getnameinfo error: %s",
1027 /* Connections that need a timeout. */
1028 if (conn
->state
!= DONE
)
1029 minidle
= MIN(minidle
, (idletime
- idlefor
));
1031 switch (conn
->state
)
1034 /* clean out stale connection */
1035 LIST_REMOVE(conn
, entries
);
1036 free_connection(conn
);
1041 MAX_FD_SET(conn
->socket
, recv_set
);
1044 case SEND_HEADER_AND_REPLY
:
1047 MAX_FD_SET(conn
->socket
, send_set
);
1050 default: errx(1, "invalid state");
1055 /* Only set timeout if cap hasn't already. */
1056 if ((*need_timeout
== 0) && (minidle
<= idletime
)) {
1058 timeout
->tv_sec
= minidle
;
1059 timeout
->tv_usec
= 0;
1065 /* ---------------------------------------------------------------------------
1066 * poll connections that select() says need attention
1068 void http_poll(fd_set
*recv_set
, fd_set
*send_set
)
1070 struct connection
*conn
;
1073 for (i
=0; i
<insock_num
; i
++)
1074 if (FD_ISSET(insocks
[i
], recv_set
))
1075 accept_connection(insocks
[i
]);
1077 LIST_FOREACH(conn
, &connlist
, entries
)
1078 switch (conn
->state
)
1081 if (FD_ISSET(conn
->socket
, recv_set
)) poll_recv_request(conn
);
1084 case SEND_HEADER_AND_REPLY
:
1085 if (FD_ISSET(conn
->socket
, send_set
)) poll_send_header_and_reply(conn
);
1089 if (FD_ISSET(conn
->socket
, send_set
)) poll_send_header(conn
);
1093 if (FD_ISSET(conn
->socket
, send_set
)) poll_send_reply(conn
);
1096 case DONE
: /* fallthrough */
1097 default: errx(1, "invalid state");
1101 void http_stop(void) {
1102 struct connection
*conn
;
1105 /* Close listening sockets. */
1106 for (i
=0; i
<insock_num
; i
++)
1111 /* Close in-flight connections. */
1112 LIST_FOREACH(conn
, &connlist
, entries
) {
1113 LIST_REMOVE(conn
, entries
);
1114 free_connection(conn
);
1119 /* vim:set ts=4 sw=4 et tw=78: */