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 * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
46 * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
47 * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
48 * .au:audio/basic # additional mime type for audio.au files
49 * *.php:/path/php # running cgi.php scripts through an interpreter
51 * A/D may be as a/d or allow/deny - first char case insensitive
52 * Deny IP rules take precedence over allow rules.
55 * The Deny/Allow IP logic:
57 * - Default is to allow all. No addresses are denied unless
58 * denied with a D: rule.
59 * - Order of Deny/Allow rules is significant
60 * - Deny rules take precedence over allow rules.
61 * - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
63 * - Specification of Allow all (A:*) is a no-op
66 * 1. Allow only specified addresses
67 * A:172.20 # Allow any address that begins with 172.20.
68 * A:10.10. # Allow any address that begins with 10.10.
69 * A:127.0.0.1 # Allow local loopback connections
70 * D:* # Deny from other IP connections
72 * 2. Only deny specified addresses
73 * D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
74 * D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
75 * A:* # (optional line added for clarity)
77 * If a sub directory contains a config file it is parsed and merged with
78 * any existing settings as if it was appended to the original configuration.
80 * subdir paths are relative to the containing subdir and thus cannot
81 * affect the parent rules.
83 * Note that since the sub dir is parsed in the forked thread servicing the
84 * subdir http request, any merge is discarded when the process exits. As a
85 * result, the subdir settings only have a lifetime of a single request.
88 * If -c is not set, an attempt will be made to open the default
89 * root configuration file. If -c is set and the file is not found, the
90 * server exits with an error.
95 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
96 #include <sys/sendfile.h>
102 /* amount of buffering in a pipe */
104 # define PIPE_BUF 4096
107 #define IOBUF_SIZE 8192 /* IO buffer */
109 #define HEADER_READ_TIMEOUT 60
111 static const char default_path_httpd_conf[] ALIGN1 = "/etc";
112 static const char httpd_conf[] ALIGN1 = "httpd.conf";
113 static const char HTTP_200[] ALIGN1 = "HTTP/1.0 200 OK\r\n";
115 typedef struct has_next_ptr {
116 struct has_next_ptr *next;
119 /* Must have "next" as a first member */
120 typedef struct Htaccess {
121 struct Htaccess *next;
123 char before_colon[1]; /* really bigger, must be last */
126 /* Must have "next" as a first member */
127 typedef struct Htaccess_IP {
128 struct Htaccess_IP *next;
135 int verbose; /* must be int (used by getopt32) */
136 smallint flg_deny_all;
138 unsigned rmt_ip; /* used for IP-based allow/deny rules */
140 off_t ContentLength; /* -1 - unknown */
141 char *rmt_ip_str; /* for $REMOTE_ADDR and $REMOTE_PORT */
142 const char *bind_addr_or_port;
145 const char *configFile;
146 const char *home_httpd;
148 const char *found_mime_type;
149 const char *found_moved_temporarily;
150 Htaccess_IP *ip_a_d; /* config allow/deny lines */
152 USE_FEATURE_HTTPD_BASIC_AUTH(const char *g_realm;)
153 USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
154 USE_FEATURE_HTTPD_CGI(char *referer;)
155 USE_FEATURE_HTTPD_CGI(char *user_agent;)
157 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
158 Htaccess *g_auth; /* config user:password lines */
160 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
161 Htaccess *mime_a; /* config mime types */
163 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
164 Htaccess *script_i; /* config script interpreters */
166 char *iobuf; /* [IOBUF_SIZE] */
167 #define hdr_buf bb_common_bufsiz1
171 #define G (*ptr_to_globals)
172 #define verbose (G.verbose )
173 #define flg_deny_all (G.flg_deny_all )
174 #define rmt_ip (G.rmt_ip )
175 #define bind_addr_or_port (G.bind_addr_or_port)
176 #define g_query (G.g_query )
177 #define configFile (G.configFile )
178 #define home_httpd (G.home_httpd )
179 #define found_mime_type (G.found_mime_type )
180 #define found_moved_temporarily (G.found_moved_temporarily)
181 #define ContentLength (G.ContentLength )
182 #define last_mod (G.last_mod )
183 #define ip_a_d (G.ip_a_d )
184 #define g_realm (G.g_realm )
185 #define remoteuser (G.remoteuser )
186 #define referer (G.referer )
187 #define user_agent (G.user_agent )
188 #define rmt_ip_str (G.rmt_ip_str )
189 #define g_auth (G.g_auth )
190 #define mime_a (G.mime_a )
191 #define script_i (G.script_i )
192 #define iobuf (G.iobuf )
193 #define hdr_ptr (G.hdr_ptr )
194 #define hdr_cnt (G.hdr_cnt )
195 #define INIT_G() do { \
196 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
197 USE_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
198 bind_addr_or_port = "80"; \
199 ContentLength = -1; \
205 HTTP_MOVED_TEMPORARILY = 302,
206 HTTP_BAD_REQUEST = 400, /* malformed syntax */
207 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
208 HTTP_NOT_FOUND = 404,
209 HTTP_FORBIDDEN = 403,
210 HTTP_REQUEST_TIMEOUT = 408,
211 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
212 HTTP_INTERNAL_SERVER_ERROR = 500,
213 #if 0 /* future use */
215 HTTP_SWITCHING_PROTOCOLS = 101,
218 HTTP_NON_AUTHORITATIVE_INFO = 203,
219 HTTP_NO_CONTENT = 204,
220 HTTP_MULTIPLE_CHOICES = 300,
221 HTTP_MOVED_PERMANENTLY = 301,
222 HTTP_NOT_MODIFIED = 304,
223 HTTP_PAYMENT_REQUIRED = 402,
224 HTTP_BAD_GATEWAY = 502,
225 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
226 HTTP_RESPONSE_SETSIZE = 0xffffffff
231 HttpResponseNum type;
236 static const HttpEnumString httpResponseNames[] = {
237 { HTTP_OK, "OK", NULL },
238 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
239 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
240 "No request appeared within a reasonable time period." },
241 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
242 "The requested method is not recognized by this server." },
243 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
244 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
246 { HTTP_NOT_FOUND, "Not Found",
247 "The requested URL was not found on this server." },
248 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
249 { HTTP_FORBIDDEN, "Forbidden", "" },
250 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
251 "Internal Server Error" },
252 #if 0 /* not implemented */
253 { HTTP_CREATED, "Created" },
254 { HTTP_ACCEPTED, "Accepted" },
255 { HTTP_NO_CONTENT, "No Content" },
256 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
257 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
258 { HTTP_NOT_MODIFIED, "Not Modified" },
259 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
260 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
265 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
267 static void free_llist(has_next_ptr **pptr)
269 has_next_ptr *cur = *pptr;
271 has_next_ptr *t = cur;
278 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
279 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
280 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
281 static ALWAYS_INLINE void free_Htaccess_list(Htaccess **pptr)
283 free_llist((has_next_ptr**)pptr);
287 static ALWAYS_INLINE void free_Htaccess_IP_list(Htaccess_IP **pptr)
289 free_llist((has_next_ptr**)pptr);
292 /* Returns presumed mask width in bits or < 0 on error.
293 * Updates strp, stores IP at provided pointer */
294 static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
296 const char *p = *strp;
304 for (j = 0; j < 4; j++) {
307 if ((*p < '0' || *p > '9') && *p != '/' && *p)
310 while (*p >= '0' && *p <= '9') {
321 ip = (ip << 8) | octet;
335 /* Returns 0 on success. Stores IP and mask at provided pointers */
336 static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
342 i = scan_ip(&str, ipp, '/');
347 /* there is /xxx after dotted-IP address */
348 i = bb_strtou(str, &p, 10);
350 /* 'xxx' itself is dotted-IP mask, parse it */
351 /* (return 0 (success) only if it has N.N.N.N form) */
352 return scan_ip(&str, maskp, '\0') - 32;
361 if (sizeof(unsigned) == 4 && i == 32) {
362 /* mask >>= 32 below may not work */
368 /* i == 0 -> *maskp = 0x00000000
369 * i == 1 -> *maskp = 0x80000000
370 * i == 4 -> *maskp = 0xf0000000
371 * i == 31 -> *maskp = 0xfffffffe
372 * i == 32 -> *maskp = 0xffffffff */
373 *maskp = (uint32_t)(~mask);
378 * Parse configuration file into in-memory linked list.
380 * The first non-white character is examined to determine if the config line
381 * is one of the following:
382 * .ext:mime/type # new mime type not compiled into httpd
383 * [adAD]:from # ip address allow/deny, * for wildcard
384 * /path:user:pass # username/password
386 * Any previous IP rules are discarded.
387 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
388 * are also discarded. That is, previous settings are retained if flag is
391 * path Path where to look for httpd.conf (without filename).
392 * flag Type of the parse request.
395 #define FIRST_PARSE 0
396 #define SUBDIR_PARSE 1
397 #define SIGNALED_PARSE 2
398 #define FIND_FROM_HTTPD_ROOT 3
399 static void parse_conf(const char *path, int flag)
402 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
405 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
406 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
407 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
410 const char *cf = configFile;
416 /* discard old rules */
417 free_Htaccess_IP_list(&ip_a_d);
419 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
420 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
421 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
422 /* retain previous auth and mime config only for subdir parse */
423 if (flag != SUBDIR_PARSE) {
424 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
425 free_Htaccess_list(&g_auth);
427 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
428 free_Htaccess_list(&mime_a);
430 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
431 free_Htaccess_list(&script_i);
436 if (flag == SUBDIR_PARSE || cf == NULL) {
437 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
439 if (flag == FIRST_PARSE)
440 bb_error_msg_and_die(bb_msg_memory_exhausted);
443 sprintf((char *)cf, "%s/%s", path, httpd_conf);
446 while ((f = fopen(cf, "r")) == NULL) {
447 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
448 /* config file not found, no changes to config */
451 if (configFile && flag == FIRST_PARSE) /* if -c option given */
452 bb_perror_msg_and_die("%s", cf);
453 flag = FIND_FROM_HTTPD_ROOT;
457 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
460 /* This could stand some work */
461 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
463 for (p = p0; *p0 != '\0' && *p0 != '#'; p0++) {
466 if (*p0 == ':' && c == NULL)
472 /* test for empty or strange line */
473 if (c == NULL || *c == '\0')
480 /* memorize deny all */
483 /* skip default other "word:*" config lines */
489 else if (*p0 != 'D' && *p0 != 'A'
490 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
493 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
496 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
501 if (*p0 == 'A' || *p0 == 'D') {
502 /* storing current config IP line */
503 pip = xzalloc(sizeof(Htaccess_IP));
505 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
506 /* syntax IP{/mask} error detected, protect all */
510 pip->allow_deny = *p0;
512 /* Deny:from_IP move top */
516 /* add to bottom A:form_IP config line */
517 Htaccess_IP *prev_IP = ip_a_d;
519 if (prev_IP == NULL) {
522 while (prev_IP->next)
523 prev_IP = prev_IP->next;
530 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
532 /* make full path from httpd root / current_path / config_line_path */
533 cf = (flag == SUBDIR_PARSE ? path : "");
534 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
538 sprintf(p0, "/%s%s", cf, buf);
540 /* another call bb_simplify_path */
545 if (*cf == '/') { /* skip duplicate (or initial) slash */
547 } else if (*cf == '.') {
548 if (cf[1] == '/' || cf[1] == '\0') { /* remove extra '.' */
550 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == '\0')) {
553 while (*--p != '/') /* omit previous dir */;
562 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
563 ++p; /* so keep last character */
566 sprintf(p0, "%s:%s", p0, c);
570 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
571 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
572 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
573 /* storing current config line */
574 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
576 cf = strcpy(cur->before_colon, p0);
579 cur->after_colon = c;
580 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
582 /* config .mime line move top for overwrite previous */
588 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
589 if (*cf == '*' && cf[1] == '.') {
590 /* config script interpreter line move top for overwrite previous */
591 cur->next = script_i;
596 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
602 /* sort path, if current lenght eq or bigger then move up */
603 Htaccess *prev_hti = g_auth;
604 size_t l = strlen(cf);
607 for (hti = prev_hti; hti; hti = hti->next) {
608 if (l >= strlen(hti->before_colon)) {
609 /* insert before hti */
611 if (prev_hti != hti) {
612 prev_hti->next = cur;
620 prev_hti = prev_hti->next;
622 if (!hti) { /* not inserted, add to bottom */
634 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
636 * Given a string, html-encode special characters.
637 * This is used for the -e command line option to provide an easy way
638 * for scripts to encode result data without confusing browsers. The
639 * returned string pointer is memory allocated by malloc().
641 * Returns a pointer to the encoded string (malloced).
643 static char *encodeString(const char *string)
645 /* take the simple route and encode everything */
646 /* could possibly scan once to get length. */
647 int len = strlen(string);
648 char *out = xmalloc(len * 6 + 1);
652 while ((ch = *string++)) {
653 // very simple check for what to encode
654 if (isalnum(ch)) *p++ = ch;
655 else p += sprintf(p, "&#%d;", (unsigned char) ch);
660 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
663 * Given a URL encoded string, convert it to plain ascii.
664 * Since decoding always makes strings smaller, the decode is done in-place.
665 * Thus, callers should strdup() the argument if they do not want the
666 * argument modified. The return is the original pointer, allowing this
667 * function to be easily used as arguments to other functions.
669 * string The first string to decode.
670 * option_d 1 if called for httpd -d
672 * Returns a pointer to the decoded string (same as input).
674 static unsigned hex_to_bin(unsigned char c)
676 unsigned v = c | 0x20; /* lowercase */
686 void t(char c) { printf("'%c' %u\n", c, hex_to_bin(c)); }
687 int main() { t('0'); t('9'); t('A'); t('F'); t('a'); t('f');
688 t('0'-1); t('9'+1); t('A'-1); t('F'+1); t('a'-1); t('f'+1); return 0; }
690 static char *decodeString(char *orig, int option_d)
692 /* note that decoded string is always shorter than original */
697 while ((c = *ptr++) != '\0') {
700 if (option_d && c == '+') {
708 v = hex_to_bin(ptr[0]);
716 v = (v * 16) | hex_to_bin(ptr[1]);
719 if (!option_d && (v == '/' || v == '\0')) {
720 /* caller takes it as indication of invalid
721 * (dangerous wrt exploits) chars */
731 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
733 * Decode a base64 data stream as per rfc1521.
734 * Note that the rfc states that non base64 chars are to be ignored.
735 * Since the decode always results in a shorter size than the input,
736 * it is OK to pass the input arg as an output arg.
737 * Parameter: a pointer to a base64 encoded string.
738 * Decoded data is stored in-place.
740 static void decodeBase64(char *Data)
742 const unsigned char *in = (const unsigned char *)Data;
743 /* The decoded size will be at most 3/4 the size of the encoded */
750 if (t >= '0' && t <= '9')
752 else if (t >= 'A' && t <= 'Z')
754 else if (t >= 'a' && t <= 'z')
768 *Data++ = (char) (ch >> 16);
769 *Data++ = (char) (ch >> 8);
779 * Create a listen server socket on the designated port.
781 static int openServer(void)
783 int n = bb_strtou(bind_addr_or_port, NULL, 10);
784 if (!errno && n && n <= 0xffff)
785 n = create_and_bind_stream_or_die(NULL, n);
787 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
793 * Log the connection closure and exit.
795 static void log_and_exit(void) ATTRIBUTE_NORETURN;
796 static void log_and_exit(void)
798 /* Paranoia. IE said to be buggy. It may send some extra data
799 * or be confused by us just exiting without SHUT_WR. Oh well. */
800 shutdown(1, SHUT_WR);
802 while (read(0, iobuf, IOBUF_SIZE) > 0)
806 bb_error_msg("closed");
807 _exit(xfunc_error_retval);
811 * Create and send HTTP response headers.
812 * The arguments are combined and sent as one write operation. Note that
813 * IE will puke big-time if the headers are not sent in one packet and the
814 * second packet is delayed for any reason.
815 * responseNum - the result code to send.
816 * Return result of write().
818 static void send_headers(HttpResponseNum responseNum)
820 static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
822 const char *responseString = "";
823 const char *infoString = NULL;
824 const char *mime_type;
826 time_t timer = time(0);
830 for (i = 0; i < ARRAY_SIZE(httpResponseNames); i++) {
831 if (httpResponseNames[i].type == responseNum) {
832 responseString = httpResponseNames[i].name;
833 infoString = httpResponseNames[i].info;
837 /* error message is HTML */
838 mime_type = responseNum == HTTP_OK ?
839 found_mime_type : "text/html";
842 bb_error_msg("response:%u", responseNum);
844 /* emit the current date */
845 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
847 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
848 "Date: %s\r\nConnection: close\r\n",
849 responseNum, responseString, mime_type, tmp_str);
851 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
852 if (responseNum == HTTP_UNAUTHORIZED) {
853 len += sprintf(iobuf + len,
854 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
858 if (responseNum == HTTP_MOVED_TEMPORARILY) {
859 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
860 found_moved_temporarily,
861 (g_query ? "?" : ""),
862 (g_query ? g_query : ""));
865 if (ContentLength != -1) { /* file */
866 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
867 len += sprintf(iobuf + len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
868 tmp_str, "Content-length:", ContentLength);
873 len += sprintf(iobuf + len,
874 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
875 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
876 responseNum, responseString,
877 responseNum, responseString, infoString);
880 fprintf(stderr, "headers: '%s'\n", iobuf);
881 if (full_write(1, iobuf, len) != len) {
883 bb_perror_msg("error");
888 static void send_headers_and_exit(HttpResponseNum responseNum) ATTRIBUTE_NORETURN;
889 static void send_headers_and_exit(HttpResponseNum responseNum)
891 send_headers(responseNum);
896 * Read from the socket until '\n' or EOF. '\r' chars are removed.
897 * '\n' is replaced with NUL.
898 * Return number of characters read or 0 if nothing is read
899 * ('\r' and '\n' are not counted).
900 * Data is returned in iobuf.
902 static int get_line(void)
909 hdr_cnt = safe_read(0, hdr_buf, sizeof(hdr_buf));
914 iobuf[count] = c = *hdr_ptr++;
923 if (count < (IOBUF_SIZE - 1)) /* check overflow */
929 #if ENABLE_FEATURE_HTTPD_CGI
930 static void setenv1(const char *name, const char *value)
932 setenv(name, value ? value : "", 1);
936 * Spawn CGI script, forward CGI's stdin/out <=> network
938 * Environment variables are set up and the script is invoked with pipes
939 * for stdin/stdout. If a post is being done the script is fed the POST
940 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
943 * const char *url The requested URL (with leading /).
944 * int bodyLen Length of the post body.
945 * const char *cookie For set HTTP_COOKIE.
946 * const char *content_type For set CONTENT_TYPE.
948 static void send_cgi_and_exit(
953 const char *content_type) ATTRIBUTE_NORETURN;
954 static void send_cgi_and_exit(
959 const char *content_type)
961 struct { int rd; int wr; } fromCgi; /* CGI -> httpd pipe */
962 struct { int rd; int wr; } toCgi; /* httpd -> CGI pipe */
971 * We are mucking with environment _first_ and then vfork/exec,
972 * this allows us to use vfork safely. Parent don't care about
973 * these environment changes anyway.
981 while ((script = strchr(script + 1, '/')) != NULL) {
982 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
986 if (!is_directory(purl + 1, 1, &sb)) {
987 /* not directory, found script.cgi/PATH_INFO */
991 *script = '/'; /* is directory, find next '/' */
993 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
994 setenv1("REQUEST_METHOD", request);
996 putenv(xasprintf("%s=%s?%s", "REQUEST_URI", purl, g_query));
998 setenv1("REQUEST_URI", purl);
1001 *script = '\0'; /* cut off /PATH_INFO */
1003 /* SCRIPT_FILENAME required by PHP in CGI mode */
1004 fullpath = concat_path_file(home_httpd, purl);
1005 setenv1("SCRIPT_FILENAME", fullpath);
1006 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1007 setenv1("SCRIPT_NAME", purl);
1008 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1009 * QUERY_STRING: The information which follows the ? in the URL
1010 * which referenced this script. This is the query information.
1011 * It should not be decoded in any fashion. This variable
1012 * should always be set when there is query information,
1013 * regardless of command line decoding. */
1014 /* (Older versions of bbox seem to do some decoding) */
1015 setenv1("QUERY_STRING", g_query);
1016 putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1017 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1018 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1019 /* Having _separate_ variables for IP and port defeats
1020 * the purpose of having socket abstraction. Which "port"
1021 * are you using on Unix domain socket?
1022 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1025 char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
1026 char *cp = strrchr(p, ':');
1027 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1029 if (cp) *cp = '\0'; /* delete :PORT */
1030 setenv1("REMOTE_ADDR", p);
1033 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1034 setenv1("REMOTE_PORT", cp + 1);
1038 setenv1("HTTP_USER_AGENT", user_agent);
1040 putenv(xasprintf("CONTENT_LENGTH=%d", bodyLen));
1042 setenv1("HTTP_COOKIE", cookie);
1044 setenv1("CONTENT_TYPE", content_type);
1045 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1047 setenv1("REMOTE_USER", remoteuser);
1048 putenv((char*)"AUTH_TYPE=Basic");
1052 setenv1("HTTP_REFERER", referer);
1059 /* TODO: log perror? */
1065 xfunc_error_retval = 242;
1067 xmove_fd(toCgi.rd, 0); /* replace stdin with the pipe */
1068 xmove_fd(fromCgi.wr, 1); /* replace stdout with the pipe */
1071 /* User seeing stderr output can be a security problem.
1072 * If CGI really wants that, it can always do dup itself. */
1075 /* script must have absolute path */
1076 script = strrchr(fullpath, '/');
1078 goto error_execing_cgi;
1080 /* chdiring to script's dir */
1081 if (chdir(fullpath) == 0) {
1083 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1084 char *interpr = NULL;
1085 char *suffix = strrchr(purl, '.');
1089 for (cur = script_i; cur; cur = cur->next) {
1090 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1091 interpr = cur->after_colon;
1098 /* set argv[0] to name without path */
1099 argv[0] = (char*)bb_basename(purl);
1101 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1103 execv(interpr, argv);
1106 execv(fullpath, argv);
1110 * (we are CGI here, our stdout is pumped to the net) */
1111 send_headers_and_exit(HTTP_NOT_FOUND);
1114 /* Parent process */
1116 /* First, restore variables possibly changed by child */
1117 xfunc_error_retval = 0;
1119 /* Prepare for pumping data.
1120 * iobuf is used for CGI -> network data,
1121 * 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 /* This loop still looks messy. What is an exit criteria?
1131 * "CGI's output closed"? Or "CGI has exited"?
1132 * What to do if CGI has closed both input and output, but
1133 * didn't exit? etc... */
1135 /* NB: breaking out of this loop jumps to log_and_exit() */
1144 FD_SET(fromCgi.rd, &readSet);
1145 if (bodyLen > 0 || hdr_cnt > 0) {
1146 FD_SET(toCgi.wr, &writeSet);
1147 nfound = toCgi.wr > fromCgi.rd ? toCgi.wr : fromCgi.rd;
1149 FD_SET(0, &readSet);
1150 /* Now wait on the set of sockets! */
1151 nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1154 close(toCgi.wr); /* no more POST data to CGI */
1157 nfound = select(fromCgi.rd + 1, &readSet, NULL, NULL, NULL);
1161 if (waitpid(pid, &status, WNOHANG) <= 0) {
1162 /* Weird. CGI didn't exit and no fd's
1163 * are ready, yet select returned?! */
1167 if (DEBUG && WIFEXITED(status))
1168 bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
1169 if (DEBUG && WIFSIGNALED(status))
1170 bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
1174 if (hdr_cnt > 0 && FD_ISSET(toCgi.wr, &writeSet)) {
1175 /* Have data from peer and can write to CGI */
1176 count = safe_write(toCgi.wr, hdr_ptr, hdr_cnt);
1177 /* Doesn't happen, we dont use nonblocking IO here
1178 *if (count < 0 && errno == EAGAIN) {
1185 hdr_cnt = bodyLen = 0; /* EOF/broken pipe to CGI */
1187 } else if (bodyLen > 0 && hdr_cnt == 0
1188 && FD_ISSET(0, &readSet)
1190 /* We expect data, prev data portion is eaten by CGI
1191 * and there *is* data to read from the peer
1193 count = bodyLen > (int)sizeof(hdr_buf) ? (int)sizeof(hdr_buf) : bodyLen;
1194 count = safe_read(0, hdr_buf, count);
1200 bodyLen = 0; /* closed */
1204 #define PIPESIZE PIPE_BUF
1205 #if PIPESIZE >= IOBUF_SIZE
1206 # error "PIPESIZE >= IOBUF_SIZE"
1208 if (FD_ISSET(fromCgi.rd, &readSet)) {
1209 /* There is something to read from CGI */
1212 /* Are we still buffering CGI output? */
1213 if (buf_count >= 0) {
1214 /* HTTP_200[] has single "\r\n" at the end.
1215 * According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1216 * CGI scripts MUST send their own header terminated by
1217 * empty line, then data. That's why we have only one
1218 * <cr><lf> pair here. We will output "200 OK" line
1219 * if needed, but CGI still has to provide blank line
1220 * between header and body */
1222 /* Must use safe_read, not full_read, because
1223 * CGI may output a few first bytes and then wait
1224 * for POSTDATA without closing stdout.
1225 * With full_read we may wait here forever. */
1226 count = safe_read(fromCgi.rd, rbuf + buf_count, PIPESIZE - 8);
1228 /* eof (or error) and there was no "HTTP",
1229 * so write it, then write received data */
1231 full_write(1, HTTP_200, sizeof(HTTP_200)-1);
1232 full_write(1, rbuf, buf_count);
1234 break; /* CGI stdout is closed, exiting */
1238 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1239 if (buf_count >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1240 /* send "HTTP/1.0 " */
1241 if (full_write(1, HTTP_200, 9) != 9)
1243 rbuf += 8; /* skip "Status: " */
1244 count = buf_count - 8;
1245 buf_count = -1; /* buffering off */
1246 } else if (buf_count >= 4) {
1247 /* Did CGI add "HTTP"? */
1248 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1249 /* there is no "HTTP", do it ourself */
1250 if (full_write(1, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1254 if (!strstr(rbuf, "ontent-")) {
1255 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1257 * Counter-example of valid CGI without Content-type:
1258 * echo -en "HTTP/1.0 302 Found\r\n"
1259 * echo -en "Location: http://www.busybox.net\r\n"
1263 buf_count = -1; /* buffering off */
1266 count = safe_read(fromCgi.rd, rbuf, PIPESIZE);
1268 break; /* eof (or error) */
1270 if (full_write(1, rbuf, count) != count)
1273 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1274 } /* if (FD_ISSET(fromCgi.rd)) */
1278 #endif /* FEATURE_HTTPD_CGI */
1281 * Send a file response to a HTTP request, and exit
1283 static void send_file_and_exit(const char *url) ATTRIBUTE_NORETURN;
1284 static void send_file_and_exit(const char *url)
1286 static const char *const suffixTable[] = {
1287 /* Warning: shorter equivalent suffix in one line must be first */
1288 ".htm.html", "text/html",
1289 ".jpg.jpeg", "image/jpeg",
1290 ".gif", "image/gif",
1291 ".png", "image/png",
1292 ".txt.h.c.cc.cpp", "text/plain",
1294 ".wav", "audio/wav",
1295 ".avi", "video/x-msvideo",
1296 ".qt.mov", "video/quicktime",
1297 ".mpe.mpeg", "video/mpeg",
1298 ".mid.midi", "audio/midi",
1299 ".mp3", "audio/mpeg",
1300 #if 0 /* unpopular */
1301 ".au", "audio/basic",
1302 ".pac", "application/x-ns-proxy-autoconfig",
1303 ".vrml.wrl", "model/vrml",
1310 const char *const *table;
1311 const char *try_suffix;
1313 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1317 suffix = strrchr(url, '.');
1319 /* If not found, set default as "application/octet-stream"; */
1320 found_mime_type = "application/octet-stream";
1322 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1325 for (table = suffixTable; *table; table += 2) {
1326 try_suffix = strstr(table[0], suffix);
1328 try_suffix += strlen(suffix);
1329 if (*try_suffix == '\0' || *try_suffix == '.') {
1330 found_mime_type = table[1];
1335 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1336 for (cur = mime_a; cur; cur = cur->next) {
1337 if (strcmp(cur->before_colon, suffix) == 0) {
1338 found_mime_type = cur->after_colon;
1346 bb_error_msg("sending file '%s' content-type: %s",
1347 url, found_mime_type);
1349 f = open(url, O_RDONLY);
1352 bb_perror_msg("cannot open '%s'", url);
1353 send_headers_and_exit(HTTP_NOT_FOUND);
1356 send_headers(HTTP_OK);
1358 /* If you want to know about EPIPE below
1359 * (happens if you abort downloads from local httpd): */
1360 signal(SIGPIPE, SIG_IGN);
1362 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1364 /* byte count (3rd arg) is rounded down to 64k */
1365 count = sendfile(1, f, &offset, MAXINT(ssize_t) - 0xffff);
1371 } while (count > 0);
1376 while ((count = safe_read(f, iobuf, IOBUF_SIZE)) > 0) {
1378 count = full_write(1, iobuf, count);
1382 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1385 if (count < 0 && verbose > 1)
1386 bb_perror_msg("error");
1390 static int checkPermIP(void)
1394 /* This could stand some work */
1395 for (cur = ip_a_d; cur; cur = cur->next) {
1398 "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1400 (unsigned char)(cur->ip >> 24),
1401 (unsigned char)(cur->ip >> 16),
1402 (unsigned char)(cur->ip >> 8),
1403 (unsigned char)(cur->ip),
1404 (unsigned char)(cur->mask >> 24),
1405 (unsigned char)(cur->mask >> 16),
1406 (unsigned char)(cur->mask >> 8),
1407 (unsigned char)(cur->mask)
1410 if ((rmt_ip & cur->mask) == cur->ip)
1411 return cur->allow_deny == 'A'; /* Allow/Deny */
1414 /* if unconfigured, return 1 - access from all */
1415 return !flg_deny_all;
1418 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1420 * Check the permission file for access password protected.
1422 * If config file isn't present, everything is allowed.
1423 * Entries are of the form you can see example from header source
1425 * path The file path.
1426 * request User information to validate.
1428 * Returns 1 if request is OK.
1430 static int checkPerm(const char *path, const char *request)
1436 const char *prev = NULL;
1438 /* This could stand some work */
1439 for (cur = g_auth; cur; cur = cur->next) {
1442 p0 = cur->before_colon;
1443 if (prev != NULL && strcmp(prev, p0) != 0)
1444 continue; /* find next identical */
1445 p = cur->after_colon;
1447 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1450 if (strncmp(p0, path, l) == 0
1451 && (l == 1 || path[l] == '/' || path[l] == '\0')
1454 /* path match found. Check request */
1455 /* for check next /path:user:password */
1457 u = strchr(request, ':');
1459 /* bad request, ':' required */
1463 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1467 if (strncmp(p, request, u - request) != 0) {
1468 /* user doesn't match */
1471 pp = strchr(p, ':');
1472 if (pp && pp[1] == '$' && pp[2] == '1'
1473 && pp[3] == '$' && pp[4]
1476 cipher = pw_encrypt(u+1, pp);
1477 if (strcmp(cipher, pp) == 0)
1478 goto set_remoteuser_var; /* Ok */
1484 if (strcmp(p, request) == 0) {
1486 remoteuser = strdup(request);
1488 remoteuser[u - request] = '\0';
1495 return prev == NULL;
1497 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1502 static void exit_on_signal(int sig) ATTRIBUTE_NORETURN;
1503 static void exit_on_signal(int sig)
1505 send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
1509 * Handle an incoming http request and exit.
1511 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr) ATTRIBUTE_NORETURN;
1512 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
1514 static const char request_GET[] ALIGN1 = "GET";
1520 int http_major_version;
1522 #if ENABLE_FEATURE_HTTPD_CGI
1523 const char *prequest;
1524 unsigned long length = 0;
1526 char *content_type = 0;
1528 struct sigaction sa;
1529 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1530 int credentials = -1; /* if not required this is Ok */
1533 /* Allocation of iobuf is postponed until now
1534 * (IOW, server process doesn't need to waste 8k) */
1535 iobuf = xmalloc(IOBUF_SIZE);
1538 if (fromAddr->sa.sa_family == AF_INET) {
1539 rmt_ip = ntohl(fromAddr->sin.sin_addr.s_addr);
1541 if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1542 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr->sa);
1545 /* this trick makes -v logging much simpler */
1546 applet_name = rmt_ip_str;
1548 bb_error_msg("connected");
1551 /* Install timeout handler */
1552 memset(&sa, 0, sizeof(sa));
1553 sa.sa_handler = exit_on_signal;
1554 /* sigemptyset(&sa.sa_mask); - memset should be enough */
1555 /*sa.sa_flags = 0; - no SA_RESTART */
1556 sigaction(SIGALRM, &sa, NULL);
1557 alarm(HEADER_READ_TIMEOUT);
1559 if (!get_line()) /* EOF or error or empty line */
1560 send_headers_and_exit(HTTP_BAD_REQUEST);
1562 /* Determine type of request (GET/POST) */
1563 urlp = strpbrk(iobuf, " \t");
1565 send_headers_and_exit(HTTP_BAD_REQUEST);
1567 #if ENABLE_FEATURE_HTTPD_CGI
1568 prequest = request_GET;
1569 if (strcasecmp(iobuf, prequest) != 0) {
1571 if (strcasecmp(iobuf, prequest) != 0)
1572 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1575 if (strcasecmp(iobuf, request_GET) != 0)
1576 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1578 urlp = skip_whitespace(urlp);
1580 send_headers_and_exit(HTTP_BAD_REQUEST);
1582 /* Find end of URL and parse HTTP version, if any */
1583 http_major_version = -1;
1584 tptr = strchrnul(urlp, ' ');
1585 /* Is it " HTTP/"? */
1586 if (tptr[0] && strncmp(tptr + 1, HTTP_200, 5) == 0)
1587 http_major_version = (tptr[6] - '0');
1590 /* Copy URL from after "GET "/"POST " to stack-allocated char[] */
1591 urlcopy = alloca((tptr - urlp) + sizeof("/index.html"));
1592 /*if (urlcopy == NULL)
1593 * send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);*/
1594 strcpy(urlcopy, urlp);
1595 /* NB: urlcopy ptr is never changed after this */
1597 /* Extract url args if present */
1598 tptr = strchr(urlcopy, '?');
1605 /* Decode URL escape sequences */
1606 tptr = decodeString(urlcopy, 0);
1608 send_headers_and_exit(HTTP_BAD_REQUEST);
1609 if (tptr == urlcopy + 1) {
1610 /* '/' or NUL is encoded */
1611 send_headers_and_exit(HTTP_NOT_FOUND);
1614 /* Canonicalize path */
1615 /* Algorithm stolen from libbb bb_simplify_path(),
1616 * but don't strdup and reducing trailing slash and protect out root */
1617 urlp = tptr = urlcopy;
1620 /* skip duplicate (or initial) slash */
1625 /* skip extra '.' */
1626 if (tptr[1] == '/' || !tptr[1]) {
1629 /* '..': be careful */
1630 if (tptr[1] == '.' && (tptr[2] == '/' || !tptr[2])) {
1632 if (urlp == urlcopy) /* protect root */
1633 send_headers_and_exit(HTTP_BAD_REQUEST);
1634 while (*--urlp != '/') /* omit previous dir */;
1641 *++urlp = '\0'; /* so keep last character */
1642 tptr = urlp; /* end ptr */
1644 /* If URL is a directory, add '/' */
1645 if (tptr[-1] != '/') {
1646 if (is_directory(urlcopy + 1, 1, &sb)) {
1647 found_moved_temporarily = urlcopy;
1653 bb_error_msg("url:%s", urlcopy);
1656 ip_allowed = checkPermIP();
1657 while (ip_allowed && (tptr = strchr(tptr + 1, '/')) != NULL) {
1658 /* have path1/path2 */
1660 if (is_directory(urlcopy + 1, 1, &sb)) {
1661 /* may be having subdir config */
1662 parse_conf(urlcopy + 1, SUBDIR_PARSE);
1663 ip_allowed = checkPermIP();
1667 if (http_major_version >= 0) {
1668 /* Request was with "... HTTP/nXXX", and n >= 0 */
1670 /* Read until blank line for HTTP version specified, else parse immediate */
1672 alarm(HEADER_READ_TIMEOUT);
1674 break; /* EOF or error or empty line */
1676 bb_error_msg("header: '%s'", iobuf);
1678 #if ENABLE_FEATURE_HTTPD_CGI
1679 /* try and do our best to parse more lines */
1680 if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
1681 /* extra read only for POST */
1682 if (prequest != request_GET) {
1683 tptr = iobuf + sizeof("Content-length:") - 1;
1685 send_headers_and_exit(HTTP_BAD_REQUEST);
1687 /* not using strtoul: it ignores leading minus! */
1688 length = strtol(tptr, &tptr, 10);
1689 /* length is "ulong", but we need to pass it to int later */
1690 /* so we check for negative or too large values in one go: */
1691 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1692 if (tptr[0] || errno || length > INT_MAX)
1693 send_headers_and_exit(HTTP_BAD_REQUEST);
1695 } else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
1696 cookie = strdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
1697 } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
1698 content_type = strdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
1699 } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
1700 referer = strdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
1701 } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
1702 user_agent = strdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
1705 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1706 if (STRNCASECMP(iobuf, "Authorization:") == 0) {
1707 /* We only allow Basic credentials.
1708 * It shows up as "Authorization: Basic <userid:password>" where
1709 * the userid:password is base64 encoded.
1711 tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
1712 if (STRNCASECMP(tptr, "Basic") != 0)
1714 tptr += sizeof("Basic")-1;
1715 /* decodeBase64() skips whitespace itself */
1717 credentials = checkPerm(urlcopy, tptr);
1719 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1720 } /* while extra header reading */
1723 /* We read headers, disable peer timeout */
1726 if (strcmp(bb_basename(urlcopy), httpd_conf) == 0 || ip_allowed == 0) {
1727 /* protect listing [/path]/httpd_conf or IP deny */
1728 send_headers_and_exit(HTTP_FORBIDDEN);
1731 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1732 if (credentials <= 0 && checkPerm(urlcopy, ":") == 0) {
1733 send_headers_and_exit(HTTP_UNAUTHORIZED);
1737 if (found_moved_temporarily) {
1738 send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
1741 tptr = urlcopy + 1; /* skip first '/' */
1743 #if ENABLE_FEATURE_HTTPD_CGI
1744 if (strncmp(tptr, "cgi-bin/", 8) == 0) {
1745 if (tptr[8] == '\0') {
1746 /* protect listing "cgi-bin/" */
1747 send_headers_and_exit(HTTP_FORBIDDEN);
1749 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1751 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1753 char *suffix = strrchr(tptr, '.');
1756 for (cur = script_i; cur; cur = cur->next) {
1757 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1758 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1764 if (prequest != request_GET) {
1765 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1767 #endif /* FEATURE_HTTPD_CGI */
1769 if (urlp[-1] == '/')
1770 strcpy(urlp, "index.html");
1771 if (stat(tptr, &sb) == 0) {
1772 /* It's a dir URL and there is index.html */
1773 ContentLength = sb.st_size;
1774 last_mod = sb.st_mtime;
1776 #if ENABLE_FEATURE_HTTPD_CGI
1777 else if (urlp[-1] == '/') {
1778 /* It's a dir URL and there is no index.html
1779 * Try cgi-bin/index.cgi */
1780 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1783 send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1788 * fall through to send_file, it errors out if open fails
1792 send_file_and_exit(tptr);
1796 * The main http server function.
1797 * Given a socket, listen for new connections and farm out
1798 * the processing as a [v]forked process.
1802 static void mini_httpd(int server_socket) ATTRIBUTE_NORETURN;
1803 static void mini_httpd(int server_socket)
1805 /* NB: it's best to not use xfuncs in this loop before fork().
1806 * Otherwise server may die on transient errors (temporary
1807 * out-of-memory condition, etc), which is Bad(tm).
1808 * Try to do any dangerous calls after fork.
1812 len_and_sockaddr fromAddr;
1814 /* Wait for connections... */
1815 fromAddr.len = LSA_SIZEOF_SA;
1816 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1820 /* set the KEEPALIVE option to cull dead connections */
1821 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1825 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1826 /* Do not reload config on HUP */
1827 signal(SIGHUP, SIG_IGN);
1829 close(server_socket);
1833 handle_incoming_and_exit(&fromAddr);
1835 /* parent, or fork failed */
1841 static void mini_httpd_nommu(int server_socket, int argc, char **argv) ATTRIBUTE_NORETURN;
1842 static void mini_httpd_nommu(int server_socket, int argc, char **argv)
1844 char *argv_copy[argc + 2];
1846 argv_copy[0] = argv[0];
1847 argv_copy[1] = (char*)"-i";
1848 memcpy(&argv_copy[2], &argv[1], argc * sizeof(argv[0]));
1850 /* NB: it's best to not use xfuncs in this loop before vfork().
1851 * Otherwise server may die on transient errors (temporary
1852 * out-of-memory condition, etc), which is Bad(tm).
1853 * Try to do any dangerous calls after fork.
1857 len_and_sockaddr fromAddr;
1859 /* Wait for connections... */
1860 fromAddr.len = LSA_SIZEOF_SA;
1861 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1865 /* set the KEEPALIVE option to cull dead connections */
1866 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1870 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1871 /* Do not reload config on HUP */
1872 signal(SIGHUP, SIG_IGN);
1874 close(server_socket);
1878 /* Run a copy of ourself in inetd mode */
1881 /* parent, or vfork failed */
1889 * Process a HTTP connection on stdin/out.
1892 static void mini_httpd_inetd(void) ATTRIBUTE_NORETURN;
1893 static void mini_httpd_inetd(void)
1895 len_and_sockaddr fromAddr;
1897 fromAddr.len = LSA_SIZEOF_SA;
1898 getpeername(0, &fromAddr.sa, &fromAddr.len);
1899 handle_incoming_and_exit(&fromAddr);
1902 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1903 static void sighup_handler(int sig)
1905 struct sigaction sa;
1907 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1909 memset(&sa, 0, sizeof(sa));
1910 sa.sa_handler = sighup_handler;
1911 /*sigemptyset(&sa.sa_mask); - memset should be enough */
1912 sa.sa_flags = SA_RESTART;
1913 sigaction(SIGHUP, &sa, NULL);
1918 c_opt_config_file = 0,
1921 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1922 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1923 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1924 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1929 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1930 OPT_DECODE_URL = 1 << d_opt_decode_url,
1931 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1932 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1933 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1934 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1935 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1936 OPT_PORT = 1 << p_opt_port,
1937 OPT_INETD = 1 << p_opt_inetd,
1938 OPT_FOREGROUND = 1 << p_opt_foreground,
1939 OPT_VERBOSE = 1 << p_opt_verbose,
1943 int httpd_main(int argc, char **argv);
1944 int httpd_main(int argc, char **argv)
1946 int server_socket = server_socket; /* for gcc */
1948 char *url_for_decode;
1949 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1950 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1951 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1952 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1956 #if ENABLE_LOCALE_SUPPORT
1957 /* Undo busybox.c: we want to speak English in http (dates etc) */
1958 setlocale(LC_TIME, "C");
1961 home_httpd = xrealloc_getcwd_or_warn(NULL);
1962 /* -v counts, -i implies -f */
1963 opt_complementary = "vv:if";
1964 /* We do not "absolutize" path given by -h (home) opt.
1965 * If user gives relative path in -h, $SCRIPT_FILENAME can end up
1967 opt = getopt32(argv, "c:d:h:"
1968 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1969 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1970 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1971 USE_FEATURE_HTTPD_SETUID("u:")
1973 &configFile, &url_for_decode, &home_httpd
1974 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1975 USE_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
1976 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1977 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1978 , &bind_addr_or_port
1981 if (opt & OPT_DECODE_URL) {
1982 fputs(decodeString(url_for_decode, 1), stdout);
1985 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1986 if (opt & OPT_ENCODE_URL) {
1987 fputs(encodeString(url_for_encode), stdout);
1991 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1992 if (opt & OPT_MD5) {
1993 puts(pw_encrypt(pass, "$1$"));
1997 #if ENABLE_FEATURE_HTTPD_SETUID
1998 if (opt & OPT_SETUID) {
1999 if (!get_uidgid(&ugid, s_ugid, 1))
2000 bb_error_msg_and_die("unrecognized user[:group] "
2001 "name '%s'", s_ugid);
2006 if (!(opt & OPT_FOREGROUND)) {
2007 bb_daemonize_or_rexec(0, argv); /* don't change current directory */
2012 if (!(opt & OPT_INETD)) {
2013 signal(SIGCHLD, SIG_IGN);
2014 server_socket = openServer();
2015 #if ENABLE_FEATURE_HTTPD_SETUID
2016 /* drop privileges */
2017 if (opt & OPT_SETUID) {
2018 if (ugid.gid != (gid_t)-1) {
2019 if (setgroups(1, &ugid.gid) == -1)
2020 bb_perror_msg_and_die("setgroups");
2028 #if ENABLE_FEATURE_HTTPD_CGI
2030 char *p = getenv("PATH");
2031 /* env strings themself are not freed, no need to strdup(p): */
2035 // if (!(opt & OPT_INETD))
2036 // setenv_long("SERVER_PORT", ???);
2040 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2041 if (!(opt & OPT_INETD))
2043 else /* do not install HUP handler in inetd mode */
2045 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2047 xfunc_error_retval = 0;
2048 if (opt & OPT_INETD)
2051 if (!(opt & OPT_FOREGROUND))
2052 bb_daemonize(0); /* don't change current directory */
2053 mini_httpd(server_socket); /* never returns */
2055 mini_httpd_nommu(server_socket, argc, argv); /* never returns */