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[] = {
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; \
292 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
295 static void send_file_and_exit(const char *url, int headers) ATTRIBUTE_NORETURN;
297 static void free_llist(has_next_ptr **pptr)
299 has_next_ptr *cur = *pptr;
301 has_next_ptr *t = cur;
308 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
309 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
310 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
311 static ALWAYS_INLINE void free_Htaccess_list(Htaccess **pptr)
313 free_llist((has_next_ptr**)pptr);
317 static ALWAYS_INLINE void free_Htaccess_IP_list(Htaccess_IP **pptr)
319 free_llist((has_next_ptr**)pptr);
322 /* Returns presumed mask width in bits or < 0 on error.
323 * Updates strp, stores IP at provided pointer */
324 static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
326 const char *p = *strp;
334 for (j = 0; j < 4; j++) {
337 if ((*p < '0' || *p > '9') && *p != '/' && *p)
340 while (*p >= '0' && *p <= '9') {
351 ip = (ip << 8) | octet;
365 /* Returns 0 on success. Stores IP and mask at provided pointers */
366 static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
372 i = scan_ip(&str, ipp, '/');
377 /* there is /xxx after dotted-IP address */
378 i = bb_strtou(str, &p, 10);
380 /* 'xxx' itself is dotted-IP mask, parse it */
381 /* (return 0 (success) only if it has N.N.N.N form) */
382 return scan_ip(&str, maskp, '\0') - 32;
391 if (sizeof(unsigned) == 4 && i == 32) {
392 /* mask >>= 32 below may not work */
398 /* i == 0 -> *maskp = 0x00000000
399 * i == 1 -> *maskp = 0x80000000
400 * i == 4 -> *maskp = 0xf0000000
401 * i == 31 -> *maskp = 0xfffffffe
402 * i == 32 -> *maskp = 0xffffffff */
403 *maskp = (uint32_t)(~mask);
408 * Parse configuration file into in-memory linked list.
410 * The first non-white character is examined to determine if the config line
411 * is one of the following:
412 * .ext:mime/type # new mime type not compiled into httpd
413 * [adAD]:from # ip address allow/deny, * for wildcard
414 * /path:user:pass # username/password
415 * Ennn:error.html # error page for status nnn
417 * Any previous IP rules are discarded.
418 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
419 * are also discarded. That is, previous settings are retained if flag is
421 * Error pages are only parsed on the main config file.
423 * path Path where to look for httpd.conf (without filename).
424 * flag Type of the parse request.
427 #define FIRST_PARSE 0
428 #define SUBDIR_PARSE 1
429 #define SIGNALED_PARSE 2
430 #define FIND_FROM_HTTPD_ROOT 3
431 static void parse_conf(const char *path, int flag)
434 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
437 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
438 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
439 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
442 const char *cf = configFile;
448 /* discard old rules */
449 free_Htaccess_IP_list(&ip_a_d);
451 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
452 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
453 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
454 /* retain previous auth and mime config only for subdir parse */
455 if (flag != SUBDIR_PARSE) {
456 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
457 free_Htaccess_list(&g_auth);
459 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
460 free_Htaccess_list(&mime_a);
462 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
463 free_Htaccess_list(&script_i);
468 if (flag == SUBDIR_PARSE || cf == NULL) {
469 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
471 if (flag == FIRST_PARSE)
472 bb_error_msg_and_die(bb_msg_memory_exhausted);
475 sprintf((char *)cf, "%s/%s", path, httpd_conf);
478 while ((f = fopen(cf, "r")) == NULL) {
479 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
480 /* config file not found, no changes to config */
483 if (configFile && flag == FIRST_PARSE) /* if -c option given */
484 bb_perror_msg_and_die("%s", cf);
485 flag = FIND_FROM_HTTPD_ROOT;
489 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
492 /* This could stand some work */
493 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
495 for (p = p0; *p0 != '\0' && *p0 != '#'; p0++) {
498 if (*p0 == ':' && c == NULL)
504 /* test for empty or strange line */
505 if (c == NULL || *c == '\0')
512 /* memorize deny all */
515 /* skip default other "word:*" config lines */
521 if (*p0 == 'A' || *p0 == 'D') {
522 /* storing current config IP line */
523 pip = xzalloc(sizeof(Htaccess_IP));
525 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
526 /* syntax IP{/mask} error detected, protect all */
530 pip->allow_deny = *p0;
532 /* Deny:from_IP move top */
536 /* add to bottom A:form_IP config line */
537 Htaccess_IP *prev_IP = ip_a_d;
539 if (prev_IP == NULL) {
542 while (prev_IP->next)
543 prev_IP = prev_IP->next;
551 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
552 if (flag == FIRST_PARSE && *p0 == 'E') {
554 /* error status code */
555 int status = atoi(++p0);
556 /* c already points at the character following ':' in parse loop */
557 // c = strchr(p0, ':'); c++;
558 if (status < HTTP_CONTINUE) {
559 bb_error_msg("config error '%s' in '%s'", buf, cf);
563 /* then error page; find matching status */
564 for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
565 if (http_response_type[i] == status) {
566 http_error_page[i] = concat_path_file((*c == '/') ? NULL : home_httpd, c);
574 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
576 /* make full path from httpd root / current_path / config_line_path */
577 cf = (flag == SUBDIR_PARSE ? path : "");
578 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
582 sprintf(p0, "/%s%s", cf, buf);
584 /* another call bb_simplify_path */
589 if (*cf == '/') { /* skip duplicate (or initial) slash */
591 } else if (*cf == '.') {
592 if (cf[1] == '/' || cf[1] == '\0') { /* remove extra '.' */
594 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == '\0')) {
597 while (*--p != '/') /* omit previous dir */;
606 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
607 ++p; /* so keep last character */
610 sprintf(p0, "%s:%s", p0, c);
614 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
615 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
616 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
617 /* storing current config line */
618 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
620 cf = strcpy(cur->before_colon, p0);
623 cur->after_colon = c;
624 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
626 /* config .mime line move top for overwrite previous */
632 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
633 if (*cf == '*' && cf[1] == '.') {
634 /* config script interpreter line move top for overwrite previous */
635 cur->next = script_i;
640 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
646 /* sort path, if current lenght eq or bigger then move up */
647 Htaccess *prev_hti = g_auth;
648 size_t l = strlen(cf);
651 for (hti = prev_hti; hti; hti = hti->next) {
652 if (l >= strlen(hti->before_colon)) {
653 /* insert before hti */
655 if (prev_hti != hti) {
656 prev_hti->next = cur;
664 prev_hti = prev_hti->next;
666 if (!hti) { /* not inserted, add to bottom */
678 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
680 * Given a string, html-encode special characters.
681 * This is used for the -e command line option to provide an easy way
682 * for scripts to encode result data without confusing browsers. The
683 * returned string pointer is memory allocated by malloc().
685 * Returns a pointer to the encoded string (malloced).
687 static char *encodeString(const char *string)
689 /* take the simple route and encode everything */
690 /* could possibly scan once to get length. */
691 int len = strlen(string);
692 char *out = xmalloc(len * 6 + 1);
696 while ((ch = *string++)) {
697 // very simple check for what to encode
698 if (isalnum(ch)) *p++ = ch;
699 else p += sprintf(p, "&#%d;", (unsigned char) ch);
704 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
707 * Given a URL encoded string, convert it to plain ascii.
708 * Since decoding always makes strings smaller, the decode is done in-place.
709 * Thus, callers should strdup() the argument if they do not want the
710 * argument modified. The return is the original pointer, allowing this
711 * function to be easily used as arguments to other functions.
713 * string The first string to decode.
714 * option_d 1 if called for httpd -d
716 * Returns a pointer to the decoded string (same as input).
718 static unsigned hex_to_bin(unsigned char c)
720 unsigned v = c | 0x20; /* lowercase */
730 void t(char c) { printf("'%c' %u\n", c, hex_to_bin(c)); }
731 int main() { t('0'); t('9'); t('A'); t('F'); t('a'); t('f');
732 t('0'-1); t('9'+1); t('A'-1); t('F'+1); t('a'-1); t('f'+1); return 0; }
734 static char *decodeString(char *orig, int option_d)
736 /* note that decoded string is always shorter than original */
741 while ((c = *ptr++) != '\0') {
744 if (option_d && c == '+') {
752 v = hex_to_bin(ptr[0]);
760 v = (v * 16) | hex_to_bin(ptr[1]);
763 if (!option_d && (v == '/' || v == '\0')) {
764 /* caller takes it as indication of invalid
765 * (dangerous wrt exploits) chars */
775 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
777 * Decode a base64 data stream as per rfc1521.
778 * Note that the rfc states that non base64 chars are to be ignored.
779 * Since the decode always results in a shorter size than the input,
780 * it is OK to pass the input arg as an output arg.
781 * Parameter: a pointer to a base64 encoded string.
782 * Decoded data is stored in-place.
784 static void decodeBase64(char *Data)
786 const unsigned char *in = (const unsigned char *)Data;
787 /* The decoded size will be at most 3/4 the size of the encoded */
794 if (t >= '0' && t <= '9')
796 else if (t >= 'A' && t <= 'Z')
798 else if (t >= 'a' && t <= 'z')
812 *Data++ = (char) (ch >> 16);
813 *Data++ = (char) (ch >> 8);
823 * Create a listen server socket on the designated port.
825 static int openServer(void)
827 int n = bb_strtou(bind_addr_or_port, NULL, 10);
828 if (!errno && n && n <= 0xffff)
829 n = create_and_bind_stream_or_die(NULL, n);
831 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
837 * Log the connection closure and exit.
839 static void log_and_exit(void) ATTRIBUTE_NORETURN;
840 static void log_and_exit(void)
842 /* Paranoia. IE said to be buggy. It may send some extra data
843 * or be confused by us just exiting without SHUT_WR. Oh well. */
844 shutdown(1, SHUT_WR);
846 while (read(0, iobuf, IOBUF_SIZE) > 0)
850 bb_error_msg("closed");
851 _exit(xfunc_error_retval);
855 * Create and send HTTP response headers.
856 * The arguments are combined and sent as one write operation. Note that
857 * IE will puke big-time if the headers are not sent in one packet and the
858 * second packet is delayed for any reason.
859 * responseNum - the result code to send.
861 static void send_headers(int responseNum)
863 static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
865 const char *responseString = "";
866 const char *infoString = NULL;
867 const char *mime_type;
868 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
869 const char *error_page = 0;
872 time_t timer = time(0);
876 for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
877 if (http_response_type[i] == responseNum) {
878 responseString = http_response[i].name;
879 infoString = http_response[i].info;
880 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
881 error_page = http_error_page[i];
886 /* error message is HTML */
887 mime_type = responseNum == HTTP_OK ?
888 found_mime_type : "text/html";
891 bb_error_msg("response:%u", responseNum);
893 /* emit the current date */
894 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
896 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
897 "Date: %s\r\nConnection: close\r\n",
898 responseNum, responseString, mime_type, tmp_str);
900 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
901 if (responseNum == HTTP_UNAUTHORIZED) {
902 len += sprintf(iobuf + len,
903 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
907 if (responseNum == HTTP_MOVED_TEMPORARILY) {
908 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
909 found_moved_temporarily,
910 (g_query ? "?" : ""),
911 (g_query ? g_query : ""));
914 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
915 if (error_page && !access(error_page, R_OK)) {
916 strcat(iobuf, "\r\n");
920 fprintf(stderr, "headers: '%s'\n", iobuf);
921 full_write(1, iobuf, len);
923 fprintf(stderr, "writing error page: '%s'\n", error_page);
924 return send_file_and_exit(error_page, FALSE);
928 if (ContentLength != -1) { /* file */
929 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
930 len += sprintf(iobuf + len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
931 tmp_str, "Content-length:", ContentLength);
936 len += sprintf(iobuf + len,
937 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
938 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
939 responseNum, responseString,
940 responseNum, responseString, infoString);
943 fprintf(stderr, "headers: '%s'\n", iobuf);
944 if (full_write(1, iobuf, len) != len) {
946 bb_perror_msg("error");
951 static void send_headers_and_exit(int responseNum) ATTRIBUTE_NORETURN;
952 static void send_headers_and_exit(int responseNum)
954 send_headers(responseNum);
959 * Read from the socket until '\n' or EOF. '\r' chars are removed.
960 * '\n' is replaced with NUL.
961 * Return number of characters read or 0 if nothing is read
962 * ('\r' and '\n' are not counted).
963 * Data is returned in iobuf.
965 static int get_line(void)
972 hdr_cnt = safe_read(0, hdr_buf, sizeof(hdr_buf));
977 iobuf[count] = c = *hdr_ptr++;
986 if (count < (IOBUF_SIZE - 1)) /* check overflow */
992 #if ENABLE_FEATURE_HTTPD_CGI
993 static void setenv1(const char *name, const char *value)
995 setenv(name, value ? value : "", 1);
999 * Spawn CGI script, forward CGI's stdin/out <=> network
1001 * Environment variables are set up and the script is invoked with pipes
1002 * for stdin/stdout. If a post is being done the script is fed the POST
1003 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
1006 * const char *url The requested URL (with leading /).
1007 * int bodyLen Length of the post body.
1008 * const char *cookie For set HTTP_COOKIE.
1009 * const char *content_type For set CONTENT_TYPE.
1011 static void send_cgi_and_exit(
1013 const char *request,
1016 const char *content_type) ATTRIBUTE_NORETURN;
1017 static void send_cgi_and_exit(
1019 const char *request,
1022 const char *content_type)
1024 struct { int rd; int wr; } fromCgi; /* CGI -> httpd pipe */
1025 struct { int rd; int wr; } toCgi; /* httpd -> CGI pipe */
1034 * We are mucking with environment _first_ and then vfork/exec,
1035 * this allows us to use vfork safely. Parent don't care about
1036 * these environment changes anyway.
1042 purl = xstrdup(url);
1044 while ((script = strchr(script + 1, '/')) != NULL) {
1045 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1049 if (!is_directory(purl + 1, 1, &sb)) {
1050 /* not directory, found script.cgi/PATH_INFO */
1054 *script = '/'; /* is directory, find next '/' */
1056 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1057 setenv1("REQUEST_METHOD", request);
1059 putenv(xasprintf("%s=%s?%s", "REQUEST_URI", purl, g_query));
1061 setenv1("REQUEST_URI", purl);
1064 *script = '\0'; /* cut off /PATH_INFO */
1066 /* SCRIPT_FILENAME required by PHP in CGI mode */
1067 fullpath = concat_path_file(home_httpd, purl);
1068 setenv1("SCRIPT_FILENAME", fullpath);
1069 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1070 setenv1("SCRIPT_NAME", purl);
1071 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1072 * QUERY_STRING: The information which follows the ? in the URL
1073 * which referenced this script. This is the query information.
1074 * It should not be decoded in any fashion. This variable
1075 * should always be set when there is query information,
1076 * regardless of command line decoding. */
1077 /* (Older versions of bbox seem to do some decoding) */
1078 setenv1("QUERY_STRING", g_query);
1079 putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1080 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1081 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1082 /* Having _separate_ variables for IP and port defeats
1083 * the purpose of having socket abstraction. Which "port"
1084 * are you using on Unix domain socket?
1085 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1088 char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
1089 char *cp = strrchr(p, ':');
1090 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1092 if (cp) *cp = '\0'; /* delete :PORT */
1093 setenv1("REMOTE_ADDR", p);
1096 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1097 setenv1("REMOTE_PORT", cp + 1);
1101 setenv1("HTTP_USER_AGENT", user_agent);
1103 putenv(xasprintf("CONTENT_LENGTH=%d", bodyLen));
1105 setenv1("HTTP_COOKIE", cookie);
1107 setenv1("CONTENT_TYPE", content_type);
1108 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1110 setenv1("REMOTE_USER", remoteuser);
1111 putenv((char*)"AUTH_TYPE=Basic");
1115 setenv1("HTTP_REFERER", referer);
1122 /* TODO: log perror? */
1128 xfunc_error_retval = 242;
1130 xmove_fd(toCgi.rd, 0); /* replace stdin with the pipe */
1131 xmove_fd(fromCgi.wr, 1); /* replace stdout with the pipe */
1134 /* User seeing stderr output can be a security problem.
1135 * If CGI really wants that, it can always do dup itself. */
1138 /* script must have absolute path */
1139 script = strrchr(fullpath, '/');
1141 goto error_execing_cgi;
1143 /* chdiring to script's dir */
1144 if (chdir(fullpath) == 0) {
1146 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1147 char *interpr = NULL;
1148 char *suffix = strrchr(purl, '.');
1152 for (cur = script_i; cur; cur = cur->next) {
1153 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1154 interpr = cur->after_colon;
1161 /* set argv[0] to name without path */
1162 argv[0] = (char*)bb_basename(purl);
1164 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1166 execv(interpr, argv);
1169 execv(fullpath, argv);
1173 * (we are CGI here, our stdout is pumped to the net) */
1174 send_headers_and_exit(HTTP_NOT_FOUND);
1177 /* Parent process */
1179 /* First, restore variables possibly changed by child */
1180 xfunc_error_retval = 0;
1182 /* Prepare for pumping data.
1183 * iobuf is used for CGI -> network data,
1184 * hdr_buf is for network -> CGI data (POSTDATA) */
1189 /* If CGI dies, we still want to correctly finish reading its output
1190 * and send it to the peer. So please no SIGPIPEs! */
1191 signal(SIGPIPE, SIG_IGN);
1193 /* This loop still looks messy. What is an exit criteria?
1194 * "CGI's output closed"? Or "CGI has exited"?
1195 * What to do if CGI has closed both input and output, but
1196 * didn't exit? etc... */
1198 /* NB: breaking out of this loop jumps to log_and_exit() */
1207 FD_SET(fromCgi.rd, &readSet);
1208 if (bodyLen > 0 || hdr_cnt > 0) {
1209 FD_SET(toCgi.wr, &writeSet);
1210 nfound = toCgi.wr > fromCgi.rd ? toCgi.wr : fromCgi.rd;
1212 FD_SET(0, &readSet);
1213 /* Now wait on the set of sockets! */
1214 nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1217 close(toCgi.wr); /* no more POST data to CGI */
1220 nfound = select(fromCgi.rd + 1, &readSet, NULL, NULL, NULL);
1224 if (waitpid(pid, &status, WNOHANG) <= 0) {
1225 /* Weird. CGI didn't exit and no fd's
1226 * are ready, yet select returned?! */
1230 if (DEBUG && WIFEXITED(status))
1231 bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
1232 if (DEBUG && WIFSIGNALED(status))
1233 bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
1237 if (hdr_cnt > 0 && FD_ISSET(toCgi.wr, &writeSet)) {
1238 /* Have data from peer and can write to CGI */
1239 count = safe_write(toCgi.wr, hdr_ptr, hdr_cnt);
1240 /* Doesn't happen, we dont use nonblocking IO here
1241 *if (count < 0 && errno == EAGAIN) {
1248 hdr_cnt = bodyLen = 0; /* EOF/broken pipe to CGI */
1250 } else if (bodyLen > 0 && hdr_cnt == 0
1251 && FD_ISSET(0, &readSet)
1253 /* We expect data, prev data portion is eaten by CGI
1254 * and there *is* data to read from the peer
1256 count = bodyLen > (int)sizeof(hdr_buf) ? (int)sizeof(hdr_buf) : bodyLen;
1257 count = safe_read(0, hdr_buf, count);
1263 bodyLen = 0; /* closed */
1267 #define PIPESIZE PIPE_BUF
1268 #if PIPESIZE >= IOBUF_SIZE
1269 # error "PIPESIZE >= IOBUF_SIZE"
1271 if (FD_ISSET(fromCgi.rd, &readSet)) {
1272 /* There is something to read from CGI */
1275 /* Are we still buffering CGI output? */
1276 if (buf_count >= 0) {
1277 /* HTTP_200[] has single "\r\n" at the end.
1278 * According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1279 * CGI scripts MUST send their own header terminated by
1280 * empty line, then data. That's why we have only one
1281 * <cr><lf> pair here. We will output "200 OK" line
1282 * if needed, but CGI still has to provide blank line
1283 * between header and body */
1285 /* Must use safe_read, not full_read, because
1286 * CGI may output a few first bytes and then wait
1287 * for POSTDATA without closing stdout.
1288 * With full_read we may wait here forever. */
1289 count = safe_read(fromCgi.rd, rbuf + buf_count, PIPESIZE - 8);
1291 /* eof (or error) and there was no "HTTP",
1292 * so write it, then write received data */
1294 full_write(1, HTTP_200, sizeof(HTTP_200)-1);
1295 full_write(1, rbuf, buf_count);
1297 break; /* CGI stdout is closed, exiting */
1301 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1302 if (buf_count >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1303 /* send "HTTP/1.0 " */
1304 if (full_write(1, HTTP_200, 9) != 9)
1306 rbuf += 8; /* skip "Status: " */
1307 count = buf_count - 8;
1308 buf_count = -1; /* buffering off */
1309 } else if (buf_count >= 4) {
1310 /* Did CGI add "HTTP"? */
1311 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1312 /* there is no "HTTP", do it ourself */
1313 if (full_write(1, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1317 if (!strstr(rbuf, "ontent-")) {
1318 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1320 * Counter-example of valid CGI without Content-type:
1321 * echo -en "HTTP/1.0 302 Found\r\n"
1322 * echo -en "Location: http://www.busybox.net\r\n"
1326 buf_count = -1; /* buffering off */
1329 count = safe_read(fromCgi.rd, rbuf, PIPESIZE);
1331 break; /* eof (or error) */
1333 if (full_write(1, rbuf, count) != count)
1336 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1337 } /* if (FD_ISSET(fromCgi.rd)) */
1341 #endif /* FEATURE_HTTPD_CGI */
1344 * Send a file response to a HTTP request, and exit
1347 * const char *url The requested URL (with leading /).
1348 * headers Don't send headers before if FALSE.
1350 static void send_file_and_exit(const char *url, int headers)
1352 static const char *const suffixTable[] = {
1353 /* Warning: shorter equivalent suffix in one line must be first */
1354 ".htm.html", "text/html",
1355 ".jpg.jpeg", "image/jpeg",
1356 ".gif", "image/gif",
1357 ".png", "image/png",
1358 ".txt.h.c.cc.cpp", "text/plain",
1360 ".wav", "audio/wav",
1361 ".avi", "video/x-msvideo",
1362 ".qt.mov", "video/quicktime",
1363 ".mpe.mpeg", "video/mpeg",
1364 ".mid.midi", "audio/midi",
1365 ".mp3", "audio/mpeg",
1366 #if 0 /* unpopular */
1367 ".au", "audio/basic",
1368 ".pac", "application/x-ns-proxy-autoconfig",
1369 ".vrml.wrl", "model/vrml",
1376 const char *const *table;
1377 const char *try_suffix;
1379 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1383 suffix = strrchr(url, '.');
1385 /* If not found, set default as "application/octet-stream"; */
1386 found_mime_type = "application/octet-stream";
1388 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1391 for (table = suffixTable; *table; table += 2) {
1392 try_suffix = strstr(table[0], suffix);
1394 try_suffix += strlen(suffix);
1395 if (*try_suffix == '\0' || *try_suffix == '.') {
1396 found_mime_type = table[1];
1401 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1402 for (cur = mime_a; cur; cur = cur->next) {
1403 if (strcmp(cur->before_colon, suffix) == 0) {
1404 found_mime_type = cur->after_colon;
1412 bb_error_msg("sending file '%s' content-type: %s",
1413 url, found_mime_type);
1415 f = open(url, O_RDONLY);
1418 bb_perror_msg("cannot open '%s'", url);
1420 send_headers_and_exit(HTTP_NOT_FOUND);
1424 send_headers(HTTP_OK);
1426 /* If you want to know about EPIPE below
1427 * (happens if you abort downloads from local httpd): */
1428 signal(SIGPIPE, SIG_IGN);
1430 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1432 /* byte count (3rd arg) is rounded down to 64k */
1433 count = sendfile(1, f, &offset, MAXINT(ssize_t) - 0xffff);
1439 } while (count > 0);
1444 while ((count = safe_read(f, iobuf, IOBUF_SIZE)) > 0) {
1446 count = full_write(1, iobuf, count);
1450 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1453 if (count < 0 && verbose > 1)
1454 bb_perror_msg("error");
1458 static int checkPermIP(void)
1462 /* This could stand some work */
1463 for (cur = ip_a_d; cur; cur = cur->next) {
1466 "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1468 (unsigned char)(cur->ip >> 24),
1469 (unsigned char)(cur->ip >> 16),
1470 (unsigned char)(cur->ip >> 8),
1471 (unsigned char)(cur->ip),
1472 (unsigned char)(cur->mask >> 24),
1473 (unsigned char)(cur->mask >> 16),
1474 (unsigned char)(cur->mask >> 8),
1475 (unsigned char)(cur->mask)
1478 if ((rmt_ip & cur->mask) == cur->ip)
1479 return cur->allow_deny == 'A'; /* Allow/Deny */
1482 /* if unconfigured, return 1 - access from all */
1483 return !flg_deny_all;
1486 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1488 * Check the permission file for access password protected.
1490 * If config file isn't present, everything is allowed.
1491 * Entries are of the form you can see example from header source
1493 * path The file path.
1494 * request User information to validate.
1496 * Returns 1 if request is OK.
1498 static int checkPerm(const char *path, const char *request)
1504 const char *prev = NULL;
1506 /* This could stand some work */
1507 for (cur = g_auth; cur; cur = cur->next) {
1510 p0 = cur->before_colon;
1511 if (prev != NULL && strcmp(prev, p0) != 0)
1512 continue; /* find next identical */
1513 p = cur->after_colon;
1515 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1518 if (strncmp(p0, path, l) == 0
1519 && (l == 1 || path[l] == '/' || path[l] == '\0')
1522 /* path match found. Check request */
1523 /* for check next /path:user:password */
1525 u = strchr(request, ':');
1527 /* bad request, ':' required */
1531 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1535 if (strncmp(p, request, u - request) != 0) {
1536 /* user doesn't match */
1539 pp = strchr(p, ':');
1540 if (pp && pp[1] == '$' && pp[2] == '1'
1541 && pp[3] == '$' && pp[4]
1544 cipher = pw_encrypt(u+1, pp);
1545 if (strcmp(cipher, pp) == 0)
1546 goto set_remoteuser_var; /* Ok */
1552 if (strcmp(p, request) == 0) {
1554 remoteuser = strdup(request);
1556 remoteuser[u - request] = '\0';
1563 return prev == NULL;
1565 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1570 static void exit_on_signal(int sig) ATTRIBUTE_NORETURN;
1571 static void exit_on_signal(int sig)
1573 send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
1577 * Handle an incoming http request and exit.
1579 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr) ATTRIBUTE_NORETURN;
1580 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
1582 static const char request_GET[] ALIGN1 = "GET";
1588 int http_major_version;
1590 #if ENABLE_FEATURE_HTTPD_CGI
1591 const char *prequest;
1592 unsigned long length = 0;
1594 char *content_type = 0;
1596 struct sigaction sa;
1597 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1598 int credentials = -1; /* if not required this is Ok */
1601 /* Allocation of iobuf is postponed until now
1602 * (IOW, server process doesn't need to waste 8k) */
1603 iobuf = xmalloc(IOBUF_SIZE);
1606 if (fromAddr->sa.sa_family == AF_INET) {
1607 rmt_ip = ntohl(fromAddr->sin.sin_addr.s_addr);
1609 if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1610 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr->sa);
1613 /* this trick makes -v logging much simpler */
1614 applet_name = rmt_ip_str;
1616 bb_error_msg("connected");
1619 /* Install timeout handler */
1620 memset(&sa, 0, sizeof(sa));
1621 sa.sa_handler = exit_on_signal;
1622 /* sigemptyset(&sa.sa_mask); - memset should be enough */
1623 /*sa.sa_flags = 0; - no SA_RESTART */
1624 sigaction(SIGALRM, &sa, NULL);
1625 alarm(HEADER_READ_TIMEOUT);
1627 if (!get_line()) /* EOF or error or empty line */
1628 send_headers_and_exit(HTTP_BAD_REQUEST);
1630 /* Determine type of request (GET/POST) */
1631 urlp = strpbrk(iobuf, " \t");
1633 send_headers_and_exit(HTTP_BAD_REQUEST);
1635 #if ENABLE_FEATURE_HTTPD_CGI
1636 prequest = request_GET;
1637 if (strcasecmp(iobuf, prequest) != 0) {
1639 if (strcasecmp(iobuf, prequest) != 0)
1640 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1643 if (strcasecmp(iobuf, request_GET) != 0)
1644 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1646 urlp = skip_whitespace(urlp);
1648 send_headers_and_exit(HTTP_BAD_REQUEST);
1650 /* Find end of URL and parse HTTP version, if any */
1651 http_major_version = -1;
1652 tptr = strchrnul(urlp, ' ');
1653 /* Is it " HTTP/"? */
1654 if (tptr[0] && strncmp(tptr + 1, HTTP_200, 5) == 0)
1655 http_major_version = (tptr[6] - '0');
1658 /* Copy URL from after "GET "/"POST " to stack-allocated char[] */
1659 urlcopy = alloca((tptr - urlp) + sizeof("/index.html"));
1660 /*if (urlcopy == NULL)
1661 * send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);*/
1662 strcpy(urlcopy, urlp);
1663 /* NB: urlcopy ptr is never changed after this */
1665 /* Extract url args if present */
1666 tptr = strchr(urlcopy, '?');
1673 /* Decode URL escape sequences */
1674 tptr = decodeString(urlcopy, 0);
1676 send_headers_and_exit(HTTP_BAD_REQUEST);
1677 if (tptr == urlcopy + 1) {
1678 /* '/' or NUL is encoded */
1679 send_headers_and_exit(HTTP_NOT_FOUND);
1682 /* Canonicalize path */
1683 /* Algorithm stolen from libbb bb_simplify_path(),
1684 * but don't strdup and reducing trailing slash and protect out root */
1685 urlp = tptr = urlcopy;
1688 /* skip duplicate (or initial) slash */
1693 /* skip extra '.' */
1694 if (tptr[1] == '/' || !tptr[1]) {
1697 /* '..': be careful */
1698 if (tptr[1] == '.' && (tptr[2] == '/' || !tptr[2])) {
1700 if (urlp == urlcopy) /* protect root */
1701 send_headers_and_exit(HTTP_BAD_REQUEST);
1702 while (*--urlp != '/') /* omit previous dir */;
1709 *++urlp = '\0'; /* so keep last character */
1710 tptr = urlp; /* end ptr */
1712 /* If URL is a directory, add '/' */
1713 if (tptr[-1] != '/') {
1714 if (is_directory(urlcopy + 1, 1, &sb)) {
1715 found_moved_temporarily = urlcopy;
1721 bb_error_msg("url:%s", urlcopy);
1724 ip_allowed = checkPermIP();
1725 while (ip_allowed && (tptr = strchr(tptr + 1, '/')) != NULL) {
1726 /* have path1/path2 */
1728 if (is_directory(urlcopy + 1, 1, &sb)) {
1729 /* may be having subdir config */
1730 parse_conf(urlcopy + 1, SUBDIR_PARSE);
1731 ip_allowed = checkPermIP();
1735 if (http_major_version >= 0) {
1736 /* Request was with "... HTTP/nXXX", and n >= 0 */
1738 /* Read until blank line for HTTP version specified, else parse immediate */
1740 alarm(HEADER_READ_TIMEOUT);
1742 break; /* EOF or error or empty line */
1744 bb_error_msg("header: '%s'", iobuf);
1746 #if ENABLE_FEATURE_HTTPD_CGI
1747 /* try and do our best to parse more lines */
1748 if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
1749 /* extra read only for POST */
1750 if (prequest != request_GET) {
1751 tptr = iobuf + sizeof("Content-length:") - 1;
1753 send_headers_and_exit(HTTP_BAD_REQUEST);
1755 /* not using strtoul: it ignores leading minus! */
1756 length = strtol(tptr, &tptr, 10);
1757 /* length is "ulong", but we need to pass it to int later */
1758 /* so we check for negative or too large values in one go: */
1759 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1760 if (tptr[0] || errno || length > INT_MAX)
1761 send_headers_and_exit(HTTP_BAD_REQUEST);
1763 } else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
1764 cookie = strdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
1765 } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
1766 content_type = strdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
1767 } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
1768 referer = strdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
1769 } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
1770 user_agent = strdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
1773 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1774 if (STRNCASECMP(iobuf, "Authorization:") == 0) {
1775 /* We only allow Basic credentials.
1776 * It shows up as "Authorization: Basic <userid:password>" where
1777 * the userid:password is base64 encoded.
1779 tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
1780 if (STRNCASECMP(tptr, "Basic") != 0)
1782 tptr += sizeof("Basic")-1;
1783 /* decodeBase64() skips whitespace itself */
1785 credentials = checkPerm(urlcopy, tptr);
1787 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1788 } /* while extra header reading */
1791 /* We read headers, disable peer timeout */
1794 if (strcmp(bb_basename(urlcopy), httpd_conf) == 0 || ip_allowed == 0) {
1795 /* protect listing [/path]/httpd_conf or IP deny */
1796 send_headers_and_exit(HTTP_FORBIDDEN);
1799 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1800 if (credentials <= 0 && checkPerm(urlcopy, ":") == 0) {
1801 send_headers_and_exit(HTTP_UNAUTHORIZED);
1805 if (found_moved_temporarily) {
1806 send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
1809 tptr = urlcopy + 1; /* skip first '/' */
1811 #if ENABLE_FEATURE_HTTPD_CGI
1812 if (strncmp(tptr, "cgi-bin/", 8) == 0) {
1813 if (tptr[8] == '\0') {
1814 /* protect listing "cgi-bin/" */
1815 send_headers_and_exit(HTTP_FORBIDDEN);
1817 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1819 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1821 char *suffix = strrchr(tptr, '.');
1824 for (cur = script_i; cur; cur = cur->next) {
1825 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1826 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1832 if (prequest != request_GET) {
1833 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1835 #endif /* FEATURE_HTTPD_CGI */
1837 if (urlp[-1] == '/')
1838 strcpy(urlp, "index.html");
1839 if (stat(tptr, &sb) == 0) {
1840 /* It's a dir URL and there is index.html */
1841 ContentLength = sb.st_size;
1842 last_mod = sb.st_mtime;
1844 #if ENABLE_FEATURE_HTTPD_CGI
1845 else if (urlp[-1] == '/') {
1846 /* It's a dir URL and there is no index.html
1847 * Try cgi-bin/index.cgi */
1848 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1851 send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1856 * fall through to send_file, it errors out if open fails
1860 send_file_and_exit(tptr, TRUE);
1864 * The main http server function.
1865 * Given a socket, listen for new connections and farm out
1866 * the processing as a [v]forked process.
1870 static void mini_httpd(int server_socket) ATTRIBUTE_NORETURN;
1871 static void mini_httpd(int server_socket)
1873 /* NB: it's best to not use xfuncs in this loop before fork().
1874 * Otherwise server may die on transient errors (temporary
1875 * out-of-memory condition, etc), which is Bad(tm).
1876 * Try to do any dangerous calls after fork.
1880 len_and_sockaddr fromAddr;
1882 /* Wait for connections... */
1883 fromAddr.len = LSA_SIZEOF_SA;
1884 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1888 /* set the KEEPALIVE option to cull dead connections */
1889 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1893 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1894 /* Do not reload config on HUP */
1895 signal(SIGHUP, SIG_IGN);
1897 close(server_socket);
1901 handle_incoming_and_exit(&fromAddr);
1903 /* parent, or fork failed */
1909 static void mini_httpd_nommu(int server_socket, int argc, char **argv) ATTRIBUTE_NORETURN;
1910 static void mini_httpd_nommu(int server_socket, int argc, char **argv)
1912 char *argv_copy[argc + 2];
1914 argv_copy[0] = argv[0];
1915 argv_copy[1] = (char*)"-i";
1916 memcpy(&argv_copy[2], &argv[1], argc * sizeof(argv[0]));
1918 /* NB: it's best to not use xfuncs in this loop before vfork().
1919 * Otherwise server may die on transient errors (temporary
1920 * out-of-memory condition, etc), which is Bad(tm).
1921 * Try to do any dangerous calls after fork.
1925 len_and_sockaddr fromAddr;
1927 /* Wait for connections... */
1928 fromAddr.len = LSA_SIZEOF_SA;
1929 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1933 /* set the KEEPALIVE option to cull dead connections */
1934 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1938 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1939 /* Do not reload config on HUP */
1940 signal(SIGHUP, SIG_IGN);
1942 close(server_socket);
1946 /* Run a copy of ourself in inetd mode */
1949 /* parent, or vfork failed */
1957 * Process a HTTP connection on stdin/out.
1960 static void mini_httpd_inetd(void) ATTRIBUTE_NORETURN;
1961 static void mini_httpd_inetd(void)
1963 len_and_sockaddr fromAddr;
1965 fromAddr.len = LSA_SIZEOF_SA;
1966 getpeername(0, &fromAddr.sa, &fromAddr.len);
1967 handle_incoming_and_exit(&fromAddr);
1970 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1971 static void sighup_handler(int sig)
1973 struct sigaction sa;
1975 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1977 memset(&sa, 0, sizeof(sa));
1978 sa.sa_handler = sighup_handler;
1979 /*sigemptyset(&sa.sa_mask); - memset should be enough */
1980 sa.sa_flags = SA_RESTART;
1981 sigaction(SIGHUP, &sa, NULL);
1986 c_opt_config_file = 0,
1989 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1990 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1991 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1992 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1997 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1998 OPT_DECODE_URL = 1 << d_opt_decode_url,
1999 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
2000 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
2001 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
2002 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
2003 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
2004 OPT_PORT = 1 << p_opt_port,
2005 OPT_INETD = 1 << p_opt_inetd,
2006 OPT_FOREGROUND = 1 << p_opt_foreground,
2007 OPT_VERBOSE = 1 << p_opt_verbose,
2011 int httpd_main(int argc, char **argv);
2012 int httpd_main(int argc, char **argv)
2014 int server_socket = server_socket; /* for gcc */
2016 char *url_for_decode;
2017 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
2018 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
2019 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
2020 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
2024 #if ENABLE_LOCALE_SUPPORT
2025 /* Undo busybox.c: we want to speak English in http (dates etc) */
2026 setlocale(LC_TIME, "C");
2029 home_httpd = xrealloc_getcwd_or_warn(NULL);
2030 /* -v counts, -i implies -f */
2031 opt_complementary = "vv:if";
2032 /* We do not "absolutize" path given by -h (home) opt.
2033 * If user gives relative path in -h, $SCRIPT_FILENAME can end up
2035 opt = getopt32(argv, "c:d:h:"
2036 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
2037 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
2038 USE_FEATURE_HTTPD_AUTH_MD5("m:")
2039 USE_FEATURE_HTTPD_SETUID("u:")
2041 &configFile, &url_for_decode, &home_httpd
2042 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
2043 USE_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
2044 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
2045 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
2046 , &bind_addr_or_port
2049 if (opt & OPT_DECODE_URL) {
2050 fputs(decodeString(url_for_decode, 1), stdout);
2053 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
2054 if (opt & OPT_ENCODE_URL) {
2055 fputs(encodeString(url_for_encode), stdout);
2059 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
2060 if (opt & OPT_MD5) {
2061 puts(pw_encrypt(pass, "$1$"));
2065 #if ENABLE_FEATURE_HTTPD_SETUID
2066 if (opt & OPT_SETUID) {
2067 if (!get_uidgid(&ugid, s_ugid, 1))
2068 bb_error_msg_and_die("unrecognized user[:group] "
2069 "name '%s'", s_ugid);
2074 if (!(opt & OPT_FOREGROUND)) {
2075 bb_daemonize_or_rexec(0, argv); /* don't change current directory */
2080 if (!(opt & OPT_INETD)) {
2081 signal(SIGCHLD, SIG_IGN);
2082 server_socket = openServer();
2083 #if ENABLE_FEATURE_HTTPD_SETUID
2084 /* drop privileges */
2085 if (opt & OPT_SETUID) {
2086 if (ugid.gid != (gid_t)-1) {
2087 if (setgroups(1, &ugid.gid) == -1)
2088 bb_perror_msg_and_die("setgroups");
2096 #if ENABLE_FEATURE_HTTPD_CGI
2098 char *p = getenv("PATH");
2099 /* env strings themself are not freed, no need to strdup(p): */
2103 // if (!(opt & OPT_INETD))
2104 // setenv_long("SERVER_PORT", ???);
2108 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2109 if (!(opt & OPT_INETD))
2111 else /* do not install HUP handler in inetd mode */
2113 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2115 xfunc_error_retval = 0;
2116 if (opt & OPT_INETD)
2119 if (!(opt & OPT_FOREGROUND))
2120 bb_daemonize(0); /* don't change current directory */
2121 mini_httpd(server_socket); /* never returns */
2123 mini_httpd_nommu(server_socket, argc, argv); /* never returns */