8eaebcf57ae7c7d93c54b0796e6be2fb6b4a230f
[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 /* make relative (or fail) */
600 decoded_url = safe_url;
601 if (!str_starts_with(decoded_url, base_url))
602 {
603 default_reply(conn, 404, "Not Found",
604 "The page you requested could not be found.");
605 free(decoded_url);
606 return;
607 }
608 safe_url = decoded_url + strlen(base_url) - 1;
609
610 if (strcmp(safe_url, "/") == 0) {
611 struct str *buf = html_front_page();
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, "/hosts/")) {
616 /* FIXME here - make this saner */
617 struct str *buf = html_hosts(safe_url, conn->query);
618 if (buf == NULL) {
619 default_reply(conn, 404, "Not Found",
620 "The page you requested could not be found.");
621 return;
622 }
623 str_extract(buf, &(conn->reply_length), &(conn->reply));
624 conn->mime_type = mime_type_html;
625 }
626 else if (str_starts_with(safe_url, "/graphs.xml")) {
627 struct str *buf = xml_graphs();
628 str_extract(buf, &(conn->reply_length), &(conn->reply));
629 conn->mime_type = mime_type_xml;
630 /* hack around Opera caching the XML */
631 conn->header_extra = "Pragma: no-cache\r\n";
632 }
633 else if (strcmp(safe_url, "/style.css") == 0)
634 static_style_css(conn);
635 else if (strcmp(safe_url, "/graph.js") == 0)
636 static_graph_js(conn);
637 else {
638 default_reply(conn, 404, "Not Found",
639 "The page you requested could not be found.");
640 return;
641 }
642 free(decoded_url);
643
644 process_gzip(conn);
645 assert(conn->mime_type != NULL);
646 conn->header_length = xasprintf(&(conn->header),
647 "HTTP/1.1 200 OK\r\n"
648 "Date: %s\r\n"
649 "Server: %s\r\n"
650 "Content-Length: %d\r\n"
651 "Content-Type: %s\r\n"
652 "%s"
653 "%s"
654 "\r\n"
655 ,
656 rfc1123_date(date, now), server,
657 conn->reply_length, conn->mime_type, conn->encoding,
658 conn->header_extra);
659 conn->http_code = 200;
660 }
661
662
663
664 /* ---------------------------------------------------------------------------
665 * Process a request: build the header and reply, advance state.
666 */
667 static void process_request(struct connection *conn)
668 {
669 if (!parse_request(conn))
670 {
671 default_reply(conn, 400, "Bad Request",
672 "You sent a request that the server couldn't understand.");
673 }
674 else if (strcmp(conn->method, "GET") == 0)
675 {
676 process_get(conn);
677 }
678 else if (strcmp(conn->method, "HEAD") == 0)
679 {
680 process_get(conn);
681 conn->header_only = 1;
682 }
683 else
684 {
685 default_reply(conn, 501, "Not Implemented",
686 "The method you specified (%s) is not implemented.",
687 conn->method);
688 }
689
690 /* advance state */
691 if (conn->header_only)
692 conn->state = SEND_HEADER;
693 else
694 conn->state = SEND_HEADER_AND_REPLY;
695
696 /* request not needed anymore */
697 free(conn->request);
698 conn->request = NULL; /* important: don't free it again later */
699 }
700
701
702
703 /* ---------------------------------------------------------------------------
704 * Receiving request.
705 */
706 static void poll_recv_request(struct connection *conn)
707 {
708 #define BUFSIZE 65536
709 char buf[BUFSIZE];
710 ssize_t recvd;
711
712 recvd = recv(conn->socket, buf, BUFSIZE, 0);
713 dverbosef("poll_recv_request(%d) got %d bytes", conn->socket, (int)recvd);
714 if (recvd <= 0)
715 {
716 if (recvd == -1)
717 verbosef("recv(%d) error: %s", conn->socket, strerror(errno));
718 conn->state = DONE;
719 return;
720 }
721 conn->last_active = now;
722 #undef BUFSIZE
723
724 /* append to conn->request */
725 conn->request = xrealloc(conn->request, conn->request_length+recvd+1);
726 memcpy(conn->request+conn->request_length, buf, (size_t)recvd);
727 conn->request_length += recvd;
728 conn->request[conn->request_length] = 0;
729
730 /* process request if we have all of it */
731 if (conn->request_length > 4 &&
732 memcmp(conn->request+conn->request_length-4, "\r\n\r\n", 4) == 0)
733 process_request(conn);
734
735 /* die if it's too long */
736 if (conn->request_length > MAX_REQUEST_LENGTH)
737 {
738 default_reply(conn, 413, "Request Entity Too Large",
739 "Your request was dropped because it was too long.");
740 conn->state = SEND_HEADER;
741 }
742 }
743
744
745
746 /* ---------------------------------------------------------------------------
747 * Try to send header and [a part of the] reply in one packet.
748 */
749 static void poll_send_header_and_reply(struct connection *conn)
750 {
751 ssize_t sent;
752 struct iovec iov[2];
753
754 assert(!conn->header_only);
755 assert(conn->reply_length > 0);
756 assert(conn->header_sent == 0);
757
758 assert(conn->reply_sent == 0);
759
760 /* Fill out iovec */
761 iov[0].iov_base = conn->header;
762 iov[0].iov_len = conn->header_length;
763
764 iov[1].iov_base = conn->reply + conn->reply_sent;
765 iov[1].iov_len = conn->reply_length - conn->reply_sent;
766
767 sent = writev(conn->socket, iov, 2);
768 conn->last_active = now;
769
770 /* handle any errors (-1) or closure (0) in send() */
771 if (sent < 1) {
772 if (sent == -1)
773 verbosef("writev(%d) error: %s", conn->socket, strerror(errno));
774 conn->state = DONE;
775 return;
776 }
777
778 /* Figure out what we've sent. */
779 conn->total_sent += (unsigned int)sent;
780 if (sent < (ssize_t)conn->header_length) {
781 verbosef("partially sent header");
782 conn->header_sent = sent;
783 conn->state = SEND_HEADER;
784 return;
785 }
786 /* else */
787 conn->header_sent = conn->header_length;
788 sent -= conn->header_length;
789
790 if (conn->reply_sent + sent < conn->reply_length) {
791 verbosef("partially sent reply");
792 conn->reply_sent += sent;
793 conn->state = SEND_REPLY;
794 return;
795 }
796 /* else */
797 conn->reply_sent = conn->reply_length;
798 conn->state = DONE;
799 }
800
801 /* ---------------------------------------------------------------------------
802 * Sending header. Assumes conn->header is not NULL.
803 */
804 static void poll_send_header(struct connection *conn)
805 {
806 ssize_t sent;
807
808 sent = send(conn->socket, conn->header + conn->header_sent,
809 conn->header_length - conn->header_sent, 0);
810 conn->last_active = now;
811 dverbosef("poll_send_header(%d) sent %d bytes", conn->socket, (int)sent);
812
813 /* handle any errors (-1) or closure (0) in send() */
814 if (sent < 1)
815 {
816 if (sent == -1)
817 verbosef("send(%d) error: %s", conn->socket, strerror(errno));
818 conn->state = DONE;
819 return;
820 }
821 conn->header_sent += (unsigned int)sent;
822 conn->total_sent += (unsigned int)sent;
823
824 /* check if we're done sending */
825 if (conn->header_sent == conn->header_length)
826 {
827 if (conn->header_only)
828 conn->state = DONE;
829 else
830 conn->state = SEND_REPLY;
831 }
832 }
833
834
835
836 /* ---------------------------------------------------------------------------
837 * Sending reply.
838 */
839 static void poll_send_reply(struct connection *conn)
840 {
841 ssize_t sent;
842
843 sent = send(conn->socket,
844 conn->reply + conn->reply_sent,
845 conn->reply_length - conn->reply_sent, 0);
846 conn->last_active = now;
847 dverbosef("poll_send_reply(%d) sent %d: [%d-%d] of %d",
848 conn->socket, (int)sent,
849 (int)conn->reply_sent,
850 (int)(conn->reply_sent + sent - 1),
851 (int)conn->reply_length);
852
853 /* handle any errors (-1) or closure (0) in send() */
854 if (sent < 1)
855 {
856 if (sent == -1)
857 verbosef("send(%d) error: %s", conn->socket, strerror(errno));
858 else if (sent == 0)
859 verbosef("send(%d) closure", conn->socket);
860 conn->state = DONE;
861 return;
862 }
863 conn->reply_sent += (unsigned int)sent;
864 conn->total_sent += (unsigned int)sent;
865
866 /* check if we're done sending */
867 if (conn->reply_sent == conn->reply_length) conn->state = DONE;
868 }
869
870
871
872 /* --------------------------------------------------------------------------
873 * Initialize the base path.
874 */
875 void http_init_base(const char *url)
876 {
877 char *slashed_url, *safe_url;
878 size_t urllen;
879
880 /* make sure that the url has leading and trailing slashes */
881 urllen = strlen(url);
882 slashed_url = xmalloc(urllen+3);
883 memset(slashed_url, '/', urllen+2);
884 memcpy(slashed_url+1, url, urllen); /* don't copy NULL */
885 slashed_url[urllen+2] = '\0';
886
887 /* clean the url */
888 safe_url = make_safe_uri(slashed_url);
889 free(slashed_url);
890 if (safe_url == NULL)
891 {
892 verbosef("invalid base \"%s\", ignored", url, "/");
893 return;
894 }
895
896 base_url = safe_url;
897 }
898
899 /* --------------------------------------------------------------------------
900 * Initialize the sockin global. This is the socket that we accept
901 * connections from. Pass -1 as max_conn for system limit.
902 */
903 void http_init(const char *bindaddr, const unsigned short bindport,
904 const int max_conn)
905 {
906 struct sockaddr_storage addrin;
907 struct addrinfo hints, *ai, *aiptr;
908 char ipaddr[INET6_ADDRSTRLEN], portstr[12];
909 int sockopt, ret;
910
911 memset(&hints, 0, sizeof(hints));
912 hints.ai_family = AF_UNSPEC;
913 hints.ai_socktype = SOCK_STREAM;
914 hints.ai_flags = AI_PASSIVE;
915 #ifdef AI_ADDRCONFIG
916 hints.ai_flags |= AI_ADDRCONFIG;
917 #endif
918 snprintf(portstr, sizeof(portstr), "%u", bindport);
919
920 if ((ret = getaddrinfo(bindaddr, portstr, &hints, &aiptr)))
921 err(1, "getaddrinfo(): %s", gai_strerror(ret));
922
923 for (ai = aiptr; ai; ai = ai->ai_next) {
924 /* create incoming socket */
925 sockin = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
926 if (sockin == -1)
927 continue;
928
929 /* reuse address */
930 sockopt = 1;
931 if (setsockopt(sockin, SOL_SOCKET, SO_REUSEADDR,
932 &sockopt, sizeof(sockopt)) == -1) {
933 close(sockin);
934 continue;
935 }
936
937 /* Recover address and port strings. */
938 getnameinfo(ai->ai_addr, ai->ai_addrlen, ipaddr, sizeof(ipaddr),
939 NULL, 0, NI_NUMERICHOST);
940
941 /* bind socket */
942 memcpy(&addrin, ai->ai_addr, ai->ai_addrlen);
943 if (bind(sockin, (struct sockaddr *)&addrin, ai->ai_addrlen) == -1) {
944 close(sockin);
945 continue;
946 }
947
948 verbosef("listening on %s:%u", ipaddr, bindport);
949
950 /* listen on socket */
951 if (listen(sockin, max_conn) >= 0)
952 /* Successfully bound and now listening. */
953 break;
954
955 /* Next candidate. */
956 continue;
957 }
958
959 freeaddrinfo(aiptr);
960
961 if (ai == NULL)
962 err(1, "getaddrinfo() unable to locate address");
963
964 /* ignore SIGPIPE */
965 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
966 err(1, "can't ignore SIGPIPE");
967 }
968
969
970
971 /* ---------------------------------------------------------------------------
972 * Set recv/send fd_sets and calculate timeout length.
973 */
974 void
975 http_fd_set(fd_set *recv_set, fd_set *send_set, int *max_fd,
976 struct timeval *timeout, int *need_timeout)
977 {
978 struct connection *conn, *next;
979 int minidle = idletime + 1;
980
981 #define MAX_FD_SET(sock, fdset) do { \
982 FD_SET(sock, fdset); *max_fd = max(*max_fd, sock); } while(0)
983
984 MAX_FD_SET(sockin, recv_set);
985
986 LIST_FOREACH_SAFE(conn, &connlist, entries, next)
987 {
988 int idlefor = now - conn->last_active;
989
990 /* Time out dead connections. */
991 if (idlefor >= idletime)
992 {
993 char ipaddr[INET6_ADDRSTRLEN];
994 getnameinfo((struct sockaddr *) &conn->client, sizeof(conn->client),
995 ipaddr, sizeof(ipaddr), NULL, 0, NI_NUMERICHOST);
996 verbosef("http socket timeout from %s (fd %d)",
997 ipaddr, conn->socket);
998 conn->state = DONE;
999 }
1000
1001 /* Connections that need a timeout. */
1002 if (conn->state != DONE)
1003 minidle = min(minidle, (idletime - idlefor));
1004
1005 switch (conn->state)
1006 {
1007 case DONE:
1008 /* clean out stale connection */
1009 LIST_REMOVE(conn, entries);
1010 free_connection(conn);
1011 free(conn);
1012 break;
1013
1014 case RECV_REQUEST:
1015 MAX_FD_SET(conn->socket, recv_set);
1016 break;
1017
1018 case SEND_HEADER_AND_REPLY:
1019 case SEND_HEADER:
1020 case SEND_REPLY:
1021 MAX_FD_SET(conn->socket, send_set);
1022 break;
1023
1024 default: errx(1, "invalid state");
1025 }
1026 }
1027 #undef MAX_FD_SET
1028
1029 /* Only set timeout if cap hasn't already. */
1030 if ((*need_timeout == 0) && (minidle <= idletime)) {
1031 *need_timeout = 1;
1032 timeout->tv_sec = minidle;
1033 timeout->tv_usec = 0;
1034 }
1035 }
1036
1037
1038
1039 /* ---------------------------------------------------------------------------
1040 * poll connections that select() says need attention
1041 */
1042 void http_poll(fd_set *recv_set, fd_set *send_set)
1043 {
1044 struct connection *conn;
1045
1046 if (FD_ISSET(sockin, recv_set)) accept_connection();
1047
1048 LIST_FOREACH(conn, &connlist, entries)
1049 switch (conn->state)
1050 {
1051 case RECV_REQUEST:
1052 if (FD_ISSET(conn->socket, recv_set)) poll_recv_request(conn);
1053 break;
1054
1055 case SEND_HEADER_AND_REPLY:
1056 if (FD_ISSET(conn->socket, send_set)) poll_send_header_and_reply(conn);
1057 break;
1058
1059 case SEND_HEADER:
1060 if (FD_ISSET(conn->socket, send_set)) poll_send_header(conn);
1061 break;
1062
1063 case SEND_REPLY:
1064 if (FD_ISSET(conn->socket, send_set)) poll_send_reply(conn);
1065 break;
1066
1067 case DONE: /* fallthrough */
1068 default: errx(1, "invalid state");
1069 }
1070 }
1071
1072 /* vim:set ts=4 sw=4 et tw=78: */