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 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
10 *****************************************************************************
14 * httpd -p 8080 -h $HOME/public_html
15 * For daemon start from rc script with uid=0:
17 * which is equivalent to (assuming user www has uid 80):
18 * httpd -p 80 -u 80 -h $PWD -c /etc/httpd.conf -r "Web Server Authentication"
20 * When an url starts with "/cgi-bin/" it is assumed to be a cgi script.
21 * The server changes directory to the location of the script and executes it
22 * after setting QUERY_STRING and other environment variables.
24 * If directory URL is given, no index.html is found and CGI support is enabled,
25 * cgi-bin/index.cgi will be run. Directory to list is ../$QUERY_STRING.
26 * See httpd_indexcgi.c for an example GCI code.
29 * "CGI Environment Variables": http://hoohoo.ncsa.uiuc.edu/cgi/env.html
31 * The applet can also be invoked as an url arg decoder and html text encoder
33 * foo=`httpd -d $foo` # decode "Hello%20World" as "Hello World"
34 * bar=`httpd -e "<Hello World>"` # encode as "<Hello World>"
35 * Note that url encoding for arguments is not the same as html encoding for
36 * presentation. -d decodes an url-encoded argument while -e encodes in html
39 * httpd.conf has the following format:
41 * H:/serverroot # define the server root. It will override -h
42 * A:172.20. # Allow address from 172.20.0.0/16
43 * A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
44 * A:10.0.0.0/255.255.255.128 # Allow any address that previous set
45 * A:127.0.0.1 # Allow local loopback connections
46 * D:* # Deny from other IP connections
47 * E404:/path/e404.html # /path/e404.html is the 404 (not found) error page
48 * I:index.html # Show index.html when a directory is requested
50 * P:/url:[http://]hostname[:port]/new/path
51 * # When /urlXXXXXX is requested, reverse proxy
52 * # it to http://hostname[:port]/new/pathXXXXXX
54 * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
55 * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
56 * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
57 * .au:audio/basic # additional mime type for audio.au files
58 * *.php:/path/php # run xxx.php through an interpreter
60 * A/D may be as a/d or allow/deny - only first char matters.
61 * Deny/Allow IP logic:
62 * - Default is to allow all (Allow all (A:*) is a no-op).
63 * - Deny rules take precedence over allow rules.
64 * - "Deny all" rule (D:*) is applied last.
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 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.
98 /* TODO: use TCP_CORK, parse_config() */
101 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
102 # include <sys/sendfile.h>
104 /* amount of buffering in a pipe */
106 # define PIPE_BUF 4096
111 #define IOBUF_SIZE 8192
112 #if PIPE_BUF >= IOBUF_SIZE
113 # error "PIPE_BUF >= IOBUF_SIZE"
116 #define HEADER_READ_TIMEOUT 60
118 static const char DEFAULT_PATH_HTTPD_CONF[] ALIGN1 = "/etc";
119 static const char HTTPD_CONF[] ALIGN1 = "httpd.conf";
120 static const char HTTP_200[] ALIGN1 = "HTTP/1.0 200 OK\r\n";
121 static const char index_html[] ALIGN1 = "index.html";
123 typedef struct has_next_ptr {
124 struct has_next_ptr *next;
127 /* Must have "next" as a first member */
128 typedef struct Htaccess {
129 struct Htaccess *next;
131 char before_colon[1]; /* really bigger, must be last */
134 /* Must have "next" as a first member */
135 typedef struct Htaccess_IP {
136 struct Htaccess_IP *next;
142 /* Must have "next" as a first member */
143 typedef struct Htaccess_Proxy {
144 struct Htaccess_Proxy *next;
152 HTTP_PARTIAL_CONTENT = 206,
153 HTTP_MOVED_TEMPORARILY = 302,
154 HTTP_BAD_REQUEST = 400, /* malformed syntax */
155 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
156 HTTP_NOT_FOUND = 404,
157 HTTP_FORBIDDEN = 403,
158 HTTP_REQUEST_TIMEOUT = 408,
159 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
160 HTTP_INTERNAL_SERVER_ERROR = 500,
162 #if 0 /* future use */
163 HTTP_SWITCHING_PROTOCOLS = 101,
166 HTTP_NON_AUTHORITATIVE_INFO = 203,
167 HTTP_NO_CONTENT = 204,
168 HTTP_MULTIPLE_CHOICES = 300,
169 HTTP_MOVED_PERMANENTLY = 301,
170 HTTP_NOT_MODIFIED = 304,
171 HTTP_PAYMENT_REQUIRED = 402,
172 HTTP_BAD_GATEWAY = 502,
173 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
177 static const uint16_t http_response_type[] ALIGN2 = {
179 #if ENABLE_FEATURE_HTTPD_RANGES
180 HTTP_PARTIAL_CONTENT,
182 HTTP_MOVED_TEMPORARILY,
183 HTTP_REQUEST_TIMEOUT,
184 HTTP_NOT_IMPLEMENTED,
185 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
191 HTTP_INTERNAL_SERVER_ERROR,
192 #if 0 /* not implemented */
196 HTTP_MULTIPLE_CHOICES,
197 HTTP_MOVED_PERMANENTLY,
200 HTTP_SERVICE_UNAVAILABLE,
204 static const struct {
207 } http_response[ARRAY_SIZE(http_response_type)] = {
209 #if ENABLE_FEATURE_HTTPD_RANGES
210 { "Partial Content", NULL },
213 { "Request Timeout", "No request appeared within 60 seconds" },
214 { "Not Implemented", "The requested method is not recognized" },
215 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
216 { "Unauthorized", "" },
218 { "Not Found", "The requested URL was not found" },
219 { "Bad Request", "Unsupported method" },
221 { "Internal Server Error", "Internal Server Error" },
222 #if 0 /* not implemented */
226 { "Multiple Choices" },
227 { "Moved Permanently" },
229 { "Bad Gateway", "" },
230 { "Service Unavailable", "" },
235 int verbose; /* must be int (used by getopt32) */
236 smallint flg_deny_all;
238 unsigned rmt_ip; /* used for IP-based allow/deny rules */
240 char *rmt_ip_str; /* for $REMOTE_ADDR and $REMOTE_PORT */
241 const char *bind_addr_or_port;
244 const char *opt_c_configFile;
245 const char *home_httpd;
246 const char *index_page;
248 const char *found_mime_type;
249 const char *found_moved_temporarily;
250 Htaccess_IP *ip_a_d; /* config allow/deny lines */
252 IF_FEATURE_HTTPD_BASIC_AUTH(const char *g_realm;)
253 IF_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
254 IF_FEATURE_HTTPD_CGI(char *referer;)
255 IF_FEATURE_HTTPD_CGI(char *user_agent;)
256 IF_FEATURE_HTTPD_CGI(char *host;)
257 IF_FEATURE_HTTPD_CGI(char *http_accept;)
258 IF_FEATURE_HTTPD_CGI(char *http_accept_language;)
260 off_t file_size; /* -1 - unknown */
261 #if ENABLE_FEATURE_HTTPD_RANGES
267 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
268 Htaccess *g_auth; /* config user:password lines */
270 Htaccess *mime_a; /* config mime types */
271 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
272 Htaccess *script_i; /* config script interpreters */
274 char *iobuf; /* [IOBUF_SIZE] */
275 #define hdr_buf bb_common_bufsiz1
278 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
279 const char *http_error_page[ARRAY_SIZE(http_response_type)];
281 #if ENABLE_FEATURE_HTTPD_PROXY
282 Htaccess_Proxy *proxy;
284 #if ENABLE_FEATURE_HTTPD_GZIP
285 /* client can handle gzip / we are going to send gzip */
286 smallint content_gzip;
289 #define G (*ptr_to_globals)
290 #define verbose (G.verbose )
291 #define flg_deny_all (G.flg_deny_all )
292 #define rmt_ip (G.rmt_ip )
293 #define bind_addr_or_port (G.bind_addr_or_port)
294 #define g_query (G.g_query )
295 #define opt_c_configFile (G.opt_c_configFile )
296 #define home_httpd (G.home_httpd )
297 #define index_page (G.index_page )
298 #define found_mime_type (G.found_mime_type )
299 #define found_moved_temporarily (G.found_moved_temporarily)
300 #define last_mod (G.last_mod )
301 #define ip_a_d (G.ip_a_d )
302 #define g_realm (G.g_realm )
303 #define remoteuser (G.remoteuser )
304 #define referer (G.referer )
305 #define user_agent (G.user_agent )
306 #define host (G.host )
307 #define http_accept (G.http_accept )
308 #define http_accept_language (G.http_accept_language)
309 #define file_size (G.file_size )
310 #if ENABLE_FEATURE_HTTPD_RANGES
311 #define range_start (G.range_start )
312 #define range_end (G.range_end )
313 #define range_len (G.range_len )
317 range_end = MAXINT(off_t) - 1,
318 range_len = MAXINT(off_t),
321 #define rmt_ip_str (G.rmt_ip_str )
322 #define g_auth (G.g_auth )
323 #define mime_a (G.mime_a )
324 #define script_i (G.script_i )
325 #define iobuf (G.iobuf )
326 #define hdr_ptr (G.hdr_ptr )
327 #define hdr_cnt (G.hdr_cnt )
328 #define http_error_page (G.http_error_page )
329 #define proxy (G.proxy )
330 #if ENABLE_FEATURE_HTTPD_GZIP
331 # define content_gzip (G.content_gzip )
333 # define content_gzip 0
335 #define INIT_G() do { \
336 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
337 IF_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
338 bind_addr_or_port = "80"; \
339 index_page = index_html; \
344 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
348 SEND_HEADERS = (1 << 0),
349 SEND_BODY = (1 << 1),
350 SEND_HEADERS_AND_BODY = SEND_HEADERS + SEND_BODY,
352 static void send_file_and_exit(const char *url, int what) NORETURN;
354 static void free_llist(has_next_ptr **pptr)
356 has_next_ptr *cur = *pptr;
358 has_next_ptr *t = cur;
365 static ALWAYS_INLINE void free_Htaccess_list(Htaccess **pptr)
367 free_llist((has_next_ptr**)pptr);
370 static ALWAYS_INLINE void free_Htaccess_IP_list(Htaccess_IP **pptr)
372 free_llist((has_next_ptr**)pptr);
375 /* Returns presumed mask width in bits or < 0 on error.
376 * Updates strp, stores IP at provided pointer */
377 static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
379 const char *p = *strp;
387 for (j = 0; j < 4; j++) {
390 if ((*p < '0' || *p > '9') && *p != '/' && *p)
393 while (*p >= '0' && *p <= '9') {
404 ip = (ip << 8) | octet;
418 /* Returns 0 on success. Stores IP and mask at provided pointers */
419 static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
425 i = scan_ip(&str, ipp, '/');
430 /* there is /xxx after dotted-IP address */
431 i = bb_strtou(str, &p, 10);
433 /* 'xxx' itself is dotted-IP mask, parse it */
434 /* (return 0 (success) only if it has N.N.N.N form) */
435 return scan_ip(&str, maskp, '\0') - 32;
444 if (sizeof(unsigned) == 4 && i == 32) {
445 /* mask >>= 32 below may not work */
451 /* i == 0 -> *maskp = 0x00000000
452 * i == 1 -> *maskp = 0x80000000
453 * i == 4 -> *maskp = 0xf0000000
454 * i == 31 -> *maskp = 0xfffffffe
455 * i == 32 -> *maskp = 0xffffffff */
456 *maskp = (uint32_t)(~mask);
461 * Parse configuration file into in-memory linked list.
463 * Any previous IP rules are discarded.
464 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
465 * are also discarded. That is, previous settings are retained if flag is
467 * Error pages are only parsed on the main config file.
469 * path Path where to look for httpd.conf (without filename).
470 * flag Type of the parse request.
474 FIRST_PARSE = 0, /* path will be "/etc" */
475 SIGNALED_PARSE = 1, /* path will be "/etc" */
476 SUBDIR_PARSE = 2, /* path will be derived from URL */
478 static void parse_conf(const char *path, int flag)
480 /* internally used extra flag state */
481 enum { TRY_CURDIR_PARSE = 3 };
484 const char *filename;
487 /* discard old rules */
488 free_Htaccess_IP_list(&ip_a_d);
490 /* retain previous auth and mime config only for subdir parse */
491 if (flag != SUBDIR_PARSE) {
492 free_Htaccess_list(&mime_a);
493 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
494 free_Htaccess_list(&g_auth);
496 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
497 free_Htaccess_list(&script_i);
501 filename = opt_c_configFile;
502 if (flag == SUBDIR_PARSE || filename == NULL) {
503 filename = alloca(strlen(path) + sizeof(HTTPD_CONF) + 2);
504 sprintf((char *)filename, "%s/%s", path, HTTPD_CONF);
507 while ((f = fopen_for_read(filename)) == NULL) {
508 if (flag >= SUBDIR_PARSE) { /* SUBDIR or TRY_CURDIR */
509 /* config file not found, no changes to config */
512 if (flag == FIRST_PARSE) {
513 /* -c CONFFILE given, but CONFFILE doesn't exist? */
514 if (opt_c_configFile)
515 bb_simple_perror_msg_and_die(opt_c_configFile);
516 /* else: no -c, thus we looked at /etc/httpd.conf,
517 * and it's not there. try ./httpd.conf: */
519 flag = TRY_CURDIR_PARSE;
520 filename = HTTPD_CONF;
523 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
524 /* in "/file:user:pass" lines, we prepend path in subdirs */
525 if (flag != SUBDIR_PARSE)
530 * I:default_index_file
532 * [AD]:IP[/mask] # allow/deny, * for wildcard
533 * Ennn:error.html # error page for status nnn
534 * P:/url:[http://]hostname[:port]/new/path # reverse proxy
535 * .ext:mime/type # mime type
536 * *.php:/path/php # run xxx.php through an interpreter
537 * /file:user:pass # username and password
539 while (fgets(buf, sizeof(buf), f) != NULL) {
544 { /* remove all whitespace, and # comments */
548 /* skip non-whitespace beginning. Often the whole line
549 * is non-whitespace. We want this case to work fast,
550 * without needless copying, therefore we don't merge
551 * this operation into next while loop. */
552 while ((ch = *p0) != '\0' && ch != '\n' && ch != '#'
553 && ch != ' ' && ch != '\t'
558 /* if we enter this loop, we have some whitespace.
560 while (ch != '\0' && ch != '\n' && ch != '#') {
561 if (ch != ' ' && ch != '\t') {
567 strlen_buf = p - buf;
569 continue; /* empty line */
572 after_colon = strchr(buf, ':');
574 if (after_colon == NULL || *++after_colon == '\0')
577 ch = (buf[0] & ~0x20); /* toupper if it's a letter */
580 if (index_page != index_html)
581 free((char*)index_page);
582 index_page = xstrdup(after_colon);
586 /* do not allow jumping around using H in subdir's configs */
587 if (flag == FIRST_PARSE && ch == 'H') {
588 home_httpd = xstrdup(after_colon);
593 if (ch == 'A' || ch == 'D') {
596 if (*after_colon == '*') {
598 /* memorize "deny all" */
601 /* skip assumed "A:*", it is a default anyway */
604 /* store "allow/deny IP/mask" line */
605 pip = xzalloc(sizeof(*pip));
606 if (scan_ip_mask(after_colon, &pip->ip, &pip->mask)) {
607 /* IP{/mask} syntax error detected, protect all */
611 pip->allow_deny = ch;
613 /* Deny:from_IP - prepend */
617 /* A:from_IP - append (thus all D's precedes A's) */
618 Htaccess_IP *prev_IP = ip_a_d;
619 if (prev_IP == NULL) {
622 while (prev_IP->next)
623 prev_IP = prev_IP->next;
630 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
631 if (flag == FIRST_PARSE && ch == 'E') {
633 int status = atoi(buf + 1); /* error status code */
635 if (status < HTTP_CONTINUE) {
638 /* then error page; find matching status */
639 for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
640 if (http_response_type[i] == status) {
641 /* We chdir to home_httpd, thus no need to
642 * concat_path_file(home_httpd, after_colon)
644 http_error_page[i] = xstrdup(after_colon);
652 #if ENABLE_FEATURE_HTTPD_PROXY
653 if (flag == FIRST_PARSE && ch == 'P') {
654 /* P:/url:[http://]hostname[:port]/new/path */
655 char *url_from, *host_port, *url_to;
656 Htaccess_Proxy *proxy_entry;
658 url_from = after_colon;
659 host_port = strchr(after_colon, ':');
660 if (host_port == NULL) {
664 if (strncmp(host_port, "http://", 7) == 0)
666 if (*host_port == '\0') {
669 url_to = strchr(host_port, '/');
670 if (url_to == NULL) {
674 proxy_entry = xzalloc(sizeof(*proxy_entry));
675 proxy_entry->url_from = xstrdup(url_from);
676 proxy_entry->host_port = xstrdup(host_port);
678 proxy_entry->url_to = xstrdup(url_to);
679 proxy_entry->next = proxy;
684 /* the rest of directives are non-alphabetic,
685 * must avoid using "toupper'ed" ch */
688 if (ch == '.' /* ".ext:mime/type" */
689 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
690 || (ch == '*' && buf[1] == '.') /* "*.php:/path/php" */
696 cur = xzalloc(sizeof(*cur) /* includes space for NUL */ + strlen_buf);
697 strcpy(cur->before_colon, buf);
698 p = cur->before_colon + (after_colon - buf);
700 cur->after_colon = p;
702 /* .mime line: prepend to mime_a list */
706 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
708 /* script interpreter line: prepend to script_i list */
709 cur->next = script_i;
716 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
717 if (ch == '/') { /* "/file:user:pass" */
722 /* note: path is "" unless we are in SUBDIR parse,
723 * otherwise it does NOT start with "/" */
724 cur = xzalloc(sizeof(*cur) /* includes space for NUL */
728 /* form "/path/file" */
729 sprintf(cur->before_colon, "/%s%.*s",
731 (int) (after_colon - buf - 1), /* includes "/", but not ":" */
733 /* canonicalize it */
734 p = bb_simplify_abs_path_inplace(cur->before_colon);
735 file_len = p - cur->before_colon;
736 /* add "user:pass" after NUL */
737 strcpy(++p, after_colon);
738 cur->after_colon = p;
740 /* insert cur into g_auth */
741 /* g_auth is sorted by decreased filename length */
743 Htaccess *auth, **authp;
746 while ((auth = *authp) != NULL) {
747 if (file_len >= strlen(auth->before_colon)) {
748 /* insert cur before auth */
758 #endif /* BASIC_AUTH */
760 /* the line is not recognized */
762 bb_error_msg("config error '%s' in '%s'", buf, filename);
763 } /* while (fgets) */
768 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
770 * Given a string, html-encode special characters.
771 * This is used for the -e command line option to provide an easy way
772 * for scripts to encode result data without confusing browsers. The
773 * returned string pointer is memory allocated by malloc().
775 * Returns a pointer to the encoded string (malloced).
777 static char *encodeString(const char *string)
779 /* take the simple route and encode everything */
780 /* could possibly scan once to get length. */
781 int len = strlen(string);
782 char *out = xmalloc(len * 6 + 1);
786 while ((ch = *string++) != '\0') {
787 /* very simple check for what to encode */
791 p += sprintf(p, "&#%d;", (unsigned char) ch);
799 * Given a URL encoded string, convert it to plain ascii.
800 * Since decoding always makes strings smaller, the decode is done in-place.
801 * Thus, callers should xstrdup() the argument if they do not want the
802 * argument modified. The return is the original pointer, allowing this
803 * function to be easily used as arguments to other functions.
805 * string The first string to decode.
806 * option_d 1 if called for httpd -d
808 * Returns a pointer to the decoded string (same as input).
810 static unsigned hex_to_bin(unsigned char c)
817 /* c | 0x20: letters to lower case, non-letters
818 * to (potentially different) non-letters */
819 v = (unsigned)(c | 0x20) - 'a';
824 void t(char c) { printf("'%c'(%u) %u\n", c, c, hex_to_bin(c)); }
825 int main() { t(0x10); t(0x20); t('0'); t('9'); t('A'); t('F'); t('a'); t('f');
826 t('0'-1); t('9'+1); t('A'-1); t('F'+1); t('a'-1); t('f'+1); return 0; }
829 static char *decodeString(char *orig, int option_d)
831 /* note that decoded string is always shorter than original */
836 while ((c = *ptr++) != '\0') {
839 if (option_d && c == '+') {
847 v = hex_to_bin(ptr[0]);
855 v = (v * 16) | hex_to_bin(ptr[1]);
858 if (!option_d && (v == '/' || v == '\0')) {
859 /* caller takes it as indication of invalid
860 * (dangerous wrt exploits) chars */
870 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
872 * Decode a base64 data stream as per rfc1521.
873 * Note that the rfc states that non base64 chars are to be ignored.
874 * Since the decode always results in a shorter size than the input,
875 * it is OK to pass the input arg as an output arg.
876 * Parameter: a pointer to a base64 encoded string.
877 * Decoded data is stored in-place.
879 static void decodeBase64(char *Data)
881 const unsigned char *in = (const unsigned char *)Data;
882 /* The decoded size will be at most 3/4 the size of the encoded */
889 if (t >= '0' && t <= '9')
891 else if (t >= 'A' && t <= 'Z')
893 else if (t >= 'a' && t <= 'z')
907 *Data++ = (char) (ch >> 16);
908 *Data++ = (char) (ch >> 8);
918 * Create a listen server socket on the designated port.
920 static int openServer(void)
922 unsigned n = bb_strtou(bind_addr_or_port, NULL, 10);
923 if (!errno && n && n <= 0xffff)
924 n = create_and_bind_stream_or_die(NULL, n);
926 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
932 * Log the connection closure and exit.
934 static void log_and_exit(void) NORETURN;
935 static void log_and_exit(void)
937 /* Paranoia. IE said to be buggy. It may send some extra data
938 * or be confused by us just exiting without SHUT_WR. Oh well. */
939 shutdown(1, SHUT_WR);
941 (this also messes up stdin when user runs httpd -i from terminal)
943 while (read(STDIN_FILENO, iobuf, IOBUF_SIZE) > 0)
948 bb_error_msg("closed");
949 _exit(xfunc_error_retval);
953 * Create and send HTTP response headers.
954 * The arguments are combined and sent as one write operation. Note that
955 * IE will puke big-time if the headers are not sent in one packet and the
956 * second packet is delayed for any reason.
957 * responseNum - the result code to send.
959 static void send_headers(int responseNum)
961 static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
963 const char *responseString = "";
964 const char *infoString = NULL;
965 const char *mime_type;
966 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
967 const char *error_page = NULL;
970 time_t timer = time(NULL);
974 for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
975 if (http_response_type[i] == responseNum) {
976 responseString = http_response[i].name;
977 infoString = http_response[i].info;
978 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
979 error_page = http_error_page[i];
984 /* error message is HTML */
985 mime_type = responseNum == HTTP_OK ?
986 found_mime_type : "text/html";
989 bb_error_msg("response:%u", responseNum);
991 /* emit the current date */
992 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
994 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
995 "Date: %s\r\nConnection: close\r\n",
996 responseNum, responseString, mime_type, tmp_str);
998 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
999 if (responseNum == HTTP_UNAUTHORIZED) {
1000 len += sprintf(iobuf + len,
1001 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
1005 if (responseNum == HTTP_MOVED_TEMPORARILY) {
1006 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
1007 found_moved_temporarily,
1008 (g_query ? "?" : ""),
1009 (g_query ? g_query : ""));
1012 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
1013 if (error_page && access(error_page, R_OK) == 0) {
1014 strcat(iobuf, "\r\n");
1018 fprintf(stderr, "headers: '%s'\n", iobuf);
1019 full_write(STDOUT_FILENO, iobuf, len);
1021 fprintf(stderr, "writing error page: '%s'\n", error_page);
1022 return send_file_and_exit(error_page, SEND_BODY);
1026 if (file_size != -1) { /* file */
1027 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
1028 #if ENABLE_FEATURE_HTTPD_RANGES
1029 if (responseNum == HTTP_PARTIAL_CONTENT) {
1030 len += sprintf(iobuf + len, "Content-Range: bytes %"OFF_FMT"u-%"OFF_FMT"u/%"OFF_FMT"u\r\n",
1034 file_size = range_end - range_start + 1;
1037 len += sprintf(iobuf + len,
1038 #if ENABLE_FEATURE_HTTPD_RANGES
1039 "Accept-Ranges: bytes\r\n"
1041 "Last-Modified: %s\r\n%s %"OFF_FMT"u\r\n",
1043 content_gzip ? "Transfer-length:" : "Content-length:",
1049 len += sprintf(iobuf + len, "Content-Encoding: gzip\r\n");
1051 iobuf[len++] = '\r';
1052 iobuf[len++] = '\n';
1054 len += sprintf(iobuf + len,
1055 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
1056 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
1057 responseNum, responseString,
1058 responseNum, responseString, infoString);
1061 fprintf(stderr, "headers: '%s'\n", iobuf);
1062 if (full_write(STDOUT_FILENO, iobuf, len) != len) {
1064 bb_perror_msg("error");
1069 static void send_headers_and_exit(int responseNum) NORETURN;
1070 static void send_headers_and_exit(int responseNum)
1072 IF_FEATURE_HTTPD_GZIP(content_gzip = 0;)
1073 send_headers(responseNum);
1078 * Read from the socket until '\n' or EOF. '\r' chars are removed.
1079 * '\n' is replaced with NUL.
1080 * Return number of characters read or 0 if nothing is read
1081 * ('\r' and '\n' are not counted).
1082 * Data is returned in iobuf.
1084 static int get_line(void)
1089 alarm(HEADER_READ_TIMEOUT);
1092 hdr_cnt = safe_read(STDIN_FILENO, hdr_buf, sizeof(hdr_buf));
1097 iobuf[count] = c = *hdr_ptr++;
1103 iobuf[count] = '\0';
1106 if (count < (IOBUF_SIZE - 1)) /* check overflow */
1112 #if ENABLE_FEATURE_HTTPD_CGI || ENABLE_FEATURE_HTTPD_PROXY
1114 /* gcc 4.2.1 fares better with NOINLINE */
1115 static NOINLINE void cgi_io_loop_and_exit(int fromCgi_rd, int toCgi_wr, int post_len) NORETURN;
1116 static NOINLINE void cgi_io_loop_and_exit(int fromCgi_rd, int toCgi_wr, int post_len)
1118 enum { FROM_CGI = 1, TO_CGI = 2 }; /* indexes in pfd[] */
1119 struct pollfd pfd[3];
1120 int out_cnt; /* we buffer a bit of initial CGI output */
1123 /* iobuf is used for CGI -> network data,
1124 * hdr_buf is for network -> CGI data (POSTDATA) */
1126 /* If CGI dies, we still want to correctly finish reading its output
1127 * and send it to the peer. So please no SIGPIPEs! */
1128 signal(SIGPIPE, SIG_IGN);
1130 // We inconsistently handle a case when more POSTDATA from network
1131 // is coming than we expected. We may give *some part* of that
1132 // extra data to CGI.
1134 //if (hdr_cnt > post_len) {
1135 // /* We got more POSTDATA from network than we expected */
1136 // hdr_cnt = post_len;
1138 post_len -= hdr_cnt;
1139 /* post_len - number of POST bytes not yet read from network */
1141 /* NB: breaking out of this loop jumps to log_and_exit() */
1144 memset(pfd, 0, sizeof(pfd));
1146 pfd[FROM_CGI].fd = fromCgi_rd;
1147 pfd[FROM_CGI].events = POLLIN;
1150 pfd[TO_CGI].fd = toCgi_wr;
1152 pfd[TO_CGI].events = POLLOUT;
1153 } else if (post_len > 0) {
1154 pfd[0].events = POLLIN;
1156 /* post_len <= 0 && hdr_cnt <= 0:
1157 * no more POST data to CGI,
1158 * let CGI see EOF on CGI's stdin */
1159 if (toCgi_wr != fromCgi_rd)
1165 /* Now wait on the set of sockets */
1166 count = safe_poll(pfd, toCgi_wr ? TO_CGI+1 : FROM_CGI+1, -1);
1169 if (safe_waitpid(pid, &status, WNOHANG) <= 0) {
1170 /* Weird. CGI didn't exit and no fd's
1171 * are ready, yet poll returned?! */
1174 if (DEBUG && WIFEXITED(status))
1175 bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
1176 if (DEBUG && WIFSIGNALED(status))
1177 bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
1182 if (pfd[TO_CGI].revents) {
1183 /* hdr_cnt > 0 here due to the way pfd[TO_CGI].events set */
1184 /* Have data from peer and can write to CGI */
1185 count = safe_write(toCgi_wr, hdr_ptr, hdr_cnt);
1186 /* Doesn't happen, we dont use nonblocking IO here
1187 *if (count < 0 && errno == EAGAIN) {
1194 /* EOF/broken pipe to CGI, stop piping POST data */
1195 hdr_cnt = post_len = 0;
1199 if (pfd[0].revents) {
1200 /* post_len > 0 && hdr_cnt == 0 here */
1201 /* We expect data, prev data portion is eaten by CGI
1202 * and there *is* data to read from the peer
1204 //count = post_len > (int)sizeof(hdr_buf) ? (int)sizeof(hdr_buf) : post_len;
1205 //count = safe_read(STDIN_FILENO, hdr_buf, count);
1206 count = safe_read(STDIN_FILENO, hdr_buf, sizeof(hdr_buf));
1212 /* no more POST data can be read */
1217 if (pfd[FROM_CGI].revents) {
1218 /* There is something to read from CGI */
1221 /* Are we still buffering CGI output? */
1223 /* HTTP_200[] has single "\r\n" at the end.
1224 * According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1225 * CGI scripts MUST send their own header terminated by
1226 * empty line, then data. That's why we have only one
1227 * <cr><lf> pair here. We will output "200 OK" line
1228 * if needed, but CGI still has to provide blank line
1229 * between header and body */
1231 /* Must use safe_read, not full_read, because
1232 * CGI may output a few first bytes and then wait
1233 * for POSTDATA without closing stdout.
1234 * With full_read we may wait here forever. */
1235 count = safe_read(fromCgi_rd, rbuf + out_cnt, PIPE_BUF - 8);
1237 /* eof (or error) and there was no "HTTP",
1238 * so write it, then write received data */
1240 full_write(STDOUT_FILENO, HTTP_200, sizeof(HTTP_200)-1);
1241 full_write(STDOUT_FILENO, rbuf, out_cnt);
1243 break; /* CGI stdout is closed, exiting */
1247 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1248 if (out_cnt >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1249 /* send "HTTP/1.0 " */
1250 if (full_write(STDOUT_FILENO, HTTP_200, 9) != 9)
1252 rbuf += 8; /* skip "Status: " */
1253 count = out_cnt - 8;
1254 out_cnt = -1; /* buffering off */
1255 } else if (out_cnt >= 4) {
1256 /* Did CGI add "HTTP"? */
1257 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1258 /* there is no "HTTP", do it ourself */
1259 if (full_write(STDOUT_FILENO, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1263 if (!strstr(rbuf, "ontent-")) {
1264 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1266 * Counter-example of valid CGI without Content-type:
1267 * echo -en "HTTP/1.0 302 Found\r\n"
1268 * echo -en "Location: http://www.busybox.net\r\n"
1272 out_cnt = -1; /* buffering off */
1275 count = safe_read(fromCgi_rd, rbuf, PIPE_BUF);
1277 break; /* eof (or error) */
1279 if (full_write(STDOUT_FILENO, rbuf, count) != count)
1282 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1283 } /* if (pfd[FROM_CGI].revents) */
1289 #if ENABLE_FEATURE_HTTPD_CGI
1291 static void setenv1(const char *name, const char *value)
1293 setenv(name, value ? value : "", 1);
1297 * Spawn CGI script, forward CGI's stdin/out <=> network
1299 * Environment variables are set up and the script is invoked with pipes
1300 * for stdin/stdout. If a POST is being done the script is fed the POST
1301 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
1304 * const char *url The requested URL (with leading /).
1305 * int post_len Length of the POST body.
1306 * const char *cookie For set HTTP_COOKIE.
1307 * const char *content_type For set CONTENT_TYPE.
1309 static void send_cgi_and_exit(
1311 const char *request,
1314 const char *content_type) NORETURN;
1315 static void send_cgi_and_exit(
1317 const char *request,
1320 const char *content_type)
1322 struct fd_pair fromCgi; /* CGI -> httpd pipe */
1323 struct fd_pair toCgi; /* httpd -> CGI pipe */
1327 /* Make a copy. NB: caller guarantees:
1328 * url[0] == '/', url[1] != '/' */
1332 * We are mucking with environment _first_ and then vfork/exec,
1333 * this allows us to use vfork safely. Parent doesn't care about
1334 * these environment changes anyway.
1337 /* Check for [dirs/]script.cgi/PATH_INFO */
1338 script = (char*)url;
1339 while ((script = strchr(script + 1, '/')) != NULL) {
1341 if (!is_directory(url + 1, 1, NULL)) {
1342 /* not directory, found script.cgi/PATH_INFO */
1346 *script = '/'; /* is directory, find next '/' */
1348 setenv1("PATH_INFO", script); /* set to /PATH_INFO or "" */
1349 setenv1("REQUEST_METHOD", request);
1351 putenv(xasprintf("%s=%s?%s", "REQUEST_URI", url, g_query));
1353 setenv1("REQUEST_URI", url);
1356 *script = '\0'; /* cut off /PATH_INFO */
1358 /* SCRIPT_FILENAME is required by PHP in CGI mode */
1359 if (home_httpd[0] == '/') {
1360 char *fullpath = concat_path_file(home_httpd, url);
1361 setenv1("SCRIPT_FILENAME", fullpath);
1363 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1364 setenv1("SCRIPT_NAME", url);
1365 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1366 * QUERY_STRING: The information which follows the ? in the URL
1367 * which referenced this script. This is the query information.
1368 * It should not be decoded in any fashion. This variable
1369 * should always be set when there is query information,
1370 * regardless of command line decoding. */
1371 /* (Older versions of bbox seem to do some decoding) */
1372 setenv1("QUERY_STRING", g_query);
1373 putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1374 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1375 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1376 /* Having _separate_ variables for IP and port defeats
1377 * the purpose of having socket abstraction. Which "port"
1378 * are you using on Unix domain socket?
1379 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1382 char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
1383 char *cp = strrchr(p, ':');
1384 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1386 if (cp) *cp = '\0'; /* delete :PORT */
1387 setenv1("REMOTE_ADDR", p);
1390 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1391 setenv1("REMOTE_PORT", cp + 1);
1395 setenv1("HTTP_USER_AGENT", user_agent);
1397 setenv1("HTTP_ACCEPT", http_accept);
1398 if (http_accept_language)
1399 setenv1("HTTP_ACCEPT_LANGUAGE", http_accept_language);
1401 putenv(xasprintf("CONTENT_LENGTH=%d", post_len));
1403 setenv1("HTTP_COOKIE", cookie);
1405 setenv1("CONTENT_TYPE", content_type);
1406 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1408 setenv1("REMOTE_USER", remoteuser);
1409 putenv((char*)"AUTH_TYPE=Basic");
1413 setenv1("HTTP_REFERER", referer);
1414 setenv1("HTTP_HOST", host); /* set to "" if NULL */
1415 /* setenv1("SERVER_NAME", safe_gethostname()); - don't do this,
1416 * just run "env SERVER_NAME=xyz httpd ..." instead */
1418 xpiped_pair(fromCgi);
1423 /* TODO: log perror? */
1431 xfunc_error_retval = 242;
1433 /* NB: close _first_, then move fds! */
1436 xmove_fd(toCgi.rd, 0); /* replace stdin with the pipe */
1437 xmove_fd(fromCgi.wr, 1); /* replace stdout with the pipe */
1438 /* User seeing stderr output can be a security problem.
1439 * If CGI really wants that, it can always do dup itself. */
1442 /* Chdiring to script's dir */
1443 script = strrchr(url, '/');
1444 if (script != url) { /* paranoia */
1446 if (chdir(url + 1) != 0) {
1447 bb_perror_msg("chdir(%s)", url + 1);
1448 goto error_execing_cgi;
1450 // not needed: *script = '/';
1454 /* set argv[0] to name without path */
1458 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1460 char *suffix = strrchr(script, '.');
1464 for (cur = script_i; cur; cur = cur->next) {
1465 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1466 /* found interpreter name */
1467 argv[0] = cur->after_colon;
1476 /* restore default signal dispositions for CGI process */
1483 /* _NOT_ execvp. We do not search PATH. argv[0] is a filename
1484 * without any dir components and will only match a file
1485 * in the current directory */
1486 execv(argv[0], argv);
1488 bb_perror_msg("can't execute '%s'", argv[0]);
1491 * (we are CGI here, our stdout is pumped to the net) */
1492 send_headers_and_exit(HTTP_NOT_FOUND);
1495 /* Parent process */
1497 /* Restore variables possibly changed by child */
1498 xfunc_error_retval = 0;
1503 cgi_io_loop_and_exit(fromCgi.rd, toCgi.wr, post_len);
1506 #endif /* FEATURE_HTTPD_CGI */
1509 * Send a file response to a HTTP request, and exit
1512 * const char *url The requested URL (with leading /).
1513 * what What to send (headers/body/both).
1515 static NOINLINE void send_file_and_exit(const char *url, int what)
1522 /* does <url>.gz exist? Then use it instead */
1523 char *gzurl = xasprintf("%s.gz", url);
1524 fd = open(gzurl, O_RDONLY);
1529 file_size = sb.st_size;
1530 last_mod = sb.st_mtime;
1532 IF_FEATURE_HTTPD_GZIP(content_gzip = 0;)
1533 fd = open(url, O_RDONLY);
1536 fd = open(url, O_RDONLY);
1540 bb_perror_msg("can't open '%s'", url);
1541 /* Error pages are sent by using send_file_and_exit(SEND_BODY).
1542 * IOW: it is unsafe to call send_headers_and_exit
1543 * if what is SEND_BODY! Can recurse! */
1544 if (what != SEND_BODY)
1545 send_headers_and_exit(HTTP_NOT_FOUND);
1548 /* If you want to know about EPIPE below
1549 * (happens if you abort downloads from local httpd): */
1550 signal(SIGPIPE, SIG_IGN);
1552 /* If not found, default is "application/octet-stream" */
1553 found_mime_type = "application/octet-stream";
1554 suffix = strrchr(url, '.');
1556 static const char suffixTable[] ALIGN1 =
1557 /* Shorter suffix must be first:
1558 * ".html.htm" will fail for ".htm"
1560 ".txt.h.c.cc.cpp\0" "text/plain\0"
1561 /* .htm line must be after .h line */
1562 ".htm.html\0" "text/html\0"
1563 ".jpg.jpeg\0" "image/jpeg\0"
1564 ".gif\0" "image/gif\0"
1565 ".png\0" "image/png\0"
1566 /* .css line must be after .c line */
1567 ".css\0" "text/css\0"
1568 ".wav\0" "audio/wav\0"
1569 ".avi\0" "video/x-msvideo\0"
1570 ".qt.mov\0" "video/quicktime\0"
1571 ".mpe.mpeg\0" "video/mpeg\0"
1572 ".mid.midi\0" "audio/midi\0"
1573 ".mp3\0" "audio/mpeg\0"
1574 #if 0 /* unpopular */
1575 ".au\0" "audio/basic\0"
1576 ".pac\0" "application/x-ns-proxy-autoconfig\0"
1577 ".vrml.wrl\0" "model/vrml\0"
1579 /* compiler adds another "\0" here */
1583 /* Examine built-in table */
1584 const char *table = suffixTable;
1585 const char *table_next;
1586 for (; *table; table = table_next) {
1587 const char *try_suffix;
1588 const char *mime_type;
1589 mime_type = table + strlen(table) + 1;
1590 table_next = mime_type + strlen(mime_type) + 1;
1591 try_suffix = strstr(table, suffix);
1594 try_suffix += strlen(suffix);
1595 if (*try_suffix == '\0' || *try_suffix == '.') {
1596 found_mime_type = mime_type;
1599 /* Example: strstr(table, ".av") != NULL, but it
1600 * does not match ".avi" after all and we end up here.
1601 * The table is arranged so that in this case we know
1602 * that it can't match anything in the following lines,
1603 * and we stop the search: */
1606 /* ...then user's table */
1607 for (cur = mime_a; cur; cur = cur->next) {
1608 if (strcmp(cur->before_colon, suffix) == 0) {
1609 found_mime_type = cur->after_colon;
1616 bb_error_msg("sending file '%s' content-type: %s",
1617 url, found_mime_type);
1619 #if ENABLE_FEATURE_HTTPD_RANGES
1620 if (what == SEND_BODY /* err pages and ranges don't mix */
1621 || content_gzip /* we are sending compressed page: can't do ranges */ ///why?
1625 range_len = MAXINT(off_t);
1628 range_end = file_size - 1;
1630 if (range_end < range_start
1631 || lseek(fd, range_start, SEEK_SET) != range_start
1633 lseek(fd, 0, SEEK_SET);
1636 range_len = range_end - range_start + 1;
1637 send_headers(HTTP_PARTIAL_CONTENT);
1642 if (what & SEND_HEADERS)
1643 send_headers(HTTP_OK);
1644 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1646 off_t offset = range_start;
1648 /* sz is rounded down to 64k */
1649 ssize_t sz = MAXINT(ssize_t) - 0xffff;
1650 IF_FEATURE_HTTPD_RANGES(if (sz > range_len) sz = range_len;)
1651 count = sendfile(STDOUT_FILENO, fd, &offset, sz);
1653 if (offset == range_start)
1654 break; /* fall back to read/write loop */
1657 IF_FEATURE_HTTPD_RANGES(range_len -= sz;)
1658 if (count == 0 || range_len == 0)
1663 while ((count = safe_read(fd, iobuf, IOBUF_SIZE)) > 0) {
1665 IF_FEATURE_HTTPD_RANGES(if (count > range_len) count = range_len;)
1666 n = full_write(STDOUT_FILENO, iobuf, count);
1669 IF_FEATURE_HTTPD_RANGES(range_len -= count;)
1674 IF_FEATURE_HTTPD_USE_SENDFILE(fin:)
1676 bb_perror_msg("error");
1681 static int checkPermIP(void)
1685 for (cur = ip_a_d; cur; cur = cur->next) {
1688 "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1690 (unsigned char)(cur->ip >> 24),
1691 (unsigned char)(cur->ip >> 16),
1692 (unsigned char)(cur->ip >> 8),
1693 (unsigned char)(cur->ip),
1694 (unsigned char)(cur->mask >> 24),
1695 (unsigned char)(cur->mask >> 16),
1696 (unsigned char)(cur->mask >> 8),
1697 (unsigned char)(cur->mask)
1700 if ((rmt_ip & cur->mask) == cur->ip)
1701 return (cur->allow_deny == 'A'); /* A -> 1 */
1704 return !flg_deny_all; /* depends on whether we saw "D:*" */
1707 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1709 * Config file entries are of the form "/<path>:<user>:<passwd>".
1710 * If config file has no prefix match for path, access is allowed.
1712 * path The file path
1713 * user_and_passwd "user:passwd" to validate
1715 * Returns 1 if user_and_passwd is OK.
1717 static int check_user_passwd(const char *path, const char *user_and_passwd)
1720 const char *prev = NULL;
1722 for (cur = g_auth; cur; cur = cur->next) {
1723 const char *dir_prefix;
1726 dir_prefix = cur->before_colon;
1729 /* If already saw a match, don't accept other different matches */
1730 if (prev && strcmp(prev, dir_prefix) != 0)
1734 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", dir_prefix, user_and_passwd);
1736 /* If it's not a prefix match, continue searching */
1737 len = strlen(dir_prefix);
1738 if (len != 1 /* dir_prefix "/" matches all, don't need to check */
1739 && (strncmp(dir_prefix, path, len) != 0
1740 || (path[len] != '/' && path[len] != '\0'))
1745 /* Path match found */
1748 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1751 md5_passwd = strchr(cur->after_colon, ':');
1752 if (md5_passwd && md5_passwd[1] == '$' && md5_passwd[2] == '1'
1753 && md5_passwd[3] == '$' && md5_passwd[4]
1759 user_len_p1 = md5_passwd - cur->after_colon;
1760 /* comparing "user:" */
1761 if (strncmp(cur->after_colon, user_and_passwd, user_len_p1) != 0) {
1765 encrypted = pw_encrypt(
1766 user_and_passwd + user_len_p1 /* cleartext pwd from user */,
1767 md5_passwd /*salt */, 1 /* cleanup */);
1768 r = strcmp(encrypted, md5_passwd);
1771 goto set_remoteuser_var; /* Ok */
1776 /* Comparing plaintext "user:pass" in one go */
1777 if (strcmp(cur->after_colon, user_and_passwd) == 0) {
1779 remoteuser = xstrndup(user_and_passwd,
1780 strchrnul(user_and_passwd, ':') - user_and_passwd);
1785 /* 0(bad) if prev is set: matches were found but passwd was wrong */
1786 return (prev == NULL);
1788 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1790 #if ENABLE_FEATURE_HTTPD_PROXY
1791 static Htaccess_Proxy *find_proxy_entry(const char *url)
1794 for (p = proxy; p; p = p->next) {
1795 if (strncmp(url, p->url_from, strlen(p->url_from)) == 0)
1805 static void send_REQUEST_TIMEOUT_and_exit(int sig) NORETURN;
1806 static void send_REQUEST_TIMEOUT_and_exit(int sig UNUSED_PARAM)
1808 send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
1812 * Handle an incoming http request and exit.
1814 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr) NORETURN;
1815 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
1817 static const char request_GET[] ALIGN1 = "GET";
1822 #if ENABLE_FEATURE_HTTPD_CGI
1823 static const char request_HEAD[] ALIGN1 = "HEAD";
1824 const char *prequest;
1825 char *cookie = NULL;
1826 char *content_type = NULL;
1827 unsigned long length = 0;
1828 #elif ENABLE_FEATURE_HTTPD_PROXY
1829 #define prequest request_GET
1830 unsigned long length = 0;
1832 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1833 smallint authorized = -1;
1835 smallint ip_allowed;
1836 char http_major_version;
1837 #if ENABLE_FEATURE_HTTPD_PROXY
1838 char http_minor_version;
1839 char *header_buf = header_buf; /* for gcc */
1840 char *header_ptr = header_ptr;
1841 Htaccess_Proxy *proxy_entry;
1844 /* Allocation of iobuf is postponed until now
1845 * (IOW, server process doesn't need to waste 8k) */
1846 iobuf = xmalloc(IOBUF_SIZE);
1849 if (fromAddr->u.sa.sa_family == AF_INET) {
1850 rmt_ip = ntohl(fromAddr->u.sin.sin_addr.s_addr);
1852 #if ENABLE_FEATURE_IPV6
1853 if (fromAddr->u.sa.sa_family == AF_INET6
1854 && fromAddr->u.sin6.sin6_addr.s6_addr32[0] == 0
1855 && fromAddr->u.sin6.sin6_addr.s6_addr32[1] == 0
1856 && ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[2]) == 0xffff)
1857 rmt_ip = ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[3]);
1859 if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1860 /* NB: can be NULL (user runs httpd -i by hand?) */
1861 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr->u.sa);
1864 /* this trick makes -v logging much simpler */
1866 applet_name = rmt_ip_str;
1868 bb_error_msg("connected");
1871 /* Install timeout handler. get_line() needs it. */
1872 signal(SIGALRM, send_REQUEST_TIMEOUT_and_exit);
1874 if (!get_line()) /* EOF or error or empty line */
1875 send_headers_and_exit(HTTP_BAD_REQUEST);
1877 /* Determine type of request (GET/POST) */
1878 urlp = strpbrk(iobuf, " \t");
1880 send_headers_and_exit(HTTP_BAD_REQUEST);
1882 #if ENABLE_FEATURE_HTTPD_CGI
1883 prequest = request_GET;
1884 if (strcasecmp(iobuf, prequest) != 0) {
1885 prequest = request_HEAD;
1886 if (strcasecmp(iobuf, prequest) != 0) {
1888 if (strcasecmp(iobuf, prequest) != 0)
1889 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1893 if (strcasecmp(iobuf, request_GET) != 0)
1894 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1896 urlp = skip_whitespace(urlp);
1898 send_headers_and_exit(HTTP_BAD_REQUEST);
1900 /* Find end of URL and parse HTTP version, if any */
1901 http_major_version = '0';
1902 IF_FEATURE_HTTPD_PROXY(http_minor_version = '0';)
1903 tptr = strchrnul(urlp, ' ');
1904 /* Is it " HTTP/"? */
1905 if (tptr[0] && strncmp(tptr + 1, HTTP_200, 5) == 0) {
1906 http_major_version = tptr[6];
1907 IF_FEATURE_HTTPD_PROXY(http_minor_version = tptr[8];)
1911 /* Copy URL from after "GET "/"POST " to stack-allocated char[] */
1912 urlcopy = alloca((tptr - urlp) + 2 + strlen(index_page));
1913 /*if (urlcopy == NULL)
1914 * send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);*/
1915 strcpy(urlcopy, urlp);
1916 /* NB: urlcopy ptr is never changed after this */
1918 /* Extract url args if present */
1920 tptr = strchr(urlcopy, '?');
1926 /* Decode URL escape sequences */
1927 tptr = decodeString(urlcopy, 0);
1929 send_headers_and_exit(HTTP_BAD_REQUEST);
1930 if (tptr == urlcopy + 1) {
1931 /* '/' or NUL is encoded */
1932 send_headers_and_exit(HTTP_NOT_FOUND);
1935 /* Canonicalize path */
1936 /* Algorithm stolen from libbb bb_simplify_path(),
1937 * but don't strdup, retain trailing slash, protect root */
1938 urlp = tptr = urlcopy;
1941 /* skip duplicate (or initial) slash */
1946 /* skip extra "/./" */
1947 if (tptr[1] == '/' || !tptr[1]) {
1950 /* "..": be careful */
1951 if (tptr[1] == '.' && (tptr[2] == '/' || !tptr[2])) {
1953 if (urlp == urlcopy) /* protect root */
1954 send_headers_and_exit(HTTP_BAD_REQUEST);
1955 while (*--urlp != '/') /* omit previous dir */;
1962 *++urlp = '\0'; /* terminate after last character */
1964 /* If URL is a directory, add '/' */
1965 if (urlp[-1] != '/') {
1966 if (is_directory(urlcopy + 1, 1, NULL)) {
1967 found_moved_temporarily = urlcopy;
1973 bb_error_msg("url:%s", urlcopy);
1976 ip_allowed = checkPermIP();
1977 while (ip_allowed && (tptr = strchr(tptr + 1, '/')) != NULL) {
1978 /* have path1/path2 */
1980 if (is_directory(urlcopy + 1, 1, NULL)) {
1981 /* may have subdir config */
1982 parse_conf(urlcopy + 1, SUBDIR_PARSE);
1983 ip_allowed = checkPermIP();
1988 #if ENABLE_FEATURE_HTTPD_PROXY
1989 proxy_entry = find_proxy_entry(urlcopy);
1991 header_buf = header_ptr = xmalloc(IOBUF_SIZE);
1994 if (http_major_version >= '0') {
1995 /* Request was with "... HTTP/nXXX", and n >= 0 */
1997 /* Read until blank line */
2000 break; /* EOF or error or empty line */
2002 bb_error_msg("header: '%s'", iobuf);
2004 #if ENABLE_FEATURE_HTTPD_PROXY
2005 /* We need 2 more bytes for yet another "\r\n" -
2006 * see near fdprintf(proxy_fd...) further below */
2007 if (proxy_entry && (header_ptr - header_buf) < IOBUF_SIZE - 2) {
2008 int len = strlen(iobuf);
2009 if (len > IOBUF_SIZE - (header_ptr - header_buf) - 4)
2010 len = IOBUF_SIZE - (header_ptr - header_buf) - 4;
2011 memcpy(header_ptr, iobuf, len);
2013 header_ptr[0] = '\r';
2014 header_ptr[1] = '\n';
2019 #if ENABLE_FEATURE_HTTPD_CGI || ENABLE_FEATURE_HTTPD_PROXY
2020 /* Try and do our best to parse more lines */
2021 if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
2022 /* extra read only for POST */
2023 if (prequest != request_GET
2024 # if ENABLE_FEATURE_HTTPD_CGI
2025 && prequest != request_HEAD
2028 tptr = skip_whitespace(iobuf + sizeof("Content-length:") - 1);
2030 send_headers_and_exit(HTTP_BAD_REQUEST);
2031 /* not using strtoul: it ignores leading minus! */
2032 length = bb_strtou(tptr, NULL, 10);
2033 /* length is "ulong", but we need to pass it to int later */
2034 if (errno || length > INT_MAX)
2035 send_headers_and_exit(HTTP_BAD_REQUEST);
2039 #if ENABLE_FEATURE_HTTPD_CGI
2040 else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
2041 cookie = xstrdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
2042 } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
2043 content_type = xstrdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
2044 } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
2045 referer = xstrdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
2046 } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
2047 user_agent = xstrdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
2048 } else if (STRNCASECMP(iobuf, "Host:") == 0) {
2049 host = xstrdup(skip_whitespace(iobuf + sizeof("Host:")-1));
2050 } else if (STRNCASECMP(iobuf, "Accept:") == 0) {
2051 http_accept = xstrdup(skip_whitespace(iobuf + sizeof("Accept:")-1));
2052 } else if (STRNCASECMP(iobuf, "Accept-Language:") == 0) {
2053 http_accept_language = xstrdup(skip_whitespace(iobuf + sizeof("Accept-Language:")-1));
2056 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
2057 if (STRNCASECMP(iobuf, "Authorization:") == 0) {
2058 /* We only allow Basic credentials.
2059 * It shows up as "Authorization: Basic <user>:<passwd>" where
2060 * "<user>:<passwd>" is base64 encoded.
2062 tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
2063 if (STRNCASECMP(tptr, "Basic") != 0)
2065 tptr += sizeof("Basic")-1;
2066 /* decodeBase64() skips whitespace itself */
2068 authorized = check_user_passwd(urlcopy, tptr);
2071 #if ENABLE_FEATURE_HTTPD_RANGES
2072 if (STRNCASECMP(iobuf, "Range:") == 0) {
2073 /* We know only bytes=NNN-[MMM] */
2074 char *s = skip_whitespace(iobuf + sizeof("Range:")-1);
2075 if (strncmp(s, "bytes=", 6) == 0) {
2076 s += sizeof("bytes=")-1;
2077 range_start = BB_STRTOOFF(s, &s, 10);
2078 if (s[0] != '-' || range_start < 0) {
2081 range_end = BB_STRTOOFF(s+1, NULL, 10);
2082 if (errno || range_end < range_start)
2088 #if ENABLE_FEATURE_HTTPD_GZIP
2089 if (STRNCASECMP(iobuf, "Accept-Encoding:") == 0) {
2090 /* Note: we do not support "gzip;q=0"
2091 * method of _disabling_ gzip
2092 * delivery. No one uses that, though */
2093 const char *s = strstr(iobuf, "gzip");
2095 // want more thorough checks?
2105 } /* while extra header reading */
2108 /* We are done reading headers, disable peer timeout */
2111 if (strcmp(bb_basename(urlcopy), HTTPD_CONF) == 0 || !ip_allowed) {
2112 /* protect listing [/path]/httpd.conf or IP deny */
2113 send_headers_and_exit(HTTP_FORBIDDEN);
2116 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
2117 /* Case: no "Authorization:" was seen, but page does require passwd.
2118 * Check that with dummy user:pass */
2120 authorized = check_user_passwd(urlcopy, ":");
2122 send_headers_and_exit(HTTP_UNAUTHORIZED);
2125 if (found_moved_temporarily) {
2126 send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
2129 #if ENABLE_FEATURE_HTTPD_PROXY
2130 if (proxy_entry != NULL) {
2132 len_and_sockaddr *lsa;
2134 proxy_fd = socket(AF_INET, SOCK_STREAM, 0);
2136 send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
2137 lsa = host2sockaddr(proxy_entry->host_port, 80);
2139 send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
2140 if (connect(proxy_fd, &lsa->u.sa, lsa->len) < 0)
2141 send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
2142 fdprintf(proxy_fd, "%s %s%s%s%s HTTP/%c.%c\r\n",
2143 prequest, /* GET or POST */
2144 proxy_entry->url_to, /* url part 1 */
2145 urlcopy + strlen(proxy_entry->url_from), /* url part 2 */
2146 (g_query ? "?" : ""), /* "?" (maybe) */
2147 (g_query ? g_query : ""), /* query string (maybe) */
2148 http_major_version, http_minor_version);
2149 header_ptr[0] = '\r';
2150 header_ptr[1] = '\n';
2152 write(proxy_fd, header_buf, header_ptr - header_buf);
2153 free(header_buf); /* on the order of 8k, free it */
2154 cgi_io_loop_and_exit(proxy_fd, proxy_fd, length);
2158 tptr = urlcopy + 1; /* skip first '/' */
2160 #if ENABLE_FEATURE_HTTPD_CGI
2161 if (strncmp(tptr, "cgi-bin/", 8) == 0) {
2162 if (tptr[8] == '\0') {
2163 /* protect listing "cgi-bin/" */
2164 send_headers_and_exit(HTTP_FORBIDDEN);
2166 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
2170 if (urlp[-1] == '/')
2171 strcpy(urlp, index_page);
2172 if (stat(tptr, &sb) == 0) {
2173 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
2174 char *suffix = strrchr(tptr, '.');
2177 for (cur = script_i; cur; cur = cur->next) {
2178 if (strcmp(cur->before_colon + 1, suffix) == 0) {
2179 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
2184 file_size = sb.st_size;
2185 last_mod = sb.st_mtime;
2187 #if ENABLE_FEATURE_HTTPD_CGI
2188 else if (urlp[-1] == '/') {
2189 /* It's a dir URL and there is no index.html
2190 * Try cgi-bin/index.cgi */
2191 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
2194 send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
2197 /* else fall through to send_file, it errors out if open fails: */
2199 if (prequest != request_GET && prequest != request_HEAD) {
2200 /* POST for files does not make sense */
2201 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
2203 send_file_and_exit(tptr,
2204 (prequest != request_HEAD ? SEND_HEADERS_AND_BODY : SEND_HEADERS)
2207 send_file_and_exit(tptr, SEND_HEADERS_AND_BODY);
2212 * The main http server function.
2213 * Given a socket, listen for new connections and farm out
2214 * the processing as a [v]forked process.
2218 static void mini_httpd(int server_socket) NORETURN;
2219 static void mini_httpd(int server_socket)
2221 /* NB: it's best to not use xfuncs in this loop before fork().
2222 * Otherwise server may die on transient errors (temporary
2223 * out-of-memory condition, etc), which is Bad(tm).
2224 * Try to do any dangerous calls after fork.
2228 len_and_sockaddr fromAddr;
2230 /* Wait for connections... */
2231 fromAddr.len = LSA_SIZEOF_SA;
2232 n = accept(server_socket, &fromAddr.u.sa, &fromAddr.len);
2236 /* set the KEEPALIVE option to cull dead connections */
2237 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
2241 /* Do not reload config on HUP */
2242 signal(SIGHUP, SIG_IGN);
2243 close(server_socket);
2247 handle_incoming_and_exit(&fromAddr);
2249 /* parent, or fork failed */
2255 static void mini_httpd_nommu(int server_socket, int argc, char **argv) NORETURN;
2256 static void mini_httpd_nommu(int server_socket, int argc, char **argv)
2258 char *argv_copy[argc + 2];
2260 argv_copy[0] = argv[0];
2261 argv_copy[1] = (char*)"-i";
2262 memcpy(&argv_copy[2], &argv[1], argc * sizeof(argv[0]));
2264 /* NB: it's best to not use xfuncs in this loop before vfork().
2265 * Otherwise server may die on transient errors (temporary
2266 * out-of-memory condition, etc), which is Bad(tm).
2267 * Try to do any dangerous calls after fork.
2271 len_and_sockaddr fromAddr;
2273 /* Wait for connections... */
2274 fromAddr.len = LSA_SIZEOF_SA;
2275 n = accept(server_socket, &fromAddr.u.sa, &fromAddr.len);
2279 /* set the KEEPALIVE option to cull dead connections */
2280 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
2284 /* Do not reload config on HUP */
2285 signal(SIGHUP, SIG_IGN);
2286 close(server_socket);
2290 /* Run a copy of ourself in inetd mode */
2293 /* parent, or vfork failed */
2301 * Process a HTTP connection on stdin/out.
2304 static void mini_httpd_inetd(void) NORETURN;
2305 static void mini_httpd_inetd(void)
2307 len_and_sockaddr fromAddr;
2309 memset(&fromAddr, 0, sizeof(fromAddr));
2310 fromAddr.len = LSA_SIZEOF_SA;
2311 /* NB: can fail if user runs it by hand and types in http cmds */
2312 getpeername(0, &fromAddr.u.sa, &fromAddr.len);
2313 handle_incoming_and_exit(&fromAddr);
2316 static void sighup_handler(int sig UNUSED_PARAM)
2318 parse_conf(DEFAULT_PATH_HTTPD_CONF, SIGNALED_PARSE);
2322 c_opt_config_file = 0,
2325 IF_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
2326 IF_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
2327 IF_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
2328 IF_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
2333 OPT_CONFIG_FILE = 1 << c_opt_config_file,
2334 OPT_DECODE_URL = 1 << d_opt_decode_url,
2335 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
2336 OPT_ENCODE_URL = IF_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
2337 OPT_REALM = IF_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
2338 OPT_MD5 = IF_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
2339 OPT_SETUID = IF_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
2340 OPT_PORT = 1 << p_opt_port,
2341 OPT_INETD = 1 << p_opt_inetd,
2342 OPT_FOREGROUND = 1 << p_opt_foreground,
2343 OPT_VERBOSE = 1 << p_opt_verbose,
2347 int httpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
2348 int httpd_main(int argc UNUSED_PARAM, char **argv)
2350 int server_socket = server_socket; /* for gcc */
2352 char *url_for_decode;
2353 IF_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
2354 IF_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
2355 IF_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
2356 IF_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
2360 #if ENABLE_LOCALE_SUPPORT
2361 /* Undo busybox.c: we want to speak English in http (dates etc) */
2362 setlocale(LC_TIME, "C");
2365 home_httpd = xrealloc_getcwd_or_warn(NULL);
2366 /* -v counts, -i implies -f */
2367 opt_complementary = "vv:if";
2368 /* We do not "absolutize" path given by -h (home) opt.
2369 * If user gives relative path in -h,
2370 * $SCRIPT_FILENAME will not be set. */
2371 opt = getopt32(argv, "c:d:h:"
2372 IF_FEATURE_HTTPD_ENCODE_URL_STR("e:")
2373 IF_FEATURE_HTTPD_BASIC_AUTH("r:")
2374 IF_FEATURE_HTTPD_AUTH_MD5("m:")
2375 IF_FEATURE_HTTPD_SETUID("u:")
2377 &opt_c_configFile, &url_for_decode, &home_httpd
2378 IF_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
2379 IF_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
2380 IF_FEATURE_HTTPD_AUTH_MD5(, &pass)
2381 IF_FEATURE_HTTPD_SETUID(, &s_ugid)
2382 , &bind_addr_or_port
2385 if (opt & OPT_DECODE_URL) {
2386 fputs(decodeString(url_for_decode, 1), stdout);
2389 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
2390 if (opt & OPT_ENCODE_URL) {
2391 fputs(encodeString(url_for_encode), stdout);
2395 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
2396 if (opt & OPT_MD5) {
2397 char salt[sizeof("$1$XXXXXXXX")];
2401 crypt_make_salt(salt + 3, 4, 0);
2402 puts(pw_encrypt(pass, salt, 1));
2406 #if ENABLE_FEATURE_HTTPD_SETUID
2407 if (opt & OPT_SETUID) {
2408 xget_uidgid(&ugid, s_ugid);
2413 if (!(opt & OPT_FOREGROUND)) {
2414 bb_daemonize_or_rexec(0, argv); /* don't change current directory */
2419 if (!(opt & OPT_INETD)) {
2420 signal(SIGCHLD, SIG_IGN);
2421 server_socket = openServer();
2422 #if ENABLE_FEATURE_HTTPD_SETUID
2423 /* drop privileges */
2424 if (opt & OPT_SETUID) {
2425 if (ugid.gid != (gid_t)-1) {
2426 if (setgroups(1, &ugid.gid) == -1)
2427 bb_perror_msg_and_die("setgroups");
2436 /* User can do it himself: 'env - PATH="$PATH" httpd'
2437 * We don't do it because we don't want to screw users
2439 * 'env - VAR1=val1 VAR2=val2 httpd'
2440 * and have VAR1 and VAR2 values visible in their CGIs.
2441 * Besides, it is also smaller. */
2443 char *p = getenv("PATH");
2444 /* env strings themself are not freed, no need to xstrdup(p): */
2448 // if (!(opt & OPT_INETD))
2449 // setenv_long("SERVER_PORT", ???);
2453 parse_conf(DEFAULT_PATH_HTTPD_CONF, FIRST_PARSE);
2454 if (!(opt & OPT_INETD))
2455 signal(SIGHUP, sighup_handler);
2457 xfunc_error_retval = 0;
2458 if (opt & OPT_INETD)
2461 if (!(opt & OPT_FOREGROUND))
2462 bb_daemonize(0); /* don't change current directory */
2463 mini_httpd(server_socket); /* never returns */
2465 mini_httpd_nommu(server_socket, argc, argv); /* never returns */