b513ce279b00316c3f130ae42d79dc0198989784
[darkstat] / http.c
1 /* darkstat 3
2 * copyright (c) 2001-2008 Emil Mikulic.
3 *
4 * http.c: embedded webserver.
5 * This borrows a lot of code from darkhttpd.
6 *
7 * You may use, modify and redistribute this file under the terms of the
8 * GNU General Public License version 2. (see COPYING.GPL)
9 */
10
11 #include "darkstat.h"
12 #include "http.h"
13 #include "conv.h"
14 #include "hosts_db.h"
15 #include "graph_db.h"
16 #include "err.h"
17 #include "queue.h"
18 #include "now.h"
19
20 #include <sys/uio.h>
21 #include <sys/socket.h>
22 #include <arpa/inet.h>
23 #include <netinet/in.h>
24 #include <netdb.h>
25 #include <assert.h>
26 #include <ctype.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <zlib.h>
36
37 const char *base_url = "/";
38
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_gzip[] =
44 "Vary: Accept-Encoding\r\n"
45 "Content-Encoding: gzip\r\n";
46
47 static const char server[] = PACKAGE_NAME "/" PACKAGE_VERSION;
48 static int idletime = 60;
49 static int sockin = -1; /* socket to accept connections from */
50 #define MAX_REQUEST_LENGTH 4000
51
52 #ifndef min
53 #define min(a,b) (((a) < (b)) ? (a) : (b))
54 #endif
55
56 struct connection {
57 LIST_ENTRY(connection) entries;
58
59 int socket;
60 struct sockaddr_storage client;
61 time_t last_active;
62 enum {
63 RECV_REQUEST, /* receiving request */
64 SEND_HEADER_AND_REPLY, /* try to send header+reply together */
65 SEND_HEADER, /* sending generated header */
66 SEND_REPLY, /* sending reply */
67 DONE /* conn closed, need to remove from queue */
68 } state;
69
70 /* char request[request_length+1] is null-terminated */
71 char *request;
72 size_t request_length;
73 int accept_gzip;
74
75 /* request fields */
76 char *method, *uri, *query; /* query can be NULL */
77
78 char *header;
79 const char *mime_type, *encoding, *header_extra;
80 size_t header_length, header_sent;
81 int header_dont_free, header_only, http_code;
82
83 char *reply;
84 int reply_dont_free;
85 size_t reply_length, reply_sent;
86
87 unsigned int total_sent; /* header + body = total, for logging */
88 };
89
90 static LIST_HEAD(conn_list_head, connection) connlist =
91 LIST_HEAD_INITIALIZER(conn_list_head);
92
93 /* ---------------------------------------------------------------------------
94 * Decode URL by converting %XX (where XX are hexadecimal digits) to the
95 * character it represents. Don't forget to free the return value.
96 */
97 static char *urldecode(const char *url)
98 {
99 size_t i, len = strlen(url);
100 char *out = xmalloc(len+1);
101 int pos;
102
103 for (i=0, pos=0; i<len; i++)
104 {
105 if (url[i] == '%' && i+2 < len &&
106 isxdigit(url[i+1]) && isxdigit(url[i+2]))
107 {
108 /* decode %XX */
109 #define HEX_TO_DIGIT(hex) ( \
110 ((hex) >= 'A' && (hex) <= 'F') ? ((hex)-'A'+10): \
111 ((hex) >= 'a' && (hex) <= 'f') ? ((hex)-'a'+10): \
112 ((hex)-'0') )
113
114 out[pos++] = HEX_TO_DIGIT(url[i+1]) * 16 +
115 HEX_TO_DIGIT(url[i+2]);
116 i += 2;
117
118 #undef HEX_TO_DIGIT
119 }
120 else
121 {
122 /* straight copy */
123 out[pos++] = url[i];
124 }
125 }
126 out[pos] = 0;
127 #if 0
128 /* don't really need to realloc here - it's probably a performance hit */
129 out = xrealloc(out, strlen(out)+1); /* dealloc what we don't need */
130 #endif
131 return (out);
132 }
133
134
135
136 /* ---------------------------------------------------------------------------
137 * Consolidate slashes in-place by shifting parts of the string over repeated
138 * slashes.
139 */
140 static void consolidate_slashes(char *s)
141 {
142 size_t left = 0, right = 0;
143 int saw_slash = 0;
144
145 assert(s != NULL);
146
147 while (s[right] != '\0')
148 {
149 if (saw_slash)
150 {
151 if (s[right] == '/') right++;
152 else
153 {
154 saw_slash = 0;
155 s[left++] = s[right++];
156 }
157 }
158 else
159 {
160 if (s[right] == '/') saw_slash++;
161 s[left++] = s[right++];
162 }
163 }
164 s[left] = '\0';
165 }
166
167
168
169 /* ---------------------------------------------------------------------------
170 * Resolve /./ and /../ in a URI, returing a new, safe URI, or NULL if the URI
171 * is invalid/unsafe. Returned buffer needs to be deallocated.
172 */
173 static char *make_safe_uri(char *uri)
174 {
175 char **elem, *out;
176 unsigned int slashes = 0, elements = 0;
177 size_t urilen, i, j, pos;
178
179 assert(uri != NULL);
180 if (uri[0] != '/')
181 return (NULL);
182 consolidate_slashes(uri);
183 urilen = strlen(uri);
184
185 /* count the slashes */
186 for (i=0, slashes=0; i<urilen; i++)
187 if (uri[i] == '/') slashes++;
188
189 /* make an array for the URI elements */
190 elem = xmalloc(sizeof(*elem) * slashes);
191 for (i=0; i<slashes; i++)
192 elem[i] = (NULL);
193
194 /* split by slashes and build elem[] array */
195 for (i=1; i<urilen;)
196 {
197 /* look for the next slash */
198 for (j=i; j<urilen && uri[j] != '/'; j++)
199 ;
200
201 /* process uri[i,j) */
202 if ((j == i+1) && (uri[i] == '.'))
203 /* "." */;
204 else if ((j == i+2) && (uri[i] == '.') && (uri[i+1] == '.'))
205 {
206 /* ".." */
207 if (elements == 0)
208 {
209 /*
210 * Unsafe string so free elem[]. All its elements are free
211 * at this point.
212 */
213 free(elem);
214 return (NULL);
215 }
216 else
217 {
218 elements--;
219 free(elem[elements]);
220 }
221 }
222 else elem[elements++] = split_string(uri, i, j);
223
224 i = j + 1; /* uri[j] is a slash - move along one */
225 }
226
227 /* reassemble */
228 out = xmalloc(urilen+1); /* it won't expand */
229 pos = 0;
230 for (i=0; i<elements; i++)
231 {
232 size_t delta = strlen(elem[i]);
233
234 assert(pos <= urilen);
235 out[pos++] = '/';
236
237 assert(pos+delta <= urilen);
238 memcpy(out+pos, elem[i], delta);
239 free(elem[i]);
240 pos += delta;
241 }
242 free(elem);
243
244 if ((elements == 0) || (uri[urilen-1] == '/')) out[pos++] = '/';
245 assert(pos <= urilen);
246 out[pos] = '\0';
247
248 #if 0
249 /* don't really need to do this and it's probably a performance hit: */
250 /* shorten buffer if necessary */
251 if (pos != urilen) out = xrealloc(out, strlen(out)+1);
252 #endif
253 return (out);
254 }
255
256 /* ---------------------------------------------------------------------------
257 * Allocate and initialize an empty connection.
258 */
259 static struct connection *new_connection(void)
260 {
261 struct connection *conn = xmalloc(sizeof(*conn));
262
263 conn->socket = -1;
264 memset(&conn->client, 0, sizeof(conn->client));
265 conn->last_active = now;
266 conn->request = NULL;
267 conn->request_length = 0;
268 conn->accept_gzip = 0;
269 conn->method = NULL;
270 conn->uri = NULL;
271 conn->query = NULL;
272 conn->header = NULL;
273 conn->mime_type = NULL;
274 conn->encoding = "";
275 conn->header_extra = "";
276 conn->header_length = 0;
277 conn->header_sent = 0;
278 conn->header_dont_free = 0;
279 conn->header_only = 0;
280 conn->http_code = 0;
281 conn->reply = NULL;
282 conn->reply_dont_free = 0;
283 conn->reply_length = 0;
284 conn->reply_sent = 0;
285 conn->total_sent = 0;
286
287 /* Make it harmless so it gets garbage-collected if it should, for some
288 * reason, fail to be correctly filled out.
289 */
290 conn->state = DONE;
291
292 return (conn);
293 }
294
295
296
297 /* ---------------------------------------------------------------------------
298 * Accept a connection from sockin and add it to the connection queue.
299 */
300 static void accept_connection(void)
301 {
302 struct sockaddr_storage addrin;
303 socklen_t sin_size;
304 struct connection *conn;
305 char ipaddr[INET6_ADDRSTRLEN], portstr[12];
306 int sock;
307
308 sin_size = (socklen_t)sizeof(addrin);
309 sock = accept(sockin, &addrin, &sin_size);
310 if (sock == -1)
311 {
312 if (errno == ECONNABORTED || errno == EINTR)
313 {
314 verbosef("accept() failed: %s", strerror(errno));
315 return;
316 }
317 /* else */ err(1, "accept()");
318 }
319
320 fd_set_nonblock(sock);
321
322 /* allocate and initialise struct connection */
323 conn = new_connection();
324 conn->socket = sock;
325 conn->state = RECV_REQUEST;
326 memcpy(&conn->client, &addrin, sizeof(conn->client));
327 LIST_INSERT_HEAD(&connlist, conn, entries);
328
329 getnameinfo((struct sockaddr *) &addrin, sin_size,
330 ipaddr, sizeof(ipaddr), portstr, sizeof(portstr),
331 NI_NUMERICHOST | NI_NUMERICSERV);
332 verbosef("accepted connection from %s:%s", ipaddr, portstr);
333 }
334
335
336
337 /* ---------------------------------------------------------------------------
338 * Log a connection, then cleanly deallocate its internals.
339 */
340 static void free_connection(struct connection *conn)
341 {
342 dverbosef("free_connection(%d)", conn->socket);
343 if (conn->socket != -1) close(conn->socket);
344 if (conn->request != NULL) free(conn->request);
345 if (conn->method != NULL) free(conn->method);
346 if (conn->uri != NULL) free(conn->uri);
347 if (conn->query != NULL) free(conn->query);
348 if (conn->header != NULL && !conn->header_dont_free) free(conn->header);
349 if (conn->reply != NULL && !conn->reply_dont_free) free(conn->reply);
350 }
351
352
353
354 /* ---------------------------------------------------------------------------
355 * Format [when] as an RFC1123 date, stored in the specified buffer. The same
356 * buffer is returned for convenience.
357 */
358 #define DATE_LEN 30 /* strlen("Fri, 28 Feb 2003 00:02:08 GMT")+1 */
359 static char *rfc1123_date(char *dest, const time_t when)
360 {
361 time_t tmp = when;
362 if (strftime(dest, DATE_LEN,
363 "%a, %d %b %Y %H:%M:%S %Z", gmtime(&tmp) ) == 0)
364 errx(1, "strftime() failed [%s]", dest);
365 return (dest);
366 }
367
368
369
370 /* ---------------------------------------------------------------------------
371 * A default reply for any (erroneous) occasion.
372 */
373 static void default_reply(struct connection *conn,
374 const int errcode, const char *errname, const char *format, ...)
375 {
376 char *reason, date[DATE_LEN];
377 va_list va;
378
379 va_start(va, format);
380 xvasprintf(&reason, format, va);
381 va_end(va);
382
383 /* Only really need to calculate the date once. */
384 (void)rfc1123_date(date, now);
385
386 conn->reply_length = xasprintf(&(conn->reply),
387 "<html><head><title>%d %s</title></head><body>\n"
388 "<h1>%s</h1>\n" /* errname */
389 "%s\n" /* reason */
390 "<hr>\n"
391 "Generated by %s on %s\n"
392 "</body></html>\n",
393 errcode, errname, errname, reason, server, date);
394 free(reason);
395
396 conn->header_length = xasprintf(&(conn->header),
397 "HTTP/1.1 %d %s\r\n"
398 "Date: %s\r\n"
399 "Server: %s\r\n"
400 "Content-Length: %d\r\n"
401 "Content-Type: text/html\r\n"
402 "\r\n",
403 errcode, errname, date, server, conn->reply_length);
404
405 conn->http_code = errcode;
406 }
407
408
409
410 /* ---------------------------------------------------------------------------
411 * Parses a single HTTP request field. Returns string from end of [field] to
412 * first \r, \n or end of request string. Returns NULL if [field] can't be
413 * matched.
414 *
415 * You need to remember to deallocate the result.
416 * example: parse_field(conn, "Referer: ");
417 */
418 static char *parse_field(const struct connection *conn, const char *field)
419 {
420 size_t bound1, bound2;
421 char *pos;
422
423 /* find start */
424 pos = strstr(conn->request, field);
425 if (pos == NULL)
426 return (NULL);
427 bound1 = pos - conn->request + strlen(field);
428
429 /* find end */
430 for (bound2 = bound1;
431 conn->request[bound2] != '\r' &&
432 bound2 < conn->request_length; bound2++)
433 ;
434
435 /* copy to buffer */
436 return (split_string(conn->request, bound1, bound2));
437 }
438
439
440
441 /* ---------------------------------------------------------------------------
442 * Parse an HTTP request like "GET /hosts/?sort=in HTTP/1.1" to get the method
443 * (GET), the uri (/hosts/), the query (sort=in) and whether the UA will
444 * accept gzip encoding. Remember to deallocate all these buffers. Query
445 * can be NULL. The method will be returned in uppercase.
446 */
447 static int parse_request(struct connection *conn)
448 {
449 size_t bound1, bound2, mid;
450 char *accept_enc;
451
452 /* parse method */
453 for (bound1 = 0; bound1 < conn->request_length &&
454 conn->request[bound1] != ' '; bound1++)
455 ;
456
457 conn->method = split_string(conn->request, 0, bound1);
458 strntoupper(conn->method, bound1);
459
460 /* parse uri */
461 for (; bound1 < conn->request_length &&
462 conn->request[bound1] == ' '; bound1++)
463 ;
464
465 if (bound1 == conn->request_length)
466 return (0); /* fail */
467
468 for (bound2=bound1+1; bound2 < conn->request_length &&
469 conn->request[bound2] != ' ' &&
470 conn->request[bound2] != '\r'; bound2++)
471 ;
472
473 /* find query string */
474 for (mid=bound1; mid<bound2 && conn->request[mid] != '?'; mid++)
475 ;
476
477 if (conn->request[mid] == '?') {
478 conn->query = split_string(conn->request, mid+1, bound2);
479 bound2 = mid;
480 }
481
482 conn->uri = split_string(conn->request, bound1, bound2);
483
484 /* parse important fields */
485 accept_enc = parse_field(conn, "Accept-Encoding: ");
486 if (accept_enc != NULL) {
487 if (strstr(accept_enc, "gzip") != NULL)
488 conn->accept_gzip = 1;
489 free(accept_enc);
490 }
491 return (1);
492 }
493
494 /* FIXME: maybe we need a smarter way of doing static pages: */
495
496 /* ---------------------------------------------------------------------------
497 * Web interface: static stylesheet.
498 */
499 static void
500 static_style_css(struct connection *conn)
501 {
502 #include "stylecss.h"
503
504 conn->reply = style_css;
505 conn->reply_length = style_css_len;
506 conn->reply_dont_free = 1;
507 conn->mime_type = mime_type_css;
508 }
509
510 /* ---------------------------------------------------------------------------
511 * Web interface: static JavaScript.
512 */
513 static void
514 static_graph_js(struct connection *conn)
515 {
516 #include "graphjs.h"
517
518 conn->reply = graph_js;
519 conn->reply_length = graph_js_len;
520 conn->reply_dont_free = 1;
521 conn->mime_type = mime_type_js;
522 }
523
524 /* ---------------------------------------------------------------------------
525 * gzip a reply, if requested and possible. Don't bother with a minimum
526 * length requirement, I've never seen a page fail to compress.
527 */
528 static void
529 process_gzip(struct connection *conn)
530 {
531 char *buf;
532 size_t len;
533 z_stream zs;
534
535 if (!conn->accept_gzip)
536 return;
537
538 buf = xmalloc(conn->reply_length);
539 len = conn->reply_length;
540
541 zs.zalloc = Z_NULL;
542 zs.zfree = Z_NULL;
543 zs.opaque = Z_NULL;
544
545 if (deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED,
546 15+16, /* 15 = biggest window, 16 = add gzip header+trailer */
547 8 /* default */,
548 Z_DEFAULT_STRATEGY) != Z_OK)
549 return;
550
551 zs.avail_in = conn->reply_length;
552 zs.next_in = (unsigned char *)conn->reply;
553
554 zs.avail_out = conn->reply_length;
555 zs.next_out = (unsigned char *)buf;
556
557 if (deflate(&zs, Z_FINISH) != Z_STREAM_END) {
558 deflateEnd(&zs);
559 free(buf);
560 verbosef("failed to compress %u bytes", (unsigned int)len);
561 return;
562 }
563
564 if (conn->reply_dont_free)
565 conn->reply_dont_free = 0;
566 else
567 free(conn->reply);
568
569 conn->reply = buf;
570 conn->reply_length -= zs.avail_out;
571 conn->encoding = encoding_gzip;
572 deflateEnd(&zs);
573 }
574
575 /* ---------------------------------------------------------------------------
576 * Process a GET/HEAD request
577 */
578 static void process_get(struct connection *conn)
579 {
580 char *decoded_url, *safe_url;
581 char date[DATE_LEN];
582
583 verbosef("http: %s \"%s\" %s", conn->method, conn->uri,
584 (conn->query == NULL)?"":conn->query);
585
586 /* work out path of file being requested */
587 decoded_url = urldecode(conn->uri);
588
589 /* make sure it's safe */
590 safe_url = make_safe_uri(decoded_url);
591 free(decoded_url);
592 if (safe_url == NULL)
593 {
594 default_reply(conn, 400, "Bad Request",
595 "You requested an invalid URI: %s", conn->uri);
596 return;
597 }
598
599 if (strcmp(safe_url, "/") == 0) {
600 struct str *buf = html_front_page();
601 str_extract(buf, &(conn->reply_length), &(conn->reply));
602 conn->mime_type = mime_type_html;
603 }
604 else if (str_starts_with(safe_url, "/hosts/")) {
605 /* FIXME here - make this saner */
606 struct str *buf = html_hosts(safe_url, conn->query);
607 if (buf == NULL) {
608 default_reply(conn, 404, "Not Found",
609 "The page you requested could not be found.");
610 return;
611 }
612 str_extract(buf, &(conn->reply_length), &(conn->reply));
613 conn->mime_type = mime_type_html;
614 }
615 else if (str_starts_with(safe_url, "/graphs.xml")) {
616 struct str *buf = xml_graphs();
617 str_extract(buf, &(conn->reply_length), &(conn->reply));
618 conn->mime_type = mime_type_xml;
619 /* hack around Opera caching the XML */
620 conn->header_extra = "Pragma: no-cache\r\n";
621 }
622 else if (strcmp(safe_url, "/style.css") == 0)
623 static_style_css(conn);
624 else if (strcmp(safe_url, "/graph.js") == 0)
625 static_graph_js(conn);
626 else {
627 default_reply(conn, 404, "Not Found",
628 "The page you requested could not be found.");
629 return;
630 }
631 free(safe_url);
632
633 process_gzip(conn);
634 assert(conn->mime_type != NULL);
635 conn->header_length = xasprintf(&(conn->header),
636 "HTTP/1.1 200 OK\r\n"
637 "Date: %s\r\n"
638 "Server: %s\r\n"
639 "Content-Length: %d\r\n"
640 "Content-Type: %s\r\n"
641 "%s"
642 "%s"
643 "\r\n"
644 ,
645 rfc1123_date(date, now), server,
646 conn->reply_length, conn->mime_type, conn->encoding,
647 conn->header_extra);
648 conn->http_code = 200;
649 }
650
651
652
653 /* ---------------------------------------------------------------------------
654 * Process a request: build the header and reply, advance state.
655 */
656 static void process_request(struct connection *conn)
657 {
658 if (!parse_request(conn))
659 {
660 default_reply(conn, 400, "Bad Request",
661 "You sent a request that the server couldn't understand.");
662 }
663 else if (strcmp(conn->method, "GET") == 0)
664 {
665 process_get(conn);
666 }
667 else if (strcmp(conn->method, "HEAD") == 0)
668 {
669 process_get(conn);
670 conn->header_only = 1;
671 }
672 else
673 {
674 default_reply(conn, 501, "Not Implemented",
675 "The method you specified (%s) is not implemented.",
676 conn->method);
677 }
678
679 /* advance state */
680 if (conn->header_only)
681 conn->state = SEND_HEADER;
682 else
683 conn->state = SEND_HEADER_AND_REPLY;
684
685 /* request not needed anymore */
686 free(conn->request);
687 conn->request = NULL; /* important: don't free it again later */
688 }
689
690
691
692 /* ---------------------------------------------------------------------------
693 * Receiving request.
694 */
695 static void poll_recv_request(struct connection *conn)
696 {
697 #define BUFSIZE 65536
698 char buf[BUFSIZE];
699 ssize_t recvd;
700
701 recvd = recv(conn->socket, buf, BUFSIZE, 0);
702 dverbosef("poll_recv_request(%d) got %d bytes", conn->socket, (int)recvd);
703 if (recvd <= 0)
704 {
705 if (recvd == -1)
706 verbosef("recv(%d) error: %s", conn->socket, strerror(errno));
707 conn->state = DONE;
708 return;
709 }
710 conn->last_active = now;
711 #undef BUFSIZE
712
713 /* append to conn->request */
714 conn->request = xrealloc(conn->request, conn->request_length+recvd+1);
715 memcpy(conn->request+conn->request_length, buf, (size_t)recvd);
716 conn->request_length += recvd;
717 conn->request[conn->request_length] = 0;
718
719 /* process request if we have all of it */
720 if (conn->request_length > 4 &&
721 memcmp(conn->request+conn->request_length-4, "\r\n\r\n", 4) == 0)
722 process_request(conn);
723
724 /* die if it's too long */
725 if (conn->request_length > MAX_REQUEST_LENGTH)
726 {
727 default_reply(conn, 413, "Request Entity Too Large",
728 "Your request was dropped because it was too long.");
729 conn->state = SEND_HEADER;
730 }
731 }
732
733
734
735 /* ---------------------------------------------------------------------------
736 * Try to send header and [a part of the] reply in one packet.
737 */
738 static void poll_send_header_and_reply(struct connection *conn)
739 {
740 ssize_t sent;
741 struct iovec iov[2];
742
743 assert(!conn->header_only);
744 assert(conn->reply_length > 0);
745 assert(conn->header_sent == 0);
746
747 assert(conn->reply_sent == 0);
748
749 /* Fill out iovec */
750 iov[0].iov_base = conn->header;
751 iov[0].iov_len = conn->header_length;
752
753 iov[1].iov_base = conn->reply + conn->reply_sent;
754 iov[1].iov_len = conn->reply_length - conn->reply_sent;
755
756 sent = writev(conn->socket, iov, 2);
757 conn->last_active = now;
758
759 /* handle any errors (-1) or closure (0) in send() */
760 if (sent < 1) {
761 if (sent == -1)
762 verbosef("writev(%d) error: %s", conn->socket, strerror(errno));
763 conn->state = DONE;
764 return;
765 }
766
767 /* Figure out what we've sent. */
768 conn->total_sent += (unsigned int)sent;
769 if (sent < (ssize_t)conn->header_length) {
770 verbosef("partially sent header");
771 conn->header_sent = sent;
772 conn->state = SEND_HEADER;
773 return;
774 }
775 /* else */
776 conn->header_sent = conn->header_length;
777 sent -= conn->header_length;
778
779 if (conn->reply_sent + sent < conn->reply_length) {
780 verbosef("partially sent reply");
781 conn->reply_sent += sent;
782 conn->state = SEND_REPLY;
783 return;
784 }
785 /* else */
786 conn->reply_sent = conn->reply_length;
787 conn->state = DONE;
788 }
789
790 /* ---------------------------------------------------------------------------
791 * Sending header. Assumes conn->header is not NULL.
792 */
793 static void poll_send_header(struct connection *conn)
794 {
795 ssize_t sent;
796
797 sent = send(conn->socket, conn->header + conn->header_sent,
798 conn->header_length - conn->header_sent, 0);
799 conn->last_active = now;
800 dverbosef("poll_send_header(%d) sent %d bytes", conn->socket, (int)sent);
801
802 /* handle any errors (-1) or closure (0) in send() */
803 if (sent < 1)
804 {
805 if (sent == -1)
806 verbosef("send(%d) error: %s", conn->socket, strerror(errno));
807 conn->state = DONE;
808 return;
809 }
810 conn->header_sent += (unsigned int)sent;
811 conn->total_sent += (unsigned int)sent;
812
813 /* check if we're done sending */
814 if (conn->header_sent == conn->header_length)
815 {
816 if (conn->header_only)
817 conn->state = DONE;
818 else
819 conn->state = SEND_REPLY;
820 }
821 }
822
823
824
825 /* ---------------------------------------------------------------------------
826 * Sending reply.
827 */
828 static void poll_send_reply(struct connection *conn)
829 {
830 ssize_t sent;
831
832 sent = send(conn->socket,
833 conn->reply + conn->reply_sent,
834 conn->reply_length - conn->reply_sent, 0);
835 conn->last_active = now;
836 dverbosef("poll_send_reply(%d) sent %d: [%d-%d] of %d",
837 conn->socket, (int)sent,
838 (int)conn->reply_sent,
839 (int)(conn->reply_sent + sent - 1),
840 (int)conn->reply_length);
841
842 /* handle any errors (-1) or closure (0) in send() */
843 if (sent < 1)
844 {
845 if (sent == -1)
846 verbosef("send(%d) error: %s", conn->socket, strerror(errno));
847 else if (sent == 0)
848 verbosef("send(%d) closure", conn->socket);
849 conn->state = DONE;
850 return;
851 }
852 conn->reply_sent += (unsigned int)sent;
853 conn->total_sent += (unsigned int)sent;
854
855 /* check if we're done sending */
856 if (conn->reply_sent == conn->reply_length) conn->state = DONE;
857 }
858
859
860
861 /* ---------------------------------------------------------------------------
862 * Initialize the sockin global. This is the socket that we accept
863 * connections from. Pass -1 as max_conn for system limit.
864 */
865 void http_init(const char *bindaddr, const unsigned short bindport,
866 const int max_conn)
867 {
868 struct sockaddr_storage addrin;
869 struct addrinfo hints, *ai, *aiptr;
870 char ipaddr[INET6_ADDRSTRLEN], portstr[12];
871 int sockopt, ret;
872
873 memset(&hints, 0, sizeof(hints));
874 hints.ai_family = AF_UNSPEC;
875 hints.ai_socktype = SOCK_STREAM;
876 hints.ai_flags = AI_PASSIVE;
877 #ifdef AI_ADDRCONFIG
878 hints.ai_flags |= AI_ADDRCONFIG;
879 #endif
880 snprintf(portstr, sizeof(portstr), "%u", bindport);
881
882 if ((ret = getaddrinfo(bindaddr, portstr, &hints, &aiptr)))
883 err(1, "getaddrinfo(): %s", gai_strerror(ret));
884
885 for (ai = aiptr; ai; ai = ai->ai_next) {
886 /* create incoming socket */
887 sockin = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
888 if (sockin == -1)
889 continue;
890
891 /* reuse address */
892 sockopt = 1;
893 if (setsockopt(sockin, SOL_SOCKET, SO_REUSEADDR,
894 &sockopt, sizeof(sockopt)) == -1) {
895 close(sockin);
896 continue;
897 }
898
899 /* Recover address and port strings. */
900 getnameinfo(ai->ai_addr, ai->ai_addrlen, ipaddr, sizeof(ipaddr),
901 NULL, 0, NI_NUMERICHOST);
902
903 /* bind socket */
904 memcpy(&addrin, ai->ai_addr, ai->ai_addrlen);
905 if (bind(sockin, (struct sockaddr *)&addrin, ai->ai_addrlen) == -1) {
906 close(sockin);
907 continue;
908 }
909
910 verbosef("listening on %s:%u", ipaddr, bindport);
911
912 /* listen on socket */
913 if (listen(sockin, max_conn) >= 0)
914 /* Successfully bound and now listening. */
915 break;
916
917 /* Next candidate. */
918 continue;
919 }
920
921 freeaddrinfo(aiptr);
922
923 if (ai == NULL)
924 err(1, "getaddrinfo() unable to locate address");
925
926 /* ignore SIGPIPE */
927 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
928 err(1, "can't ignore SIGPIPE");
929 }
930
931
932
933 /* ---------------------------------------------------------------------------
934 * Set recv/send fd_sets and calculate timeout length.
935 */
936 void
937 http_fd_set(fd_set *recv_set, fd_set *send_set, int *max_fd,
938 struct timeval *timeout, int *need_timeout)
939 {
940 struct connection *conn, *next;
941 int minidle = idletime + 1;
942
943 #define MAX_FD_SET(sock, fdset) do { \
944 FD_SET(sock, fdset); *max_fd = max(*max_fd, sock); } while(0)
945
946 MAX_FD_SET(sockin, recv_set);
947
948 LIST_FOREACH_SAFE(conn, &connlist, entries, next)
949 {
950 int idlefor = now - conn->last_active;
951
952 /* Time out dead connections. */
953 if (idlefor >= idletime)
954 {
955 char ipaddr[INET6_ADDRSTRLEN];
956 getnameinfo((struct sockaddr *) &conn->client, sizeof(conn->client),
957 ipaddr, sizeof(ipaddr), NULL, 0, NI_NUMERICHOST);
958 verbosef("http socket timeout from %s (fd %d)",
959 ipaddr, conn->socket);
960 conn->state = DONE;
961 }
962
963 /* Connections that need a timeout. */
964 if (conn->state != DONE)
965 minidle = min(minidle, (idletime - idlefor));
966
967 switch (conn->state)
968 {
969 case DONE:
970 /* clean out stale connection */
971 LIST_REMOVE(conn, entries);
972 free_connection(conn);
973 free(conn);
974 break;
975
976 case RECV_REQUEST:
977 MAX_FD_SET(conn->socket, recv_set);
978 break;
979
980 case SEND_HEADER_AND_REPLY:
981 case SEND_HEADER:
982 case SEND_REPLY:
983 MAX_FD_SET(conn->socket, send_set);
984 break;
985
986 default: errx(1, "invalid state");
987 }
988 }
989 #undef MAX_FD_SET
990
991 /* Only set timeout if cap hasn't already. */
992 if ((*need_timeout == 0) && (minidle <= idletime)) {
993 *need_timeout = 1;
994 timeout->tv_sec = minidle;
995 timeout->tv_usec = 0;
996 }
997 }
998
999
1000
1001 /* ---------------------------------------------------------------------------
1002 * poll connections that select() says need attention
1003 */
1004 void http_poll(fd_set *recv_set, fd_set *send_set)
1005 {
1006 struct connection *conn;
1007
1008 if (FD_ISSET(sockin, recv_set)) accept_connection();
1009
1010 LIST_FOREACH(conn, &connlist, entries)
1011 switch (conn->state)
1012 {
1013 case RECV_REQUEST:
1014 if (FD_ISSET(conn->socket, recv_set)) poll_recv_request(conn);
1015 break;
1016
1017 case SEND_HEADER_AND_REPLY:
1018 if (FD_ISSET(conn->socket, send_set)) poll_send_header_and_reply(conn);
1019 break;
1020
1021 case SEND_HEADER:
1022 if (FD_ISSET(conn->socket, send_set)) poll_send_header(conn);
1023 break;
1024
1025 case SEND_REPLY:
1026 if (FD_ISSET(conn->socket, send_set)) poll_send_reply(conn);
1027 break;
1028
1029 case DONE: /* fallthrough */
1030 default: errx(1, "invalid state");
1031 }
1032 }
1033
1034 /* vim:set ts=4 sw=4 et tw=78: */