2 * copyright (c) 2001-2008 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)
21 #include <sys/socket.h>
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
37 const char *base_url
= "/";
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 static int sockin
= -1; /* socket to accept connections from */
49 #define MAX_REQUEST_LENGTH 4000
52 #define min(a,b) (((a) < (b)) ? (a) : (b))
56 LIST_ENTRY(connection
) entries
;
59 struct sockaddr_storage client
;
62 RECV_REQUEST
, /* receiving request */
63 SEND_HEADER_AND_REPLY
, /* try to send header+reply together */
64 SEND_HEADER
, /* sending generated header */
65 SEND_REPLY
, /* sending reply */
66 DONE
/* conn closed, need to remove from queue */
69 /* char request[request_length+1] is null-terminated */
71 size_t request_length
;
75 char *method
, *uri
, *query
; /* query can be NULL */
78 const char *mime_type
, *encoding
, *header_extra
;
79 size_t header_length
, header_sent
;
80 int header_dont_free
, header_only
, http_code
;
84 size_t reply_length
, reply_sent
;
86 unsigned int total_sent
; /* header + body = total, for logging */
89 static LIST_HEAD(conn_list_head
, connection
) connlist
=
90 LIST_HEAD_INITIALIZER(conn_list_head
);
92 /* ---------------------------------------------------------------------------
93 * Decode URL by converting %XX (where XX are hexadecimal digits) to the
94 * character it represents. Don't forget to free the return value.
96 static char *urldecode(const char *url
)
98 size_t i
, len
= strlen(url
);
99 char *out
= xmalloc(len
+1);
102 for (i
=0, pos
=0; i
<len
; i
++)
104 if (url
[i
] == '%' && i
+2 < len
&&
105 isxdigit(url
[i
+1]) && isxdigit(url
[i
+2]))
108 #define HEX_TO_DIGIT(hex) ( \
109 ((hex) >= 'A' && (hex) <= 'F') ? ((hex)-'A'+10): \
110 ((hex) >= 'a' && (hex) <= 'f') ? ((hex)-'a'+10): \
113 out
[pos
++] = HEX_TO_DIGIT(url
[i
+1]) * 16 +
114 HEX_TO_DIGIT(url
[i
+2]);
127 /* don't really need to realloc here - it's probably a performance hit */
128 out
= xrealloc(out
, strlen(out
)+1); /* dealloc what we don't need */
135 /* ---------------------------------------------------------------------------
136 * Consolidate slashes in-place by shifting parts of the string over repeated
139 static void consolidate_slashes(char *s
)
141 size_t left
= 0, right
= 0;
146 while (s
[right
] != '\0')
150 if (s
[right
] == '/') right
++;
154 s
[left
++] = s
[right
++];
159 if (s
[right
] == '/') saw_slash
++;
160 s
[left
++] = s
[right
++];
168 /* ---------------------------------------------------------------------------
169 * Resolve /./ and /../ in a URI, returing a new, safe URI, or NULL if the URI
170 * is invalid/unsafe. Returned buffer needs to be deallocated.
172 static char *make_safe_uri(char *uri
)
175 unsigned int slashes
= 0, elements
= 0;
176 size_t urilen
, i
, j
, pos
;
181 consolidate_slashes(uri
);
182 urilen
= strlen(uri
);
184 /* count the slashes */
185 for (i
=0, slashes
=0; i
<urilen
; i
++)
186 if (uri
[i
] == '/') slashes
++;
188 /* make an array for the URI elements */
189 elem
= xmalloc(sizeof(*elem
) * slashes
);
190 for (i
=0; i
<slashes
; i
++)
193 /* split by slashes and build elem[] array */
196 /* look for the next slash */
197 for (j
=i
; j
<urilen
&& uri
[j
] != '/'; j
++)
200 /* process uri[i,j) */
201 if ((j
== i
+1) && (uri
[i
] == '.'))
203 else if ((j
== i
+2) && (uri
[i
] == '.') && (uri
[i
+1] == '.'))
209 * Unsafe string so free elem[]. All its elements are free
218 free(elem
[elements
]);
221 else elem
[elements
++] = split_string(uri
, i
, j
);
223 i
= j
+ 1; /* uri[j] is a slash - move along one */
227 out
= xmalloc(urilen
+1); /* it won't expand */
229 for (i
=0; i
<elements
; i
++)
231 size_t delta
= strlen(elem
[i
]);
233 assert(pos
<= urilen
);
236 assert(pos
+delta
<= urilen
);
237 memcpy(out
+pos
, elem
[i
], delta
);
243 if ((elements
== 0) || (uri
[urilen
-1] == '/')) out
[pos
++] = '/';
244 assert(pos
<= urilen
);
248 /* don't really need to do this and it's probably a performance hit: */
249 /* shorten buffer if necessary */
250 if (pos
!= urilen
) out
= xrealloc(out
, strlen(out
)+1);
255 /* ---------------------------------------------------------------------------
256 * Allocate and initialize an empty connection.
258 static struct connection
*new_connection(void)
260 struct connection
*conn
= xmalloc(sizeof(*conn
));
263 memset(&conn
->client
, 0, sizeof(conn
->client
));
264 conn
->last_active
= now
;
265 conn
->request
= NULL
;
266 conn
->request_length
= 0;
267 conn
->accept_gzip
= 0;
272 conn
->mime_type
= NULL
;
273 conn
->encoding
= NULL
;
274 conn
->header_extra
= "";
275 conn
->header_length
= 0;
276 conn
->header_sent
= 0;
277 conn
->header_dont_free
= 0;
278 conn
->header_only
= 0;
281 conn
->reply_dont_free
= 0;
282 conn
->reply_length
= 0;
283 conn
->reply_sent
= 0;
284 conn
->total_sent
= 0;
286 /* Make it harmless so it gets garbage-collected if it should, for some
287 * reason, fail to be correctly filled out.
296 /* ---------------------------------------------------------------------------
297 * Accept a connection from sockin and add it to the connection queue.
299 static void accept_connection(void)
301 struct sockaddr_storage addrin
;
303 struct connection
*conn
;
304 char ipaddr
[INET6_ADDRSTRLEN
], portstr
[12];
307 sin_size
= (socklen_t
)sizeof(addrin
);
308 sock
= accept(sockin
, &addrin
, &sin_size
);
311 if (errno
== ECONNABORTED
|| errno
== EINTR
)
313 verbosef("accept() failed: %s", strerror(errno
));
316 /* else */ err(1, "accept()");
319 fd_set_nonblock(sock
);
321 /* allocate and initialise struct connection */
322 conn
= new_connection();
324 conn
->state
= RECV_REQUEST
;
325 memcpy(&conn
->client
, &addrin
, sizeof(conn
->client
));
326 LIST_INSERT_HEAD(&connlist
, conn
, entries
);
328 getnameinfo((struct sockaddr
*) &addrin
, sin_size
,
329 ipaddr
, sizeof(ipaddr
), portstr
, sizeof(portstr
),
330 NI_NUMERICHOST
| NI_NUMERICSERV
);
331 verbosef("accepted connection from %s:%s", ipaddr
, portstr
);
336 /* ---------------------------------------------------------------------------
337 * Log a connection, then cleanly deallocate its internals.
339 static void free_connection(struct connection
*conn
)
341 dverbosef("free_connection(%d)", conn
->socket
);
342 if (conn
->socket
!= -1) close(conn
->socket
);
343 if (conn
->request
!= NULL
) free(conn
->request
);
344 if (conn
->method
!= NULL
) free(conn
->method
);
345 if (conn
->uri
!= NULL
) free(conn
->uri
);
346 if (conn
->query
!= NULL
) free(conn
->query
);
347 if (conn
->header
!= NULL
&& !conn
->header_dont_free
) free(conn
->header
);
348 if (conn
->reply
!= NULL
&& !conn
->reply_dont_free
) free(conn
->reply
);
353 /* ---------------------------------------------------------------------------
354 * Format [when] as an RFC1123 date, stored in the specified buffer. The same
355 * buffer is returned for convenience.
357 #define DATE_LEN 30 /* strlen("Fri, 28 Feb 2003 00:02:08 GMT")+1 */
358 static char *rfc1123_date(char *dest
, const time_t when
)
361 if (strftime(dest
, DATE_LEN
,
362 "%a, %d %b %Y %H:%M:%S %Z", gmtime(&tmp
) ) == 0)
363 errx(1, "strftime() failed [%s]", dest
);
367 static void generate_header(struct connection
*conn
,
368 const int code
, const char *text
)
372 assert(conn
->header
== NULL
);
373 assert(conn
->mime_type
!= NULL
);
374 if (conn
->encoding
== NULL
)
375 conn
->encoding
= encoding_identity
;
377 verbosef("http: %d %s (%s: %d bytes)", code
, text
,
378 conn
->encoding
, conn
->reply_length
);
379 conn
->header_length
= xasprintf(&(conn
->header
),
383 "Vary: Accept-Encoding\r\n"
384 "Content-Type: %s\r\n"
385 "Content-Length: %d\r\n"
386 "Content-Encoding: %s\r\n"
391 rfc1123_date(date
, now
), server
,
392 conn
->mime_type
, conn
->reply_length
, conn
->encoding
,
394 conn
->http_code
= code
;
399 /* ---------------------------------------------------------------------------
400 * A default reply for any (erroneous) occasion.
402 static void default_reply(struct connection
*conn
,
403 const int errcode
, const char *errname
, const char *format
, ...)
405 char *reason
, date
[DATE_LEN
];
408 va_start(va
, format
);
409 xvasprintf(&reason
, format
, va
);
412 conn
->reply_length
= xasprintf(&(conn
->reply
),
413 "<html><head><title>%d %s</title></head><body>\n"
414 "<h1>%s</h1>\n" /* errname */
419 errcode
, errname
, errname
, reason
, server
);
422 /* forget any dangling metadata */
423 conn
->mime_type
= mime_type_html
;
424 conn
->encoding
= encoding_identity
;
426 generate_header(conn
, errcode
, errname
);
431 /* ---------------------------------------------------------------------------
432 * Parses a single HTTP request field. Returns string from end of [field] to
433 * first \r, \n or end of request string. Returns NULL if [field] can't be
436 * You need to remember to deallocate the result.
437 * example: parse_field(conn, "Referer: ");
439 static char *parse_field(const struct connection
*conn
, const char *field
)
441 size_t bound1
, bound2
;
445 pos
= strstr(conn
->request
, field
);
448 bound1
= pos
- conn
->request
+ strlen(field
);
451 for (bound2
= bound1
;
452 conn
->request
[bound2
] != '\r' &&
453 bound2
< conn
->request_length
; bound2
++)
457 return (split_string(conn
->request
, bound1
, bound2
));
462 /* ---------------------------------------------------------------------------
463 * Parse an HTTP request like "GET /hosts/?sort=in HTTP/1.1" to get the method
464 * (GET), the uri (/hosts/), the query (sort=in) and whether the UA will
465 * accept gzip encoding. Remember to deallocate all these buffers. Query
466 * can be NULL. The method will be returned in uppercase.
468 static int parse_request(struct connection
*conn
)
470 size_t bound1
, bound2
, mid
;
474 for (bound1
= 0; bound1
< conn
->request_length
&&
475 conn
->request
[bound1
] != ' '; bound1
++)
478 conn
->method
= split_string(conn
->request
, 0, bound1
);
479 strntoupper(conn
->method
, bound1
);
482 for (; bound1
< conn
->request_length
&&
483 conn
->request
[bound1
] == ' '; bound1
++)
486 if (bound1
== conn
->request_length
)
487 return (0); /* fail */
489 for (bound2
=bound1
+1; bound2
< conn
->request_length
&&
490 conn
->request
[bound2
] != ' ' &&
491 conn
->request
[bound2
] != '\r'; bound2
++)
494 /* find query string */
495 for (mid
=bound1
; mid
<bound2
&& conn
->request
[mid
] != '?'; mid
++)
498 if (conn
->request
[mid
] == '?') {
499 conn
->query
= split_string(conn
->request
, mid
+1, bound2
);
503 conn
->uri
= split_string(conn
->request
, bound1
, bound2
);
505 /* parse important fields */
506 accept_enc
= parse_field(conn
, "Accept-Encoding: ");
507 if (accept_enc
!= NULL
) {
508 if (strstr(accept_enc
, "gzip") != NULL
)
509 conn
->accept_gzip
= 1;
515 /* FIXME: maybe we need a smarter way of doing static pages: */
517 /* ---------------------------------------------------------------------------
518 * Web interface: static stylesheet.
521 static_style_css(struct connection
*conn
)
523 #include "stylecss.h"
525 conn
->reply
= style_css
;
526 conn
->reply_length
= style_css_len
;
527 conn
->reply_dont_free
= 1;
528 conn
->mime_type
= mime_type_css
;
531 /* ---------------------------------------------------------------------------
532 * Web interface: static JavaScript.
535 static_graph_js(struct connection
*conn
)
539 conn
->reply
= graph_js
;
540 conn
->reply_length
= graph_js_len
;
541 conn
->reply_dont_free
= 1;
542 conn
->mime_type
= mime_type_js
;
545 /* ---------------------------------------------------------------------------
546 * gzip a reply, if requested and possible. Don't bother with a minimum
547 * length requirement, I've never seen a page fail to compress.
550 process_gzip(struct connection
*conn
)
556 if (!conn
->accept_gzip
)
559 buf
= xmalloc(conn
->reply_length
);
560 len
= conn
->reply_length
;
566 if (deflateInit2(&zs
, Z_BEST_COMPRESSION
, Z_DEFLATED
,
567 15+16, /* 15 = biggest window, 16 = add gzip header+trailer */
569 Z_DEFAULT_STRATEGY
) != Z_OK
)
572 zs
.avail_in
= conn
->reply_length
;
573 zs
.next_in
= (unsigned char *)conn
->reply
;
575 zs
.avail_out
= conn
->reply_length
;
576 zs
.next_out
= (unsigned char *)buf
;
578 if (deflate(&zs
, Z_FINISH
) != Z_STREAM_END
) {
581 verbosef("failed to compress %u bytes", (unsigned int)len
);
585 if (conn
->reply_dont_free
)
586 conn
->reply_dont_free
= 0;
591 conn
->reply_length
-= zs
.avail_out
;
592 conn
->encoding
= encoding_gzip
;
596 /* ---------------------------------------------------------------------------
597 * Process a GET/HEAD request
599 static void process_get(struct connection
*conn
)
601 char *decoded_url
, *safe_url
;
604 verbosef("http: %s \"%s\" %s", conn
->method
, conn
->uri
,
605 (conn
->query
== NULL
)?"":conn
->query
);
607 /* work out path of file being requested */
608 decoded_url
= urldecode(conn
->uri
);
610 /* make sure it's safe */
611 safe_url
= make_safe_uri(decoded_url
);
613 if (safe_url
== NULL
)
615 default_reply(conn
, 400, "Bad Request",
616 "You requested an invalid URI: %s", conn
->uri
);
620 /* make relative (or fail) */
621 decoded_url
= safe_url
;
622 if (!str_starts_with(decoded_url
, base_url
))
624 default_reply(conn
, 404, "Not Found",
625 "The page you requested could not be found.");
629 safe_url
= decoded_url
+ strlen(base_url
) - 1;
631 if (strcmp(safe_url
, "/") == 0) {
632 struct str
*buf
= html_front_page();
633 str_extract(buf
, &(conn
->reply_length
), &(conn
->reply
));
634 conn
->mime_type
= mime_type_html
;
636 else if (str_starts_with(safe_url
, "/hosts/")) {
637 /* FIXME here - make this saner */
638 struct str
*buf
= html_hosts(safe_url
, conn
->query
);
640 default_reply(conn
, 404, "Not Found",
641 "The page you requested could not be found.");
645 str_extract(buf
, &(conn
->reply_length
), &(conn
->reply
));
646 conn
->mime_type
= mime_type_html
;
648 else if (str_starts_with(safe_url
, "/graphs.xml")) {
649 struct str
*buf
= xml_graphs();
650 str_extract(buf
, &(conn
->reply_length
), &(conn
->reply
));
651 conn
->mime_type
= mime_type_xml
;
652 /* hack around Opera caching the XML */
653 conn
->header_extra
= "Pragma: no-cache\r\n";
655 else if (strcmp(safe_url
, "/style.css") == 0)
656 static_style_css(conn
);
657 else if (strcmp(safe_url
, "/graph.js") == 0)
658 static_graph_js(conn
);
660 default_reply(conn
, 404, "Not Found",
661 "The page you requested could not be found.");
668 assert(conn
->mime_type
!= NULL
);
669 generate_header(conn
, 200, "OK");
674 /* ---------------------------------------------------------------------------
675 * Process a request: build the header and reply, advance state.
677 static void process_request(struct connection
*conn
)
679 if (!parse_request(conn
))
681 default_reply(conn
, 400, "Bad Request",
682 "You sent a request that the server couldn't understand.");
684 else if (strcmp(conn
->method
, "GET") == 0)
688 else if (strcmp(conn
->method
, "HEAD") == 0)
691 conn
->header_only
= 1;
695 default_reply(conn
, 501, "Not Implemented",
696 "The method you specified (%s) is not implemented.",
701 if (conn
->header_only
)
702 conn
->state
= SEND_HEADER
;
704 conn
->state
= SEND_HEADER_AND_REPLY
;
706 /* request not needed anymore */
708 conn
->request
= NULL
; /* important: don't free it again later */
713 /* ---------------------------------------------------------------------------
716 static void poll_recv_request(struct connection
*conn
)
718 #define BUFSIZE 65536
722 recvd
= recv(conn
->socket
, buf
, BUFSIZE
, 0);
723 dverbosef("poll_recv_request(%d) got %d bytes", conn
->socket
, (int)recvd
);
727 verbosef("recv(%d) error: %s", conn
->socket
, strerror(errno
));
731 conn
->last_active
= now
;
734 /* append to conn->request */
735 conn
->request
= xrealloc(conn
->request
, conn
->request_length
+recvd
+1);
736 memcpy(conn
->request
+conn
->request_length
, buf
, (size_t)recvd
);
737 conn
->request_length
+= recvd
;
738 conn
->request
[conn
->request_length
] = 0;
740 /* process request if we have all of it */
741 if (conn
->request_length
> 4 &&
742 memcmp(conn
->request
+conn
->request_length
-4, "\r\n\r\n", 4) == 0)
743 process_request(conn
);
745 /* die if it's too long */
746 if (conn
->request_length
> MAX_REQUEST_LENGTH
)
748 default_reply(conn
, 413, "Request Entity Too Large",
749 "Your request was dropped because it was too long.");
750 conn
->state
= SEND_HEADER
;
756 /* ---------------------------------------------------------------------------
757 * Try to send header and [a part of the] reply in one packet.
759 static void poll_send_header_and_reply(struct connection
*conn
)
764 assert(!conn
->header_only
);
765 assert(conn
->reply_length
> 0);
766 assert(conn
->header_sent
== 0);
768 assert(conn
->reply_sent
== 0);
771 iov
[0].iov_base
= conn
->header
;
772 iov
[0].iov_len
= conn
->header_length
;
774 iov
[1].iov_base
= conn
->reply
+ conn
->reply_sent
;
775 iov
[1].iov_len
= conn
->reply_length
- conn
->reply_sent
;
777 sent
= writev(conn
->socket
, iov
, 2);
778 conn
->last_active
= now
;
780 /* handle any errors (-1) or closure (0) in send() */
783 verbosef("writev(%d) error: %s", conn
->socket
, strerror(errno
));
788 /* Figure out what we've sent. */
789 conn
->total_sent
+= (unsigned int)sent
;
790 if (sent
< (ssize_t
)conn
->header_length
) {
791 verbosef("partially sent header");
792 conn
->header_sent
= sent
;
793 conn
->state
= SEND_HEADER
;
797 conn
->header_sent
= conn
->header_length
;
798 sent
-= conn
->header_length
;
800 if (conn
->reply_sent
+ sent
< conn
->reply_length
) {
801 verbosef("partially sent reply");
802 conn
->reply_sent
+= sent
;
803 conn
->state
= SEND_REPLY
;
807 conn
->reply_sent
= conn
->reply_length
;
811 /* ---------------------------------------------------------------------------
812 * Sending header. Assumes conn->header is not NULL.
814 static void poll_send_header(struct connection
*conn
)
818 sent
= send(conn
->socket
, conn
->header
+ conn
->header_sent
,
819 conn
->header_length
- conn
->header_sent
, 0);
820 conn
->last_active
= now
;
821 dverbosef("poll_send_header(%d) sent %d bytes", conn
->socket
, (int)sent
);
823 /* handle any errors (-1) or closure (0) in send() */
827 verbosef("send(%d) error: %s", conn
->socket
, strerror(errno
));
831 conn
->header_sent
+= (unsigned int)sent
;
832 conn
->total_sent
+= (unsigned int)sent
;
834 /* check if we're done sending */
835 if (conn
->header_sent
== conn
->header_length
)
837 if (conn
->header_only
)
840 conn
->state
= SEND_REPLY
;
846 /* ---------------------------------------------------------------------------
849 static void poll_send_reply(struct connection
*conn
)
853 sent
= send(conn
->socket
,
854 conn
->reply
+ conn
->reply_sent
,
855 conn
->reply_length
- conn
->reply_sent
, 0);
856 conn
->last_active
= now
;
857 dverbosef("poll_send_reply(%d) sent %d: [%d-%d] of %d",
858 conn
->socket
, (int)sent
,
859 (int)conn
->reply_sent
,
860 (int)(conn
->reply_sent
+ sent
- 1),
861 (int)conn
->reply_length
);
863 /* handle any errors (-1) or closure (0) in send() */
867 verbosef("send(%d) error: %s", conn
->socket
, strerror(errno
));
869 verbosef("send(%d) closure", conn
->socket
);
873 conn
->reply_sent
+= (unsigned int)sent
;
874 conn
->total_sent
+= (unsigned int)sent
;
876 /* check if we're done sending */
877 if (conn
->reply_sent
== conn
->reply_length
) conn
->state
= DONE
;
882 /* --------------------------------------------------------------------------
883 * Initialize the base path.
885 void http_init_base(const char *url
)
887 char *slashed_url
, *safe_url
;
890 /* make sure that the url has leading and trailing slashes */
891 urllen
= strlen(url
);
892 slashed_url
= xmalloc(urllen
+3);
893 memset(slashed_url
, '/', urllen
+2);
894 memcpy(slashed_url
+1, url
, urllen
); /* don't copy NULL */
895 slashed_url
[urllen
+2] = '\0';
898 safe_url
= make_safe_uri(slashed_url
);
900 if (safe_url
== NULL
)
902 verbosef("invalid base \"%s\", ignored", url
, "/");
909 /* --------------------------------------------------------------------------
910 * Initialize the sockin global. This is the socket that we accept
911 * connections from. Pass -1 as max_conn for system limit.
913 void http_init(const char *bindaddr
, const unsigned short bindport
,
916 struct sockaddr_storage addrin
;
917 struct addrinfo hints
, *ai
, *aiptr
;
918 char ipaddr
[INET6_ADDRSTRLEN
], portstr
[12];
921 memset(&hints
, 0, sizeof(hints
));
922 hints
.ai_family
= AF_UNSPEC
;
923 hints
.ai_socktype
= SOCK_STREAM
;
924 hints
.ai_flags
= AI_PASSIVE
;
926 hints
.ai_flags
|= AI_ADDRCONFIG
;
928 snprintf(portstr
, sizeof(portstr
), "%u", bindport
);
930 if ((ret
= getaddrinfo(bindaddr
, portstr
, &hints
, &aiptr
)))
931 err(1, "getaddrinfo(): %s", gai_strerror(ret
));
933 for (ai
= aiptr
; ai
; ai
= ai
->ai_next
) {
934 /* create incoming socket */
935 sockin
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
941 if (setsockopt(sockin
, SOL_SOCKET
, SO_REUSEADDR
,
942 &sockopt
, sizeof(sockopt
)) == -1) {
947 /* Recover address and port strings. */
948 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, ipaddr
, sizeof(ipaddr
),
949 NULL
, 0, NI_NUMERICHOST
);
952 memcpy(&addrin
, ai
->ai_addr
, ai
->ai_addrlen
);
953 if (bind(sockin
, (struct sockaddr
*)&addrin
, ai
->ai_addrlen
) == -1) {
958 verbosef("listening on %s:%u", ipaddr
, bindport
);
960 /* listen on socket */
961 if (listen(sockin
, max_conn
) >= 0)
962 /* Successfully bound and now listening. */
965 /* Next candidate. */
972 err(1, "getaddrinfo() unable to locate address");
975 if (signal(SIGPIPE
, SIG_IGN
) == SIG_ERR
)
976 err(1, "can't ignore SIGPIPE");
981 /* ---------------------------------------------------------------------------
982 * Set recv/send fd_sets and calculate timeout length.
985 http_fd_set(fd_set
*recv_set
, fd_set
*send_set
, int *max_fd
,
986 struct timeval
*timeout
, int *need_timeout
)
988 struct connection
*conn
, *next
;
989 int minidle
= idletime
+ 1;
991 #define MAX_FD_SET(sock, fdset) do { \
992 FD_SET(sock, fdset); *max_fd = max(*max_fd, sock); } while(0)
994 MAX_FD_SET(sockin
, recv_set
);
996 LIST_FOREACH_SAFE(conn
, &connlist
, entries
, next
)
998 int idlefor
= now
- conn
->last_active
;
1000 /* Time out dead connections. */
1001 if (idlefor
>= idletime
)
1003 char ipaddr
[INET6_ADDRSTRLEN
];
1004 getnameinfo((struct sockaddr
*) &conn
->client
, sizeof(conn
->client
),
1005 ipaddr
, sizeof(ipaddr
), NULL
, 0, NI_NUMERICHOST
);
1006 verbosef("http socket timeout from %s (fd %d)",
1007 ipaddr
, conn
->socket
);
1011 /* Connections that need a timeout. */
1012 if (conn
->state
!= DONE
)
1013 minidle
= min(minidle
, (idletime
- idlefor
));
1015 switch (conn
->state
)
1018 /* clean out stale connection */
1019 LIST_REMOVE(conn
, entries
);
1020 free_connection(conn
);
1025 MAX_FD_SET(conn
->socket
, recv_set
);
1028 case SEND_HEADER_AND_REPLY
:
1031 MAX_FD_SET(conn
->socket
, send_set
);
1034 default: errx(1, "invalid state");
1039 /* Only set timeout if cap hasn't already. */
1040 if ((*need_timeout
== 0) && (minidle
<= idletime
)) {
1042 timeout
->tv_sec
= minidle
;
1043 timeout
->tv_usec
= 0;
1049 /* ---------------------------------------------------------------------------
1050 * poll connections that select() says need attention
1052 void http_poll(fd_set
*recv_set
, fd_set
*send_set
)
1054 struct connection
*conn
;
1056 if (FD_ISSET(sockin
, recv_set
)) accept_connection();
1058 LIST_FOREACH(conn
, &connlist
, entries
)
1059 switch (conn
->state
)
1062 if (FD_ISSET(conn
->socket
, recv_set
)) poll_recv_request(conn
);
1065 case SEND_HEADER_AND_REPLY
:
1066 if (FD_ISSET(conn
->socket
, send_set
)) poll_send_header_and_reply(conn
);
1070 if (FD_ISSET(conn
->socket
, send_set
)) poll_send_header(conn
);
1074 if (FD_ISSET(conn
->socket
, send_set
)) poll_send_reply(conn
);
1077 case DONE
: /* fallthrough */
1078 default: errx(1, "invalid state");
1082 /* vim:set ts=4 sw=4 et tw=78: */