0c9b141a4e092ad652f26e55d25e12665d9fef11
[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_identity[] = "identity";
44 static const char encoding_gzip[] = "gzip";
45
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
50
51 #ifndef min
52 #define min(a,b) (((a) < (b)) ? (a) : (b))
53 #endif
54
55 struct connection {
56 LIST_ENTRY(connection) entries;
57
58 int socket;
59 struct sockaddr_storage client;
60 time_t last_active;
61 enum {
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 */
67 } state;
68
69 /* char request[request_length+1] is null-terminated */
70 char *request;
71 size_t request_length;
72 int accept_gzip;
73
74 /* request fields */
75 char *method, *uri, *query; /* query can be NULL */
76
77 char *header;
78 const char *mime_type, *encoding, *header_extra;
79 size_t header_length, header_sent;
80 int header_dont_free, header_only, http_code;
81
82 char *reply;
83 int reply_dont_free;
84 size_t reply_length, reply_sent;
85
86 unsigned int total_sent; /* header + body = total, for logging */
87 };
88
89 static LIST_HEAD(conn_list_head, connection) connlist =
90 LIST_HEAD_INITIALIZER(conn_list_head);
91
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.
95 */
96 static char *urldecode(const char *url)
97 {
98 size_t i, len = strlen(url);
99 char *out = xmalloc(len+1);
100 int pos;
101
102 for (i=0, pos=0; i<len; i++)
103 {
104 if (url[i] == '%' && i+2 < len &&
105 isxdigit(url[i+1]) && isxdigit(url[i+2]))
106 {
107 /* decode %XX */
108 #define HEX_TO_DIGIT(hex) ( \
109 ((hex) >= 'A' && (hex) <= 'F') ? ((hex)-'A'+10): \
110 ((hex) >= 'a' && (hex) <= 'f') ? ((hex)-'a'+10): \
111 ((hex)-'0') )
112
113 out[pos++] = HEX_TO_DIGIT(url[i+1]) * 16 +
114 HEX_TO_DIGIT(url[i+2]);
115 i += 2;
116
117 #undef HEX_TO_DIGIT
118 }
119 else
120 {
121 /* straight copy */
122 out[pos++] = url[i];
123 }
124 }
125 out[pos] = 0;
126 #if 0
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 */
129 #endif
130 return (out);
131 }
132
133
134
135 /* ---------------------------------------------------------------------------
136 * Consolidate slashes in-place by shifting parts of the string over repeated
137 * slashes.
138 */
139 static void consolidate_slashes(char *s)
140 {
141 size_t left = 0, right = 0;
142 int saw_slash = 0;
143
144 assert(s != NULL);
145
146 while (s[right] != '\0')
147 {
148 if (saw_slash)
149 {
150 if (s[right] == '/') right++;
151 else
152 {
153 saw_slash = 0;
154 s[left++] = s[right++];
155 }
156 }
157 else
158 {
159 if (s[right] == '/') saw_slash++;
160 s[left++] = s[right++];
161 }
162 }
163 s[left] = '\0';
164 }
165
166
167
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.
171 */
172 static char *make_safe_uri(char *uri)
173 {
174 char **elem, *out;
175 unsigned int slashes = 0, elements = 0;
176 size_t urilen, i, j, pos;
177
178 assert(uri != NULL);
179 if (uri[0] != '/')
180 return (NULL);
181 consolidate_slashes(uri);
182 urilen = strlen(uri);
183
184 /* count the slashes */
185 for (i=0, slashes=0; i<urilen; i++)
186 if (uri[i] == '/') slashes++;
187
188 /* make an array for the URI elements */
189 elem = xmalloc(sizeof(*elem) * slashes);
190 for (i=0; i<slashes; i++)
191 elem[i] = (NULL);
192
193 /* split by slashes and build elem[] array */
194 for (i=1; i<urilen;)
195 {
196 /* look for the next slash */
197 for (j=i; j<urilen && uri[j] != '/'; j++)
198 ;
199
200 /* process uri[i,j) */
201 if ((j == i+1) && (uri[i] == '.'))
202 /* "." */;
203 else if ((j == i+2) && (uri[i] == '.') && (uri[i+1] == '.'))
204 {
205 /* ".." */
206 if (elements == 0)
207 {
208 /*
209 * Unsafe string so free elem[]. All its elements are free
210 * at this point.
211 */
212 free(elem);
213 return (NULL);
214 }
215 else
216 {
217 elements--;
218 free(elem[elements]);
219 }
220 }
221 else elem[elements++] = split_string(uri, i, j);
222
223 i = j + 1; /* uri[j] is a slash - move along one */
224 }
225
226 /* reassemble */
227 out = xmalloc(urilen+1); /* it won't expand */
228 pos = 0;
229 for (i=0; i<elements; i++)
230 {
231 size_t delta = strlen(elem[i]);
232
233 assert(pos <= urilen);
234 out[pos++] = '/';
235
236 assert(pos+delta <= urilen);
237 memcpy(out+pos, elem[i], delta);
238 free(elem[i]);
239 pos += delta;
240 }
241 free(elem);
242
243 if ((elements == 0) || (uri[urilen-1] == '/')) out[pos++] = '/';
244 assert(pos <= urilen);
245 out[pos] = '\0';
246
247 #if 0
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);
251 #endif
252 return (out);
253 }
254
255 /* ---------------------------------------------------------------------------
256 * Allocate and initialize an empty connection.
257 */
258 static struct connection *new_connection(void)
259 {
260 struct connection *conn = xmalloc(sizeof(*conn));
261
262 conn->socket = -1;
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;
268 conn->method = NULL;
269 conn->uri = NULL;
270 conn->query = NULL;
271 conn->header = NULL;
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;
279 conn->http_code = 0;
280 conn->reply = NULL;
281 conn->reply_dont_free = 0;
282 conn->reply_length = 0;
283 conn->reply_sent = 0;
284 conn->total_sent = 0;
285
286 /* Make it harmless so it gets garbage-collected if it should, for some
287 * reason, fail to be correctly filled out.
288 */
289 conn->state = DONE;
290
291 return (conn);
292 }
293
294
295
296 /* ---------------------------------------------------------------------------
297 * Accept a connection from sockin and add it to the connection queue.
298 */
299 static void accept_connection(void)
300 {
301 struct sockaddr_storage addrin;
302 socklen_t sin_size;
303 struct connection *conn;
304 char ipaddr[INET6_ADDRSTRLEN], portstr[12];
305 int sock;
306
307 sin_size = (socklen_t)sizeof(addrin);
308 sock = accept(sockin, &addrin, &sin_size);
309 if (sock == -1)
310 {
311 if (errno == ECONNABORTED || errno == EINTR)
312 {
313 verbosef("accept() failed: %s", strerror(errno));
314 return;
315 }
316 /* else */ err(1, "accept()");
317 }
318
319 fd_set_nonblock(sock);
320
321 /* allocate and initialise struct connection */
322 conn = new_connection();
323 conn->socket = sock;
324 conn->state = RECV_REQUEST;
325 memcpy(&conn->client, &addrin, sizeof(conn->client));
326 LIST_INSERT_HEAD(&connlist, conn, entries);
327
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);
332 }
333
334
335
336 /* ---------------------------------------------------------------------------
337 * Log a connection, then cleanly deallocate its internals.
338 */
339 static void free_connection(struct connection *conn)
340 {
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);
349 }
350
351
352
353 /* ---------------------------------------------------------------------------
354 * Format [when] as an RFC1123 date, stored in the specified buffer. The same
355 * buffer is returned for convenience.
356 */
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)
359 {
360 time_t tmp = 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);
364 return (dest);
365 }
366
367 static void generate_header(struct connection *conn,
368 const int code, const char *text)
369 {
370 char date[DATE_LEN];
371
372 assert(conn->header == NULL);
373 assert(conn->mime_type != NULL);
374 if (conn->encoding == NULL)
375 conn->encoding = encoding_identity;
376
377 verbosef("http: %d %s (%s: %d bytes)", code, text,
378 conn->encoding, conn->reply_length);
379 conn->header_length = xasprintf(&(conn->header),
380 "HTTP/1.1 %d %s\r\n"
381 "Date: %s\r\n"
382 "Server: %s\r\n"
383 "Vary: Accept-Encoding\r\n"
384 "Content-Type: %s\r\n"
385 "Content-Length: %d\r\n"
386 "Content-Encoding: %s\r\n"
387 "%s"
388 "\r\n"
389 ,
390 code, text,
391 rfc1123_date(date, now), server,
392 conn->mime_type, conn->reply_length, conn->encoding,
393 conn->header_extra);
394 conn->http_code = code;
395 }
396
397
398
399 /* ---------------------------------------------------------------------------
400 * A default reply for any (erroneous) occasion.
401 */
402 static void default_reply(struct connection *conn,
403 const int errcode, const char *errname, const char *format, ...)
404 {
405 char *reason, date[DATE_LEN];
406 va_list va;
407
408 va_start(va, format);
409 xvasprintf(&reason, format, va);
410 va_end(va);
411
412 conn->reply_length = xasprintf(&(conn->reply),
413 "<html><head><title>%d %s</title></head><body>\n"
414 "<h1>%s</h1>\n" /* errname */
415 "%s\n" /* reason */
416 "<hr>\n"
417 "Generated by %s"
418 "</body></html>\n",
419 errcode, errname, errname, reason, server);
420 free(reason);
421
422 /* forget any dangling metadata */
423 conn->mime_type = mime_type_html;
424 conn->encoding = encoding_identity;
425
426 generate_header(conn, errcode, errname);
427 }
428
429
430
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
434 * matched.
435 *
436 * You need to remember to deallocate the result.
437 * example: parse_field(conn, "Referer: ");
438 */
439 static char *parse_field(const struct connection *conn, const char *field)
440 {
441 size_t bound1, bound2;
442 char *pos;
443
444 /* find start */
445 pos = strstr(conn->request, field);
446 if (pos == NULL)
447 return (NULL);
448 bound1 = pos - conn->request + strlen(field);
449
450 /* find end */
451 for (bound2 = bound1;
452 conn->request[bound2] != '\r' &&
453 bound2 < conn->request_length; bound2++)
454 ;
455
456 /* copy to buffer */
457 return (split_string(conn->request, bound1, bound2));
458 }
459
460
461
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.
467 */
468 static int parse_request(struct connection *conn)
469 {
470 size_t bound1, bound2, mid;
471 char *accept_enc;
472
473 /* parse method */
474 for (bound1 = 0; bound1 < conn->request_length &&
475 conn->request[bound1] != ' '; bound1++)
476 ;
477
478 conn->method = split_string(conn->request, 0, bound1);
479 strntoupper(conn->method, bound1);
480
481 /* parse uri */
482 for (; bound1 < conn->request_length &&
483 conn->request[bound1] == ' '; bound1++)
484 ;
485
486 if (bound1 == conn->request_length)
487 return (0); /* fail */
488
489 for (bound2=bound1+1; bound2 < conn->request_length &&
490 conn->request[bound2] != ' ' &&
491 conn->request[bound2] != '\r'; bound2++)
492 ;
493
494 /* find query string */
495 for (mid=bound1; mid<bound2 && conn->request[mid] != '?'; mid++)
496 ;
497
498 if (conn->request[mid] == '?') {
499 conn->query = split_string(conn->request, mid+1, bound2);
500 bound2 = mid;
501 }
502
503 conn->uri = split_string(conn->request, bound1, bound2);
504
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;
510 free(accept_enc);
511 }
512 return (1);
513 }
514
515 /* FIXME: maybe we need a smarter way of doing static pages: */
516
517 /* ---------------------------------------------------------------------------
518 * Web interface: static stylesheet.
519 */
520 static void
521 static_style_css(struct connection *conn)
522 {
523 #include "stylecss.h"
524
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;
529 }
530
531 /* ---------------------------------------------------------------------------
532 * Web interface: static JavaScript.
533 */
534 static void
535 static_graph_js(struct connection *conn)
536 {
537 #include "graphjs.h"
538
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;
543 }
544
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.
548 */
549 static void
550 process_gzip(struct connection *conn)
551 {
552 char *buf;
553 size_t len;
554 z_stream zs;
555
556 if (!conn->accept_gzip)
557 return;
558
559 buf = xmalloc(conn->reply_length);
560 len = conn->reply_length;
561
562 zs.zalloc = Z_NULL;
563 zs.zfree = Z_NULL;
564 zs.opaque = Z_NULL;
565
566 if (deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED,
567 15+16, /* 15 = biggest window, 16 = add gzip header+trailer */
568 8 /* default */,
569 Z_DEFAULT_STRATEGY) != Z_OK)
570 return;
571
572 zs.avail_in = conn->reply_length;
573 zs.next_in = (unsigned char *)conn->reply;
574
575 zs.avail_out = conn->reply_length;
576 zs.next_out = (unsigned char *)buf;
577
578 if (deflate(&zs, Z_FINISH) != Z_STREAM_END) {
579 deflateEnd(&zs);
580 free(buf);
581 verbosef("failed to compress %u bytes", (unsigned int)len);
582 return;
583 }
584
585 if (conn->reply_dont_free)
586 conn->reply_dont_free = 0;
587 else
588 free(conn->reply);
589
590 conn->reply = buf;
591 conn->reply_length -= zs.avail_out;
592 conn->encoding = encoding_gzip;
593 deflateEnd(&zs);
594 }
595
596 /* ---------------------------------------------------------------------------
597 * Process a GET/HEAD request
598 */
599 static void process_get(struct connection *conn)
600 {
601 char *decoded_url, *safe_url;
602 char date[DATE_LEN];
603
604 verbosef("http: %s \"%s\" %s", conn->method, conn->uri,
605 (conn->query == NULL)?"":conn->query);
606
607 /* work out path of file being requested */
608 decoded_url = urldecode(conn->uri);
609
610 /* make sure it's safe */
611 safe_url = make_safe_uri(decoded_url);
612 free(decoded_url);
613 if (safe_url == NULL)
614 {
615 default_reply(conn, 400, "Bad Request",
616 "You requested an invalid URI: %s", conn->uri);
617 return;
618 }
619
620 /* make relative (or fail) */
621 decoded_url = safe_url;
622 if (!str_starts_with(decoded_url, base_url))
623 {
624 default_reply(conn, 404, "Not Found",
625 "The page you requested could not be found.");
626 free(decoded_url);
627 return;
628 }
629 safe_url = decoded_url + strlen(base_url) - 1;
630
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;
635 }
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);
639 if (buf == NULL) {
640 default_reply(conn, 404, "Not Found",
641 "The page you requested could not be found.");
642 free(decoded_url);
643 return;
644 }
645 str_extract(buf, &(conn->reply_length), &(conn->reply));
646 conn->mime_type = mime_type_html;
647 }
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";
654 }
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);
659 else {
660 default_reply(conn, 404, "Not Found",
661 "The page you requested could not be found.");
662 free(decoded_url);
663 return;
664 }
665 free(decoded_url);
666
667 process_gzip(conn);
668 assert(conn->mime_type != NULL);
669 generate_header(conn, 200, "OK");
670 }
671
672
673
674 /* ---------------------------------------------------------------------------
675 * Process a request: build the header and reply, advance state.
676 */
677 static void process_request(struct connection *conn)
678 {
679 if (!parse_request(conn))
680 {
681 default_reply(conn, 400, "Bad Request",
682 "You sent a request that the server couldn't understand.");
683 }
684 else if (strcmp(conn->method, "GET") == 0)
685 {
686 process_get(conn);
687 }
688 else if (strcmp(conn->method, "HEAD") == 0)
689 {
690 process_get(conn);
691 conn->header_only = 1;
692 }
693 else
694 {
695 default_reply(conn, 501, "Not Implemented",
696 "The method you specified (%s) is not implemented.",
697 conn->method);
698 }
699
700 /* advance state */
701 if (conn->header_only)
702 conn->state = SEND_HEADER;
703 else
704 conn->state = SEND_HEADER_AND_REPLY;
705
706 /* request not needed anymore */
707 free(conn->request);
708 conn->request = NULL; /* important: don't free it again later */
709 }
710
711
712
713 /* ---------------------------------------------------------------------------
714 * Receiving request.
715 */
716 static void poll_recv_request(struct connection *conn)
717 {
718 #define BUFSIZE 65536
719 char buf[BUFSIZE];
720 ssize_t recvd;
721
722 recvd = recv(conn->socket, buf, BUFSIZE, 0);
723 dverbosef("poll_recv_request(%d) got %d bytes", conn->socket, (int)recvd);
724 if (recvd <= 0)
725 {
726 if (recvd == -1)
727 verbosef("recv(%d) error: %s", conn->socket, strerror(errno));
728 conn->state = DONE;
729 return;
730 }
731 conn->last_active = now;
732 #undef BUFSIZE
733
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;
739
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);
744
745 /* die if it's too long */
746 if (conn->request_length > MAX_REQUEST_LENGTH)
747 {
748 default_reply(conn, 413, "Request Entity Too Large",
749 "Your request was dropped because it was too long.");
750 conn->state = SEND_HEADER;
751 }
752 }
753
754
755
756 /* ---------------------------------------------------------------------------
757 * Try to send header and [a part of the] reply in one packet.
758 */
759 static void poll_send_header_and_reply(struct connection *conn)
760 {
761 ssize_t sent;
762 struct iovec iov[2];
763
764 assert(!conn->header_only);
765 assert(conn->reply_length > 0);
766 assert(conn->header_sent == 0);
767
768 assert(conn->reply_sent == 0);
769
770 /* Fill out iovec */
771 iov[0].iov_base = conn->header;
772 iov[0].iov_len = conn->header_length;
773
774 iov[1].iov_base = conn->reply + conn->reply_sent;
775 iov[1].iov_len = conn->reply_length - conn->reply_sent;
776
777 sent = writev(conn->socket, iov, 2);
778 conn->last_active = now;
779
780 /* handle any errors (-1) or closure (0) in send() */
781 if (sent < 1) {
782 if (sent == -1)
783 verbosef("writev(%d) error: %s", conn->socket, strerror(errno));
784 conn->state = DONE;
785 return;
786 }
787
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;
794 return;
795 }
796 /* else */
797 conn->header_sent = conn->header_length;
798 sent -= conn->header_length;
799
800 if (conn->reply_sent + sent < conn->reply_length) {
801 verbosef("partially sent reply");
802 conn->reply_sent += sent;
803 conn->state = SEND_REPLY;
804 return;
805 }
806 /* else */
807 conn->reply_sent = conn->reply_length;
808 conn->state = DONE;
809 }
810
811 /* ---------------------------------------------------------------------------
812 * Sending header. Assumes conn->header is not NULL.
813 */
814 static void poll_send_header(struct connection *conn)
815 {
816 ssize_t sent;
817
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);
822
823 /* handle any errors (-1) or closure (0) in send() */
824 if (sent < 1)
825 {
826 if (sent == -1)
827 verbosef("send(%d) error: %s", conn->socket, strerror(errno));
828 conn->state = DONE;
829 return;
830 }
831 conn->header_sent += (unsigned int)sent;
832 conn->total_sent += (unsigned int)sent;
833
834 /* check if we're done sending */
835 if (conn->header_sent == conn->header_length)
836 {
837 if (conn->header_only)
838 conn->state = DONE;
839 else
840 conn->state = SEND_REPLY;
841 }
842 }
843
844
845
846 /* ---------------------------------------------------------------------------
847 * Sending reply.
848 */
849 static void poll_send_reply(struct connection *conn)
850 {
851 ssize_t sent;
852
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);
862
863 /* handle any errors (-1) or closure (0) in send() */
864 if (sent < 1)
865 {
866 if (sent == -1)
867 verbosef("send(%d) error: %s", conn->socket, strerror(errno));
868 else if (sent == 0)
869 verbosef("send(%d) closure", conn->socket);
870 conn->state = DONE;
871 return;
872 }
873 conn->reply_sent += (unsigned int)sent;
874 conn->total_sent += (unsigned int)sent;
875
876 /* check if we're done sending */
877 if (conn->reply_sent == conn->reply_length) conn->state = DONE;
878 }
879
880
881
882 /* --------------------------------------------------------------------------
883 * Initialize the base path.
884 */
885 void http_init_base(const char *url)
886 {
887 char *slashed_url, *safe_url;
888 size_t urllen;
889
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';
896
897 /* clean the url */
898 safe_url = make_safe_uri(slashed_url);
899 free(slashed_url);
900 if (safe_url == NULL)
901 {
902 verbosef("invalid base \"%s\", ignored", url, "/");
903 return;
904 }
905
906 base_url = safe_url;
907 }
908
909 /* --------------------------------------------------------------------------
910 * Initialize the sockin global. This is the socket that we accept
911 * connections from. Pass -1 as max_conn for system limit.
912 */
913 void http_init(const char *bindaddr, const unsigned short bindport,
914 const int max_conn)
915 {
916 struct sockaddr_storage addrin;
917 struct addrinfo hints, *ai, *aiptr;
918 char ipaddr[INET6_ADDRSTRLEN], portstr[12];
919 int sockopt, ret;
920
921 memset(&hints, 0, sizeof(hints));
922 hints.ai_family = AF_UNSPEC;
923 hints.ai_socktype = SOCK_STREAM;
924 hints.ai_flags = AI_PASSIVE;
925 #ifdef AI_ADDRCONFIG
926 hints.ai_flags |= AI_ADDRCONFIG;
927 #endif
928 snprintf(portstr, sizeof(portstr), "%u", bindport);
929
930 if ((ret = getaddrinfo(bindaddr, portstr, &hints, &aiptr)))
931 err(1, "getaddrinfo(): %s", gai_strerror(ret));
932
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);
936 if (sockin == -1)
937 continue;
938
939 /* reuse address */
940 sockopt = 1;
941 if (setsockopt(sockin, SOL_SOCKET, SO_REUSEADDR,
942 &sockopt, sizeof(sockopt)) == -1) {
943 close(sockin);
944 continue;
945 }
946
947 /* Recover address and port strings. */
948 getnameinfo(ai->ai_addr, ai->ai_addrlen, ipaddr, sizeof(ipaddr),
949 NULL, 0, NI_NUMERICHOST);
950
951 /* bind socket */
952 memcpy(&addrin, ai->ai_addr, ai->ai_addrlen);
953 if (bind(sockin, (struct sockaddr *)&addrin, ai->ai_addrlen) == -1) {
954 close(sockin);
955 continue;
956 }
957
958 verbosef("listening on %s:%u", ipaddr, bindport);
959
960 /* listen on socket */
961 if (listen(sockin, max_conn) >= 0)
962 /* Successfully bound and now listening. */
963 break;
964
965 /* Next candidate. */
966 continue;
967 }
968
969 freeaddrinfo(aiptr);
970
971 if (ai == NULL)
972 err(1, "getaddrinfo() unable to locate address");
973
974 /* ignore SIGPIPE */
975 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
976 err(1, "can't ignore SIGPIPE");
977 }
978
979
980
981 /* ---------------------------------------------------------------------------
982 * Set recv/send fd_sets and calculate timeout length.
983 */
984 void
985 http_fd_set(fd_set *recv_set, fd_set *send_set, int *max_fd,
986 struct timeval *timeout, int *need_timeout)
987 {
988 struct connection *conn, *next;
989 int minidle = idletime + 1;
990
991 #define MAX_FD_SET(sock, fdset) do { \
992 FD_SET(sock, fdset); *max_fd = max(*max_fd, sock); } while(0)
993
994 MAX_FD_SET(sockin, recv_set);
995
996 LIST_FOREACH_SAFE(conn, &connlist, entries, next)
997 {
998 int idlefor = now - conn->last_active;
999
1000 /* Time out dead connections. */
1001 if (idlefor >= idletime)
1002 {
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);
1008 conn->state = DONE;
1009 }
1010
1011 /* Connections that need a timeout. */
1012 if (conn->state != DONE)
1013 minidle = min(minidle, (idletime - idlefor));
1014
1015 switch (conn->state)
1016 {
1017 case DONE:
1018 /* clean out stale connection */
1019 LIST_REMOVE(conn, entries);
1020 free_connection(conn);
1021 free(conn);
1022 break;
1023
1024 case RECV_REQUEST:
1025 MAX_FD_SET(conn->socket, recv_set);
1026 break;
1027
1028 case SEND_HEADER_AND_REPLY:
1029 case SEND_HEADER:
1030 case SEND_REPLY:
1031 MAX_FD_SET(conn->socket, send_set);
1032 break;
1033
1034 default: errx(1, "invalid state");
1035 }
1036 }
1037 #undef MAX_FD_SET
1038
1039 /* Only set timeout if cap hasn't already. */
1040 if ((*need_timeout == 0) && (minidle <= idletime)) {
1041 *need_timeout = 1;
1042 timeout->tv_sec = minidle;
1043 timeout->tv_usec = 0;
1044 }
1045 }
1046
1047
1048
1049 /* ---------------------------------------------------------------------------
1050 * poll connections that select() says need attention
1051 */
1052 void http_poll(fd_set *recv_set, fd_set *send_set)
1053 {
1054 struct connection *conn;
1055
1056 if (FD_ISSET(sockin, recv_set)) accept_connection();
1057
1058 LIST_FOREACH(conn, &connlist, entries)
1059 switch (conn->state)
1060 {
1061 case RECV_REQUEST:
1062 if (FD_ISSET(conn->socket, recv_set)) poll_recv_request(conn);
1063 break;
1064
1065 case SEND_HEADER_AND_REPLY:
1066 if (FD_ISSET(conn->socket, send_set)) poll_send_header_and_reply(conn);
1067 break;
1068
1069 case SEND_HEADER:
1070 if (FD_ISSET(conn->socket, send_set)) poll_send_header(conn);
1071 break;
1072
1073 case SEND_REPLY:
1074 if (FD_ISSET(conn->socket, send_set)) poll_send_reply(conn);
1075 break;
1076
1077 case DONE: /* fallthrough */
1078 default: errx(1, "invalid state");
1079 }
1080 }
1081
1082 /* vim:set ts=4 sw=4 et tw=78: */