1 /* vi: set sw=4 ts=4: */
3 * httpd implementation for busybox
5 * Copyright (C) 2002,2003 Glenn Engel <glenne@engel.org>
6 * Copyright (C) 2003-2006 Vladimir Oleynik <dzo@simtreas.ru>
8 * simplify patch stolen from libbb without using strdup
10 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
12 *****************************************************************************
16 * httpd -p 8080 -h $HOME/public_html
17 * or for daemon start from rc script with uid=0:
19 * This is equivalent if www user have uid=80 to
20 * httpd -p 80 -u 80 -h /www -c /etc/httpd.conf -r "Web Server Authentication"
23 * When a url starts by "/cgi-bin/" it is assumed to be a cgi script. The
24 * server changes directory to the location of the script and executes it
25 * after setting QUERY_STRING and other environment variables.
28 * "CGI Environment Variables": http://hoohoo.ncsa.uiuc.edu/cgi/env.html
30 * The server can also be invoked as a url arg decoder and html text encoder
32 * foo=`httpd -d $foo` # decode "Hello%20World" as "Hello World"
33 * bar=`httpd -e "<Hello World>"` # encode as "<Hello World>"
34 * Note that url encoding for arguments is not the same as html encoding for
35 * presentation. -d decodes a url-encoded argument while -e encodes in html
38 * httpd.conf has the following format:
40 * A:172.20. # Allow address from 172.20.0.0/16
41 * A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
42 * A:10.0.0.0/255.255.255.128 # Allow any address that previous set
43 * A:127.0.0.1 # Allow local loopback connections
44 * D:* # Deny from other IP connections
45 * E404:/path/e404.html # /path/e404.html is the 404 (not found) error page
46 * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
47 * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
48 * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
49 * .au:audio/basic # additional mime type for audio.au files
50 * *.php:/path/php # running cgi.php scripts through an interpreter
52 * A/D may be as a/d or allow/deny - first char case insensitive
53 * Deny IP rules take precedence over allow rules.
56 * The Deny/Allow IP logic:
58 * - Default is to allow all. No addresses are denied unless
59 * denied with a D: rule.
60 * - Order of Deny/Allow rules is significant
61 * - Deny rules take precedence over allow rules.
62 * - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
64 * - Specification of Allow all (A:*) is a no-op
67 * 1. Allow only specified addresses
68 * A:172.20 # Allow any address that begins with 172.20.
69 * A:10.10. # Allow any address that begins with 10.10.
70 * A:127.0.0.1 # Allow local loopback connections
71 * D:* # Deny from other IP connections
73 * 2. Only deny specified addresses
74 * D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
75 * D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
76 * A:* # (optional line added for clarity)
78 * If a sub directory contains a config file it is parsed and merged with
79 * any existing settings as if it was appended to the original configuration.
81 * subdir paths are relative to the containing subdir and thus cannot
82 * affect the parent rules.
84 * Note that since the sub dir is parsed in the forked thread servicing the
85 * subdir http request, any merge is discarded when the process exits. As a
86 * result, the subdir settings only have a lifetime of a single request.
88 * Custom error pages can contain an absolute path or be relative to
89 * 'home_httpd'. Error pages are to be static files (no CGI or script). Error
90 * page can only be defined in the root configuration file and are not taken
91 * into account in local (directories) config files.
93 * If -c is not set, an attempt will be made to open the default
94 * root configuration file. If -c is set and the file is not found, the
95 * server exits with an error.
100 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
101 #include <sys/sendfile.h>
107 /* amount of buffering in a pipe */
109 # define PIPE_BUF 4096
112 #define IOBUF_SIZE 8192 /* IO buffer */
114 #define HEADER_READ_TIMEOUT 60
116 static const char default_path_httpd_conf[] ALIGN1 = "/etc";
117 static const char httpd_conf[] ALIGN1 = "httpd.conf";
118 static const char HTTP_200[] ALIGN1 = "HTTP/1.0 200 OK\r\n";
120 typedef struct has_next_ptr {
121 struct has_next_ptr *next;
124 /* Must have "next" as a first member */
125 typedef struct Htaccess {
126 struct Htaccess *next;
128 char before_colon[1]; /* really bigger, must be last */
131 /* Must have "next" as a first member */
132 typedef struct Htaccess_IP {
133 struct Htaccess_IP *next;
141 HTTP_MOVED_TEMPORARILY = 302,
142 HTTP_BAD_REQUEST = 400, /* malformed syntax */
143 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
144 HTTP_NOT_FOUND = 404,
145 HTTP_FORBIDDEN = 403,
146 HTTP_REQUEST_TIMEOUT = 408,
147 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
148 HTTP_INTERNAL_SERVER_ERROR = 500,
150 #if 0 /* future use */
151 HTTP_SWITCHING_PROTOCOLS = 101,
154 HTTP_NON_AUTHORITATIVE_INFO = 203,
155 HTTP_NO_CONTENT = 204,
156 HTTP_MULTIPLE_CHOICES = 300,
157 HTTP_MOVED_PERMANENTLY = 301,
158 HTTP_NOT_MODIFIED = 304,
159 HTTP_PAYMENT_REQUIRED = 402,
160 HTTP_BAD_GATEWAY = 502,
161 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
162 HTTP_RESPONSE_SETSIZE = 0xffffffff
166 static const uint16_t http_response_type[] ALIGN2 = {
168 HTTP_MOVED_TEMPORARILY,
169 HTTP_REQUEST_TIMEOUT,
170 HTTP_NOT_IMPLEMENTED,
171 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
177 HTTP_INTERNAL_SERVER_ERROR,
178 #if 0 /* not implemented */
182 HTTP_MULTIPLE_CHOICES,
183 HTTP_MOVED_PERMANENTLY,
186 HTTP_SERVICE_UNAVAILABLE,
190 static const struct {
193 } http_response[ARRAY_SIZE(http_response_type)] = {
195 { "Found", "Directories must end with a slash" }, /* ?? */
196 { "Request Timeout", "No request appeared within 60 seconds" },
197 { "Not Implemented", "The requested method is not recognized" },
198 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
199 { "Unauthorized", "" },
201 { "Not Found", "The requested URL was not found" },
202 { "Bad Request", "Unsupported method" },
204 { "Internal Server Error", "Internal Server Error" },
205 #if 0 /* not implemented */
209 { "Multiple Choices" },
210 { "Moved Permanently" },
212 { "Bad Gateway", "" },
213 { "Service Unavailable", "" },
218 int verbose; /* must be int (used by getopt32) */
219 smallint flg_deny_all;
221 unsigned rmt_ip; /* used for IP-based allow/deny rules */
223 off_t ContentLength; /* -1 - unknown */
224 char *rmt_ip_str; /* for $REMOTE_ADDR and $REMOTE_PORT */
225 const char *bind_addr_or_port;
228 const char *configFile;
229 const char *home_httpd;
231 const char *found_mime_type;
232 const char *found_moved_temporarily;
233 Htaccess_IP *ip_a_d; /* config allow/deny lines */
235 USE_FEATURE_HTTPD_BASIC_AUTH(const char *g_realm;)
236 USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
237 USE_FEATURE_HTTPD_CGI(char *referer;)
238 USE_FEATURE_HTTPD_CGI(char *user_agent;)
240 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
241 Htaccess *g_auth; /* config user:password lines */
243 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
244 Htaccess *mime_a; /* config mime types */
246 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
247 Htaccess *script_i; /* config script interpreters */
249 char *iobuf; /* [IOBUF_SIZE] */
250 #define hdr_buf bb_common_bufsiz1
253 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
254 const char *http_error_page[ARRAY_SIZE(http_response_type)];
257 #define G (*ptr_to_globals)
258 #define verbose (G.verbose )
259 #define flg_deny_all (G.flg_deny_all )
260 #define rmt_ip (G.rmt_ip )
261 #define bind_addr_or_port (G.bind_addr_or_port)
262 #define g_query (G.g_query )
263 #define configFile (G.configFile )
264 #define home_httpd (G.home_httpd )
265 #define found_mime_type (G.found_mime_type )
266 #define found_moved_temporarily (G.found_moved_temporarily)
267 #define ContentLength (G.ContentLength )
268 #define last_mod (G.last_mod )
269 #define ip_a_d (G.ip_a_d )
270 #define g_realm (G.g_realm )
271 #define remoteuser (G.remoteuser )
272 #define referer (G.referer )
273 #define user_agent (G.user_agent )
274 #define rmt_ip_str (G.rmt_ip_str )
275 #define g_auth (G.g_auth )
276 #define mime_a (G.mime_a )
277 #define script_i (G.script_i )
278 #define iobuf (G.iobuf )
279 #define hdr_ptr (G.hdr_ptr )
280 #define hdr_cnt (G.hdr_cnt )
281 #define http_error_page (G.http_error_page )
282 #define INIT_G() do { \
283 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
284 USE_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
285 bind_addr_or_port = "80"; \
286 ContentLength = -1; \
290 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
293 static void send_file_and_exit(const char *url, int headers) ATTRIBUTE_NORETURN;
295 static void free_llist(has_next_ptr **pptr)
297 has_next_ptr *cur = *pptr;
299 has_next_ptr *t = cur;
306 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
307 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
308 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
309 static ALWAYS_INLINE void free_Htaccess_list(Htaccess **pptr)
311 free_llist((has_next_ptr**)pptr);
315 static ALWAYS_INLINE void free_Htaccess_IP_list(Htaccess_IP **pptr)
317 free_llist((has_next_ptr**)pptr);
320 /* Returns presumed mask width in bits or < 0 on error.
321 * Updates strp, stores IP at provided pointer */
322 static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
324 const char *p = *strp;
332 for (j = 0; j < 4; j++) {
335 if ((*p < '0' || *p > '9') && *p != '/' && *p)
338 while (*p >= '0' && *p <= '9') {
349 ip = (ip << 8) | octet;
363 /* Returns 0 on success. Stores IP and mask at provided pointers */
364 static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
370 i = scan_ip(&str, ipp, '/');
375 /* there is /xxx after dotted-IP address */
376 i = bb_strtou(str, &p, 10);
378 /* 'xxx' itself is dotted-IP mask, parse it */
379 /* (return 0 (success) only if it has N.N.N.N form) */
380 return scan_ip(&str, maskp, '\0') - 32;
389 if (sizeof(unsigned) == 4 && i == 32) {
390 /* mask >>= 32 below may not work */
396 /* i == 0 -> *maskp = 0x00000000
397 * i == 1 -> *maskp = 0x80000000
398 * i == 4 -> *maskp = 0xf0000000
399 * i == 31 -> *maskp = 0xfffffffe
400 * i == 32 -> *maskp = 0xffffffff */
401 *maskp = (uint32_t)(~mask);
406 * Parse configuration file into in-memory linked list.
408 * The first non-white character is examined to determine if the config line
409 * is one of the following:
410 * .ext:mime/type # new mime type not compiled into httpd
411 * [adAD]:from # ip address allow/deny, * for wildcard
412 * /path:user:pass # username/password
413 * Ennn:error.html # error page for status nnn
415 * Any previous IP rules are discarded.
416 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
417 * are also discarded. That is, previous settings are retained if flag is
419 * Error pages are only parsed on the main config file.
421 * path Path where to look for httpd.conf (without filename).
422 * flag Type of the parse request.
425 #define FIRST_PARSE 0
426 #define SUBDIR_PARSE 1
427 #define SIGNALED_PARSE 2
428 #define FIND_FROM_HTTPD_ROOT 3
429 static void parse_conf(const char *path, int flag)
432 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
435 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
436 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
437 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
440 const char *cf = configFile;
446 /* discard old rules */
447 free_Htaccess_IP_list(&ip_a_d);
449 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
450 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
451 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
452 /* retain previous auth and mime config only for subdir parse */
453 if (flag != SUBDIR_PARSE) {
454 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
455 free_Htaccess_list(&g_auth);
457 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
458 free_Htaccess_list(&mime_a);
460 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
461 free_Htaccess_list(&script_i);
466 if (flag == SUBDIR_PARSE || cf == NULL) {
467 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
468 sprintf((char *)cf, "%s/%s", path, httpd_conf);
471 while ((f = fopen(cf, "r")) == NULL) {
472 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
473 /* config file not found, no changes to config */
476 if (configFile && flag == FIRST_PARSE) /* if -c option given */
477 bb_perror_msg_and_die("%s", cf);
478 flag = FIND_FROM_HTTPD_ROOT;
482 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
485 /* This could stand some work */
486 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
488 for (p = p0; *p0 != '\0' && *p0 != '#'; p0++) {
491 if (*p0 == ':' && c == NULL)
497 /* test for empty or strange line */
498 if (c == NULL || *c == '\0')
505 /* memorize deny all */
508 /* skip default other "word:*" config lines */
514 if (*p0 == 'A' || *p0 == 'D') {
515 /* storing current config IP line */
516 pip = xzalloc(sizeof(Htaccess_IP));
518 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
519 /* syntax IP{/mask} error detected, protect all */
523 pip->allow_deny = *p0;
525 /* Deny:from_IP move top */
529 /* add to bottom A:form_IP config line */
530 Htaccess_IP *prev_IP = ip_a_d;
532 if (prev_IP == NULL) {
535 while (prev_IP->next)
536 prev_IP = prev_IP->next;
544 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
545 if (flag == FIRST_PARSE && *p0 == 'E') {
547 /* error status code */
548 int status = atoi(++p0);
549 /* c already points at the character following ':' in parse loop */
550 /* c = strchr(p0, ':'); c++; */
551 if (status < HTTP_CONTINUE) {
552 bb_error_msg("config error '%s' in '%s'", buf, cf);
556 /* then error page; find matching status */
557 for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
558 if (http_response_type[i] == status) {
559 http_error_page[i] = concat_path_file((*c == '/') ? NULL : home_httpd, c);
567 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
569 /* make full path from httpd root / current_path / config_line_path */
570 cf = (flag == SUBDIR_PARSE ? path : "");
571 p0 = xmalloc(strlen(cf) + (c - buf) + 2 + strlen(c));
573 sprintf(p0, "/%s%s", cf, buf);
575 /* another call bb_simplify_path */
580 if (*cf == '/') { /* skip duplicate (or initial) slash */
582 } else if (*cf == '.') {
583 if (cf[1] == '/' || cf[1] == '\0') { /* remove extra '.' */
585 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == '\0')) {
588 while (*--p != '/') /* omit previous dir */;
597 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
598 ++p; /* so keep last character */
601 sprintf(p0, "%s:%s", p0, c);
605 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
606 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
607 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
608 /* storing current config line */
609 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
611 cf = strcpy(cur->before_colon, p0);
614 cur->after_colon = c;
615 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
617 /* config .mime line move top for overwrite previous */
623 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
624 if (*cf == '*' && cf[1] == '.') {
625 /* config script interpreter line move top for overwrite previous */
626 cur->next = script_i;
631 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
637 /* sort path, if current lenght eq or bigger then move up */
638 Htaccess *prev_hti = g_auth;
639 size_t l = strlen(cf);
642 for (hti = prev_hti; hti; hti = hti->next) {
643 if (l >= strlen(hti->before_colon)) {
644 /* insert before hti */
646 if (prev_hti != hti) {
647 prev_hti->next = cur;
655 prev_hti = prev_hti->next;
657 if (!hti) { /* not inserted, add to bottom */
669 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
671 * Given a string, html-encode special characters.
672 * This is used for the -e command line option to provide an easy way
673 * for scripts to encode result data without confusing browsers. The
674 * returned string pointer is memory allocated by malloc().
676 * Returns a pointer to the encoded string (malloced).
678 static char *encodeString(const char *string)
680 /* take the simple route and encode everything */
681 /* could possibly scan once to get length. */
682 int len = strlen(string);
683 char *out = xmalloc(len * 6 + 1);
687 while ((ch = *string++)) {
688 /* very simple check for what to encode */
692 p += sprintf(p, "&#%d;", (unsigned char) ch);
697 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
700 * Given a URL encoded string, convert it to plain ascii.
701 * Since decoding always makes strings smaller, the decode is done in-place.
702 * Thus, callers should strdup() the argument if they do not want the
703 * argument modified. The return is the original pointer, allowing this
704 * function to be easily used as arguments to other functions.
706 * string The first string to decode.
707 * option_d 1 if called for httpd -d
709 * Returns a pointer to the decoded string (same as input).
711 static unsigned hex_to_bin(unsigned char c)
718 /* c | 0x20: letters to lower case, non-letters
719 * to (potentially different) non-letters */
720 v = (unsigned)(c | 0x20) - 'a';
726 void t(char c) { printf("'%c'(%u) %u\n", c, c, hex_to_bin(c)); }
727 int main() { t(0x10); t(0x20); t('0'); t('9'); t('A'); t('F'); t('a'); t('f');
728 t('0'-1); t('9'+1); t('A'-1); t('F'+1); t('a'-1); t('f'+1); return 0; }
730 static char *decodeString(char *orig, int option_d)
732 /* note that decoded string is always shorter than original */
737 while ((c = *ptr++) != '\0') {
740 if (option_d && c == '+') {
748 v = hex_to_bin(ptr[0]);
756 v = (v * 16) | hex_to_bin(ptr[1]);
759 if (!option_d && (v == '/' || v == '\0')) {
760 /* caller takes it as indication of invalid
761 * (dangerous wrt exploits) chars */
771 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
773 * Decode a base64 data stream as per rfc1521.
774 * Note that the rfc states that non base64 chars are to be ignored.
775 * Since the decode always results in a shorter size than the input,
776 * it is OK to pass the input arg as an output arg.
777 * Parameter: a pointer to a base64 encoded string.
778 * Decoded data is stored in-place.
780 static void decodeBase64(char *Data)
782 const unsigned char *in = (const unsigned char *)Data;
783 /* The decoded size will be at most 3/4 the size of the encoded */
790 if (t >= '0' && t <= '9')
792 else if (t >= 'A' && t <= 'Z')
794 else if (t >= 'a' && t <= 'z')
808 *Data++ = (char) (ch >> 16);
809 *Data++ = (char) (ch >> 8);
819 * Create a listen server socket on the designated port.
821 static int openServer(void)
823 int n = bb_strtou(bind_addr_or_port, NULL, 10);
824 if (!errno && n && n <= 0xffff)
825 n = create_and_bind_stream_or_die(NULL, n);
827 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
833 * Log the connection closure and exit.
835 static void log_and_exit(void) ATTRIBUTE_NORETURN;
836 static void log_and_exit(void)
838 /* Paranoia. IE said to be buggy. It may send some extra data
839 * or be confused by us just exiting without SHUT_WR. Oh well. */
840 shutdown(1, SHUT_WR);
842 while (read(0, iobuf, IOBUF_SIZE) > 0)
846 bb_error_msg("closed");
847 _exit(xfunc_error_retval);
851 * Create and send HTTP response headers.
852 * The arguments are combined and sent as one write operation. Note that
853 * IE will puke big-time if the headers are not sent in one packet and the
854 * second packet is delayed for any reason.
855 * responseNum - the result code to send.
857 static void send_headers(int responseNum)
859 static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
861 const char *responseString = "";
862 const char *infoString = NULL;
863 const char *mime_type;
864 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
865 const char *error_page = 0;
868 time_t timer = time(0);
872 for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
873 if (http_response_type[i] == responseNum) {
874 responseString = http_response[i].name;
875 infoString = http_response[i].info;
876 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
877 error_page = http_error_page[i];
882 /* error message is HTML */
883 mime_type = responseNum == HTTP_OK ?
884 found_mime_type : "text/html";
887 bb_error_msg("response:%u", responseNum);
889 /* emit the current date */
890 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
892 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
893 "Date: %s\r\nConnection: close\r\n",
894 responseNum, responseString, mime_type, tmp_str);
896 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
897 if (responseNum == HTTP_UNAUTHORIZED) {
898 len += sprintf(iobuf + len,
899 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
903 if (responseNum == HTTP_MOVED_TEMPORARILY) {
904 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
905 found_moved_temporarily,
906 (g_query ? "?" : ""),
907 (g_query ? g_query : ""));
910 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
911 if (error_page && !access(error_page, R_OK)) {
912 strcat(iobuf, "\r\n");
916 fprintf(stderr, "headers: '%s'\n", iobuf);
917 full_write(1, iobuf, len);
919 fprintf(stderr, "writing error page: '%s'\n", error_page);
920 return send_file_and_exit(error_page, FALSE);
924 if (ContentLength != -1) { /* file */
925 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
926 len += sprintf(iobuf + len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
927 tmp_str, "Content-length:", ContentLength);
932 len += sprintf(iobuf + len,
933 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
934 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
935 responseNum, responseString,
936 responseNum, responseString, infoString);
939 fprintf(stderr, "headers: '%s'\n", iobuf);
940 if (full_write(1, iobuf, len) != len) {
942 bb_perror_msg("error");
947 static void send_headers_and_exit(int responseNum) ATTRIBUTE_NORETURN;
948 static void send_headers_and_exit(int responseNum)
950 send_headers(responseNum);
955 * Read from the socket until '\n' or EOF. '\r' chars are removed.
956 * '\n' is replaced with NUL.
957 * Return number of characters read or 0 if nothing is read
958 * ('\r' and '\n' are not counted).
959 * Data is returned in iobuf.
961 static int get_line(void)
968 hdr_cnt = safe_read(0, hdr_buf, sizeof(hdr_buf));
973 iobuf[count] = c = *hdr_ptr++;
982 if (count < (IOBUF_SIZE - 1)) /* check overflow */
988 #if ENABLE_FEATURE_HTTPD_CGI
989 static void setenv1(const char *name, const char *value)
991 setenv(name, value ? value : "", 1);
995 * Spawn CGI script, forward CGI's stdin/out <=> network
997 * Environment variables are set up and the script is invoked with pipes
998 * for stdin/stdout. If a post is being done the script is fed the POST
999 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
1002 * const char *url The requested URL (with leading /).
1003 * int bodyLen Length of the post body.
1004 * const char *cookie For set HTTP_COOKIE.
1005 * const char *content_type For set CONTENT_TYPE.
1007 static void send_cgi_and_exit(
1009 const char *request,
1012 const char *content_type) ATTRIBUTE_NORETURN;
1013 static void send_cgi_and_exit(
1015 const char *request,
1018 const char *content_type)
1020 struct { int rd; int wr; } fromCgi; /* CGI -> httpd pipe */
1021 struct { int rd; int wr; } toCgi; /* httpd -> CGI pipe */
1030 * We are mucking with environment _first_ and then vfork/exec,
1031 * this allows us to use vfork safely. Parent don't care about
1032 * these environment changes anyway.
1038 purl = xstrdup(url);
1040 while ((script = strchr(script + 1, '/')) != NULL) {
1041 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1045 if (!is_directory(purl + 1, 1, &sb)) {
1046 /* not directory, found script.cgi/PATH_INFO */
1050 *script = '/'; /* is directory, find next '/' */
1052 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1053 setenv1("REQUEST_METHOD", request);
1055 putenv(xasprintf("%s=%s?%s", "REQUEST_URI", purl, g_query));
1057 setenv1("REQUEST_URI", purl);
1060 *script = '\0'; /* cut off /PATH_INFO */
1062 /* SCRIPT_FILENAME required by PHP in CGI mode */
1063 fullpath = concat_path_file(home_httpd, purl);
1064 setenv1("SCRIPT_FILENAME", fullpath);
1065 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1066 setenv1("SCRIPT_NAME", purl);
1067 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1068 * QUERY_STRING: The information which follows the ? in the URL
1069 * which referenced this script. This is the query information.
1070 * It should not be decoded in any fashion. This variable
1071 * should always be set when there is query information,
1072 * regardless of command line decoding. */
1073 /* (Older versions of bbox seem to do some decoding) */
1074 setenv1("QUERY_STRING", g_query);
1075 putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1076 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1077 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1078 /* Having _separate_ variables for IP and port defeats
1079 * the purpose of having socket abstraction. Which "port"
1080 * are you using on Unix domain socket?
1081 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1084 char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
1085 char *cp = strrchr(p, ':');
1086 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1088 if (cp) *cp = '\0'; /* delete :PORT */
1089 setenv1("REMOTE_ADDR", p);
1092 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1093 setenv1("REMOTE_PORT", cp + 1);
1097 setenv1("HTTP_USER_AGENT", user_agent);
1099 putenv(xasprintf("CONTENT_LENGTH=%d", bodyLen));
1101 setenv1("HTTP_COOKIE", cookie);
1103 setenv1("CONTENT_TYPE", content_type);
1104 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1106 setenv1("REMOTE_USER", remoteuser);
1107 putenv((char*)"AUTH_TYPE=Basic");
1111 setenv1("HTTP_REFERER", referer);
1118 /* TODO: log perror? */
1124 xfunc_error_retval = 242;
1126 xmove_fd(toCgi.rd, 0); /* replace stdin with the pipe */
1127 xmove_fd(fromCgi.wr, 1); /* replace stdout with the pipe */
1130 /* User seeing stderr output can be a security problem.
1131 * If CGI really wants that, it can always do dup itself. */
1134 /* script must have absolute path */
1135 script = strrchr(fullpath, '/');
1137 goto error_execing_cgi;
1139 /* chdiring to script's dir */
1140 if (chdir(fullpath) == 0) {
1142 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1143 char *interpr = NULL;
1144 char *suffix = strrchr(purl, '.');
1148 for (cur = script_i; cur; cur = cur->next) {
1149 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1150 interpr = cur->after_colon;
1157 /* set argv[0] to name without path */
1158 argv[0] = (char*)bb_basename(purl);
1160 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1162 execv(interpr, argv);
1165 execv(fullpath, argv);
1169 * (we are CGI here, our stdout is pumped to the net) */
1170 send_headers_and_exit(HTTP_NOT_FOUND);
1173 /* Parent process */
1175 /* First, restore variables possibly changed by child */
1176 xfunc_error_retval = 0;
1178 /* Prepare for pumping data.
1179 * iobuf is used for CGI -> network data,
1180 * hdr_buf is for network -> CGI data (POSTDATA) */
1185 /* If CGI dies, we still want to correctly finish reading its output
1186 * and send it to the peer. So please no SIGPIPEs! */
1187 signal(SIGPIPE, SIG_IGN);
1189 /* This loop still looks messy. What is an exit criteria?
1190 * "CGI's output closed"? Or "CGI has exited"?
1191 * What to do if CGI has closed both input and output, but
1192 * didn't exit? etc... */
1194 /* NB: breaking out of this loop jumps to log_and_exit() */
1203 FD_SET(fromCgi.rd, &readSet);
1204 if (bodyLen > 0 || hdr_cnt > 0) {
1205 FD_SET(toCgi.wr, &writeSet);
1206 nfound = toCgi.wr > fromCgi.rd ? toCgi.wr : fromCgi.rd;
1208 FD_SET(0, &readSet);
1209 /* Now wait on the set of sockets! */
1210 nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1213 close(toCgi.wr); /* no more POST data to CGI */
1216 nfound = select(fromCgi.rd + 1, &readSet, NULL, NULL, NULL);
1220 if (waitpid(pid, &status, WNOHANG) <= 0) {
1221 /* Weird. CGI didn't exit and no fd's
1222 * are ready, yet select returned?! */
1226 if (DEBUG && WIFEXITED(status))
1227 bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
1228 if (DEBUG && WIFSIGNALED(status))
1229 bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
1233 if (hdr_cnt > 0 && FD_ISSET(toCgi.wr, &writeSet)) {
1234 /* Have data from peer and can write to CGI */
1235 count = safe_write(toCgi.wr, hdr_ptr, hdr_cnt);
1236 /* Doesn't happen, we dont use nonblocking IO here
1237 *if (count < 0 && errno == EAGAIN) {
1244 hdr_cnt = bodyLen = 0; /* EOF/broken pipe to CGI */
1246 } else if (bodyLen > 0 && hdr_cnt == 0
1247 && FD_ISSET(0, &readSet)
1249 /* We expect data, prev data portion is eaten by CGI
1250 * and there *is* data to read from the peer
1252 count = bodyLen > (int)sizeof(hdr_buf) ? (int)sizeof(hdr_buf) : bodyLen;
1253 count = safe_read(0, hdr_buf, count);
1259 bodyLen = 0; /* closed */
1263 #define PIPESIZE PIPE_BUF
1264 #if PIPESIZE >= IOBUF_SIZE
1265 # error "PIPESIZE >= IOBUF_SIZE"
1267 if (FD_ISSET(fromCgi.rd, &readSet)) {
1268 /* There is something to read from CGI */
1271 /* Are we still buffering CGI output? */
1272 if (buf_count >= 0) {
1273 /* HTTP_200[] has single "\r\n" at the end.
1274 * According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1275 * CGI scripts MUST send their own header terminated by
1276 * empty line, then data. That's why we have only one
1277 * <cr><lf> pair here. We will output "200 OK" line
1278 * if needed, but CGI still has to provide blank line
1279 * between header and body */
1281 /* Must use safe_read, not full_read, because
1282 * CGI may output a few first bytes and then wait
1283 * for POSTDATA without closing stdout.
1284 * With full_read we may wait here forever. */
1285 count = safe_read(fromCgi.rd, rbuf + buf_count, PIPESIZE - 8);
1287 /* eof (or error) and there was no "HTTP",
1288 * so write it, then write received data */
1290 full_write(1, HTTP_200, sizeof(HTTP_200)-1);
1291 full_write(1, rbuf, buf_count);
1293 break; /* CGI stdout is closed, exiting */
1297 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1298 if (buf_count >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1299 /* send "HTTP/1.0 " */
1300 if (full_write(1, HTTP_200, 9) != 9)
1302 rbuf += 8; /* skip "Status: " */
1303 count = buf_count - 8;
1304 buf_count = -1; /* buffering off */
1305 } else if (buf_count >= 4) {
1306 /* Did CGI add "HTTP"? */
1307 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1308 /* there is no "HTTP", do it ourself */
1309 if (full_write(1, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1313 if (!strstr(rbuf, "ontent-")) {
1314 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1316 * Counter-example of valid CGI without Content-type:
1317 * echo -en "HTTP/1.0 302 Found\r\n"
1318 * echo -en "Location: http://www.busybox.net\r\n"
1322 buf_count = -1; /* buffering off */
1325 count = safe_read(fromCgi.rd, rbuf, PIPESIZE);
1327 break; /* eof (or error) */
1329 if (full_write(1, rbuf, count) != count)
1332 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1333 } /* if (FD_ISSET(fromCgi.rd)) */
1337 #endif /* FEATURE_HTTPD_CGI */
1340 * Send a file response to a HTTP request, and exit
1343 * const char *url The requested URL (with leading /).
1344 * headers Don't send headers before if FALSE.
1346 static void send_file_and_exit(const char *url, int headers)
1348 static const char *const suffixTable[] = {
1349 /* Warning: shorter equivalent suffix in one line must be first */
1350 ".htm.html", "text/html",
1351 ".jpg.jpeg", "image/jpeg",
1352 ".gif", "image/gif",
1353 ".png", "image/png",
1354 ".txt.h.c.cc.cpp", "text/plain",
1356 ".wav", "audio/wav",
1357 ".avi", "video/x-msvideo",
1358 ".qt.mov", "video/quicktime",
1359 ".mpe.mpeg", "video/mpeg",
1360 ".mid.midi", "audio/midi",
1361 ".mp3", "audio/mpeg",
1362 #if 0 /* unpopular */
1363 ".au", "audio/basic",
1364 ".pac", "application/x-ns-proxy-autoconfig",
1365 ".vrml.wrl", "model/vrml",
1372 const char *const *table;
1373 const char *try_suffix;
1375 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1379 suffix = strrchr(url, '.');
1381 /* If not found, set default as "application/octet-stream"; */
1382 found_mime_type = "application/octet-stream";
1384 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1387 for (table = suffixTable; *table; table += 2) {
1388 try_suffix = strstr(table[0], suffix);
1390 try_suffix += strlen(suffix);
1391 if (*try_suffix == '\0' || *try_suffix == '.') {
1392 found_mime_type = table[1];
1397 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1398 for (cur = mime_a; cur; cur = cur->next) {
1399 if (strcmp(cur->before_colon, suffix) == 0) {
1400 found_mime_type = cur->after_colon;
1408 bb_error_msg("sending file '%s' content-type: %s",
1409 url, found_mime_type);
1411 f = open(url, O_RDONLY);
1414 bb_perror_msg("cannot open '%s'", url);
1416 send_headers_and_exit(HTTP_NOT_FOUND);
1420 send_headers(HTTP_OK);
1422 /* If you want to know about EPIPE below
1423 * (happens if you abort downloads from local httpd): */
1424 signal(SIGPIPE, SIG_IGN);
1426 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1428 /* byte count (3rd arg) is rounded down to 64k */
1429 count = sendfile(1, f, &offset, MAXINT(ssize_t) - 0xffff);
1435 } while (count > 0);
1440 while ((count = safe_read(f, iobuf, IOBUF_SIZE)) > 0) {
1442 count = full_write(1, iobuf, count);
1446 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1449 if (count < 0 && verbose > 1)
1450 bb_perror_msg("error");
1454 static int checkPermIP(void)
1458 /* This could stand some work */
1459 for (cur = ip_a_d; cur; cur = cur->next) {
1462 "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1464 (unsigned char)(cur->ip >> 24),
1465 (unsigned char)(cur->ip >> 16),
1466 (unsigned char)(cur->ip >> 8),
1467 (unsigned char)(cur->ip),
1468 (unsigned char)(cur->mask >> 24),
1469 (unsigned char)(cur->mask >> 16),
1470 (unsigned char)(cur->mask >> 8),
1471 (unsigned char)(cur->mask)
1474 if ((rmt_ip & cur->mask) == cur->ip)
1475 return cur->allow_deny == 'A'; /* Allow/Deny */
1478 /* if unconfigured, return 1 - access from all */
1479 return !flg_deny_all;
1482 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1484 * Check the permission file for access password protected.
1486 * If config file isn't present, everything is allowed.
1487 * Entries are of the form you can see example from header source
1489 * path The file path.
1490 * request User information to validate.
1492 * Returns 1 if request is OK.
1494 static int checkPerm(const char *path, const char *request)
1500 const char *prev = NULL;
1502 /* This could stand some work */
1503 for (cur = g_auth; cur; cur = cur->next) {
1506 p0 = cur->before_colon;
1507 if (prev != NULL && strcmp(prev, p0) != 0)
1508 continue; /* find next identical */
1509 p = cur->after_colon;
1511 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1514 if (strncmp(p0, path, l) == 0
1515 && (l == 1 || path[l] == '/' || path[l] == '\0')
1518 /* path match found. Check request */
1519 /* for check next /path:user:password */
1521 u = strchr(request, ':');
1523 /* bad request, ':' required */
1527 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1531 if (strncmp(p, request, u - request) != 0) {
1532 /* user doesn't match */
1535 pp = strchr(p, ':');
1536 if (pp && pp[1] == '$' && pp[2] == '1'
1537 && pp[3] == '$' && pp[4]
1540 cipher = pw_encrypt(u+1, pp);
1541 if (strcmp(cipher, pp) == 0)
1542 goto set_remoteuser_var; /* Ok */
1548 if (strcmp(p, request) == 0) {
1550 remoteuser = strdup(request);
1552 remoteuser[u - request] = '\0';
1559 return prev == NULL;
1561 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1566 static void exit_on_signal(int sig) ATTRIBUTE_NORETURN;
1567 static void exit_on_signal(int sig)
1569 send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
1573 * Handle an incoming http request and exit.
1575 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr) ATTRIBUTE_NORETURN;
1576 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
1578 static const char request_GET[] ALIGN1 = "GET";
1584 int http_major_version;
1586 #if ENABLE_FEATURE_HTTPD_CGI
1587 const char *prequest;
1588 unsigned long length = 0;
1590 char *content_type = 0;
1592 struct sigaction sa;
1593 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1594 int credentials = -1; /* if not required this is Ok */
1597 /* Allocation of iobuf is postponed until now
1598 * (IOW, server process doesn't need to waste 8k) */
1599 iobuf = xmalloc(IOBUF_SIZE);
1602 if (fromAddr->sa.sa_family == AF_INET) {
1603 rmt_ip = ntohl(fromAddr->sin.sin_addr.s_addr);
1605 if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1606 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr->sa);
1609 /* this trick makes -v logging much simpler */
1610 applet_name = rmt_ip_str;
1612 bb_error_msg("connected");
1615 /* Install timeout handler */
1616 memset(&sa, 0, sizeof(sa));
1617 sa.sa_handler = exit_on_signal;
1618 /* sigemptyset(&sa.sa_mask); - memset should be enough */
1619 /*sa.sa_flags = 0; - no SA_RESTART */
1620 sigaction(SIGALRM, &sa, NULL);
1621 alarm(HEADER_READ_TIMEOUT);
1623 if (!get_line()) /* EOF or error or empty line */
1624 send_headers_and_exit(HTTP_BAD_REQUEST);
1626 /* Determine type of request (GET/POST) */
1627 urlp = strpbrk(iobuf, " \t");
1629 send_headers_and_exit(HTTP_BAD_REQUEST);
1631 #if ENABLE_FEATURE_HTTPD_CGI
1632 prequest = request_GET;
1633 if (strcasecmp(iobuf, prequest) != 0) {
1635 if (strcasecmp(iobuf, prequest) != 0)
1636 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1639 if (strcasecmp(iobuf, request_GET) != 0)
1640 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1642 urlp = skip_whitespace(urlp);
1644 send_headers_and_exit(HTTP_BAD_REQUEST);
1646 /* Find end of URL and parse HTTP version, if any */
1647 http_major_version = -1;
1648 tptr = strchrnul(urlp, ' ');
1649 /* Is it " HTTP/"? */
1650 if (tptr[0] && strncmp(tptr + 1, HTTP_200, 5) == 0)
1651 http_major_version = (tptr[6] - '0');
1654 /* Copy URL from after "GET "/"POST " to stack-allocated char[] */
1655 urlcopy = alloca((tptr - urlp) + sizeof("/index.html"));
1656 /*if (urlcopy == NULL)
1657 * send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);*/
1658 strcpy(urlcopy, urlp);
1659 /* NB: urlcopy ptr is never changed after this */
1661 /* Extract url args if present */
1662 tptr = strchr(urlcopy, '?');
1669 /* Decode URL escape sequences */
1670 tptr = decodeString(urlcopy, 0);
1672 send_headers_and_exit(HTTP_BAD_REQUEST);
1673 if (tptr == urlcopy + 1) {
1674 /* '/' or NUL is encoded */
1675 send_headers_and_exit(HTTP_NOT_FOUND);
1678 /* Canonicalize path */
1679 /* Algorithm stolen from libbb bb_simplify_path(),
1680 * but don't strdup and reducing trailing slash and protect out root */
1681 urlp = tptr = urlcopy;
1684 /* skip duplicate (or initial) slash */
1689 /* skip extra '.' */
1690 if (tptr[1] == '/' || !tptr[1]) {
1693 /* '..': be careful */
1694 if (tptr[1] == '.' && (tptr[2] == '/' || !tptr[2])) {
1696 if (urlp == urlcopy) /* protect root */
1697 send_headers_and_exit(HTTP_BAD_REQUEST);
1698 while (*--urlp != '/') /* omit previous dir */;
1705 *++urlp = '\0'; /* so keep last character */
1706 tptr = urlp; /* end ptr */
1708 /* If URL is a directory, add '/' */
1709 if (tptr[-1] != '/') {
1710 if (is_directory(urlcopy + 1, 1, &sb)) {
1711 found_moved_temporarily = urlcopy;
1717 bb_error_msg("url:%s", urlcopy);
1720 ip_allowed = checkPermIP();
1721 while (ip_allowed && (tptr = strchr(tptr + 1, '/')) != NULL) {
1722 /* have path1/path2 */
1724 if (is_directory(urlcopy + 1, 1, &sb)) {
1725 /* may be having subdir config */
1726 parse_conf(urlcopy + 1, SUBDIR_PARSE);
1727 ip_allowed = checkPermIP();
1731 if (http_major_version >= 0) {
1732 /* Request was with "... HTTP/nXXX", and n >= 0 */
1734 /* Read until blank line for HTTP version specified, else parse immediate */
1736 alarm(HEADER_READ_TIMEOUT);
1738 break; /* EOF or error or empty line */
1740 bb_error_msg("header: '%s'", iobuf);
1742 #if ENABLE_FEATURE_HTTPD_CGI
1743 /* try and do our best to parse more lines */
1744 if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
1745 /* extra read only for POST */
1746 if (prequest != request_GET) {
1747 tptr = iobuf + sizeof("Content-length:") - 1;
1749 send_headers_and_exit(HTTP_BAD_REQUEST);
1751 /* not using strtoul: it ignores leading minus! */
1752 length = strtol(tptr, &tptr, 10);
1753 /* length is "ulong", but we need to pass it to int later */
1754 /* so we check for negative or too large values in one go: */
1755 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1756 if (tptr[0] || errno || length > INT_MAX)
1757 send_headers_and_exit(HTTP_BAD_REQUEST);
1759 } else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
1760 cookie = strdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
1761 } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
1762 content_type = strdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
1763 } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
1764 referer = strdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
1765 } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
1766 user_agent = strdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
1769 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1770 if (STRNCASECMP(iobuf, "Authorization:") == 0) {
1771 /* We only allow Basic credentials.
1772 * It shows up as "Authorization: Basic <userid:password>" where
1773 * the userid:password is base64 encoded.
1775 tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
1776 if (STRNCASECMP(tptr, "Basic") != 0)
1778 tptr += sizeof("Basic")-1;
1779 /* decodeBase64() skips whitespace itself */
1781 credentials = checkPerm(urlcopy, tptr);
1783 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1784 } /* while extra header reading */
1787 /* We read headers, disable peer timeout */
1790 if (strcmp(bb_basename(urlcopy), httpd_conf) == 0 || ip_allowed == 0) {
1791 /* protect listing [/path]/httpd_conf or IP deny */
1792 send_headers_and_exit(HTTP_FORBIDDEN);
1795 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1796 if (credentials <= 0 && checkPerm(urlcopy, ":") == 0) {
1797 send_headers_and_exit(HTTP_UNAUTHORIZED);
1801 if (found_moved_temporarily) {
1802 send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
1805 tptr = urlcopy + 1; /* skip first '/' */
1807 #if ENABLE_FEATURE_HTTPD_CGI
1808 if (strncmp(tptr, "cgi-bin/", 8) == 0) {
1809 if (tptr[8] == '\0') {
1810 /* protect listing "cgi-bin/" */
1811 send_headers_and_exit(HTTP_FORBIDDEN);
1813 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1815 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1817 char *suffix = strrchr(tptr, '.');
1820 for (cur = script_i; cur; cur = cur->next) {
1821 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1822 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1828 if (prequest != request_GET) {
1829 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1831 #endif /* FEATURE_HTTPD_CGI */
1833 if (urlp[-1] == '/')
1834 strcpy(urlp, "index.html");
1835 if (stat(tptr, &sb) == 0) {
1836 /* It's a dir URL and there is index.html */
1837 ContentLength = sb.st_size;
1838 last_mod = sb.st_mtime;
1840 #if ENABLE_FEATURE_HTTPD_CGI
1841 else if (urlp[-1] == '/') {
1842 /* It's a dir URL and there is no index.html
1843 * Try cgi-bin/index.cgi */
1844 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1847 send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1852 * fall through to send_file, it errors out if open fails
1856 send_file_and_exit(tptr, TRUE);
1860 * The main http server function.
1861 * Given a socket, listen for new connections and farm out
1862 * the processing as a [v]forked process.
1866 static void mini_httpd(int server_socket) ATTRIBUTE_NORETURN;
1867 static void mini_httpd(int server_socket)
1869 /* NB: it's best to not use xfuncs in this loop before fork().
1870 * Otherwise server may die on transient errors (temporary
1871 * out-of-memory condition, etc), which is Bad(tm).
1872 * Try to do any dangerous calls after fork.
1876 len_and_sockaddr fromAddr;
1878 /* Wait for connections... */
1879 fromAddr.len = LSA_SIZEOF_SA;
1880 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1884 /* set the KEEPALIVE option to cull dead connections */
1885 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1889 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1890 /* Do not reload config on HUP */
1891 signal(SIGHUP, SIG_IGN);
1893 close(server_socket);
1897 handle_incoming_and_exit(&fromAddr);
1899 /* parent, or fork failed */
1905 static void mini_httpd_nommu(int server_socket, int argc, char **argv) ATTRIBUTE_NORETURN;
1906 static void mini_httpd_nommu(int server_socket, int argc, char **argv)
1908 char *argv_copy[argc + 2];
1910 argv_copy[0] = argv[0];
1911 argv_copy[1] = (char*)"-i";
1912 memcpy(&argv_copy[2], &argv[1], argc * sizeof(argv[0]));
1914 /* NB: it's best to not use xfuncs in this loop before vfork().
1915 * Otherwise server may die on transient errors (temporary
1916 * out-of-memory condition, etc), which is Bad(tm).
1917 * Try to do any dangerous calls after fork.
1921 len_and_sockaddr fromAddr;
1923 /* Wait for connections... */
1924 fromAddr.len = LSA_SIZEOF_SA;
1925 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1929 /* set the KEEPALIVE option to cull dead connections */
1930 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1934 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1935 /* Do not reload config on HUP */
1936 signal(SIGHUP, SIG_IGN);
1938 close(server_socket);
1942 /* Run a copy of ourself in inetd mode */
1945 /* parent, or vfork failed */
1953 * Process a HTTP connection on stdin/out.
1956 static void mini_httpd_inetd(void) ATTRIBUTE_NORETURN;
1957 static void mini_httpd_inetd(void)
1959 len_and_sockaddr fromAddr;
1961 fromAddr.len = LSA_SIZEOF_SA;
1962 getpeername(0, &fromAddr.sa, &fromAddr.len);
1963 handle_incoming_and_exit(&fromAddr);
1966 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1967 static void sighup_handler(int sig)
1969 struct sigaction sa;
1971 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1973 memset(&sa, 0, sizeof(sa));
1974 sa.sa_handler = sighup_handler;
1975 /*sigemptyset(&sa.sa_mask); - memset should be enough */
1976 sa.sa_flags = SA_RESTART;
1977 sigaction(SIGHUP, &sa, NULL);
1982 c_opt_config_file = 0,
1985 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1986 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1987 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1988 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1993 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1994 OPT_DECODE_URL = 1 << d_opt_decode_url,
1995 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1996 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1997 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1998 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1999 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
2000 OPT_PORT = 1 << p_opt_port,
2001 OPT_INETD = 1 << p_opt_inetd,
2002 OPT_FOREGROUND = 1 << p_opt_foreground,
2003 OPT_VERBOSE = 1 << p_opt_verbose,
2007 int httpd_main(int argc, char **argv);
2008 int httpd_main(int argc, char **argv)
2010 int server_socket = server_socket; /* for gcc */
2012 char *url_for_decode;
2013 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
2014 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
2015 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
2016 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
2020 #if ENABLE_LOCALE_SUPPORT
2021 /* Undo busybox.c: we want to speak English in http (dates etc) */
2022 setlocale(LC_TIME, "C");
2025 home_httpd = xrealloc_getcwd_or_warn(NULL);
2026 /* -v counts, -i implies -f */
2027 opt_complementary = "vv:if";
2028 /* We do not "absolutize" path given by -h (home) opt.
2029 * If user gives relative path in -h, $SCRIPT_FILENAME can end up
2031 opt = getopt32(argv, "c:d:h:"
2032 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
2033 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
2034 USE_FEATURE_HTTPD_AUTH_MD5("m:")
2035 USE_FEATURE_HTTPD_SETUID("u:")
2037 &configFile, &url_for_decode, &home_httpd
2038 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
2039 USE_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
2040 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
2041 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
2042 , &bind_addr_or_port
2045 if (opt & OPT_DECODE_URL) {
2046 fputs(decodeString(url_for_decode, 1), stdout);
2049 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
2050 if (opt & OPT_ENCODE_URL) {
2051 fputs(encodeString(url_for_encode), stdout);
2055 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
2056 if (opt & OPT_MD5) {
2057 puts(pw_encrypt(pass, "$1$"));
2061 #if ENABLE_FEATURE_HTTPD_SETUID
2062 if (opt & OPT_SETUID) {
2063 if (!get_uidgid(&ugid, s_ugid, 1))
2064 bb_error_msg_and_die("unrecognized user[:group] "
2065 "name '%s'", s_ugid);
2070 if (!(opt & OPT_FOREGROUND)) {
2071 bb_daemonize_or_rexec(0, argv); /* don't change current directory */
2076 if (!(opt & OPT_INETD)) {
2077 signal(SIGCHLD, SIG_IGN);
2078 server_socket = openServer();
2079 #if ENABLE_FEATURE_HTTPD_SETUID
2080 /* drop privileges */
2081 if (opt & OPT_SETUID) {
2082 if (ugid.gid != (gid_t)-1) {
2083 if (setgroups(1, &ugid.gid) == -1)
2084 bb_perror_msg_and_die("setgroups");
2092 #if ENABLE_FEATURE_HTTPD_CGI
2094 char *p = getenv("PATH");
2095 /* env strings themself are not freed, no need to strdup(p): */
2099 // if (!(opt & OPT_INETD))
2100 // setenv_long("SERVER_PORT", ???);
2104 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2105 if (!(opt & OPT_INETD))
2107 else /* do not install HUP handler in inetd mode */
2109 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2111 xfunc_error_retval = 0;
2112 if (opt & OPT_INETD)
2115 if (!(opt & OPT_FOREGROUND))
2116 bb_daemonize(0); /* don't change current directory */
2117 mini_httpd(server_socket); /* never returns */
2119 mini_httpd_nommu(server_socket, argc, argv); /* never returns */