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