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);
293 //#define isdigit(a) ((unsigned)((a) - '0') <= 9)
294 //#define notdigit(a) ((unsigned)((a) - '0') > 9)
296 /* Returns presumed mask width in bits or < 0 on error.
297 * Updates strp, stores IP at provided pointer */
298 static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
300 const char *p = *strp;
308 for (j = 0; j < 4; j++) {
311 if ((*p < '0' || *p > '9') && *p != '/' && *p)
314 while (*p >= '0' && *p <= '9') {
325 ip = (ip << 8) | octet;
339 /* Returns 0 on success. Stores IP and mask at provided pointers */
340 static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
346 i = scan_ip(&str, ipp, '/');
351 /* there is /xxx after dotted-IP address */
352 i = bb_strtou(str, &p, 10);
354 /* 'xxx' itself is dotted-IP mask, parse it */
355 /* (return 0 (success) only if it has N.N.N.N form) */
356 return scan_ip(&str, maskp, '\0') - 32;
365 if (sizeof(unsigned) == 4 && i == 32) {
366 /* mask >>= 32 below may not work */
372 /* i == 0 -> *maskp = 0x00000000
373 * i == 1 -> *maskp = 0x80000000
374 * i == 4 -> *maskp = 0xf0000000
375 * i == 31 -> *maskp = 0xfffffffe
376 * i == 32 -> *maskp = 0xffffffff */
377 *maskp = (uint32_t)(~mask);
382 * Parse configuration file into in-memory linked list.
384 * The first non-white character is examined to determine if the config line
385 * is one of the following:
386 * .ext:mime/type # new mime type not compiled into httpd
387 * [adAD]:from # ip address allow/deny, * for wildcard
388 * /path:user:pass # username/password
390 * Any previous IP rules are discarded.
391 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
392 * are also discarded. That is, previous settings are retained if flag is
395 * path Path where to look for httpd.conf (without filename).
396 * flag Type of the parse request.
399 #define FIRST_PARSE 0
400 #define SUBDIR_PARSE 1
401 #define SIGNALED_PARSE 2
402 #define FIND_FROM_HTTPD_ROOT 3
403 static void parse_conf(const char *path, int flag)
406 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
409 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
410 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
411 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
414 const char *cf = configFile;
420 /* discard old rules */
421 free_Htaccess_IP_list(&ip_a_d);
423 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
424 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
425 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
426 /* retain previous auth and mime config only for subdir parse */
427 if (flag != SUBDIR_PARSE) {
428 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
429 free_Htaccess_list(&g_auth);
431 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
432 free_Htaccess_list(&mime_a);
434 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
435 free_Htaccess_list(&script_i);
440 if (flag == SUBDIR_PARSE || cf == NULL) {
441 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
443 if (flag == FIRST_PARSE)
444 bb_error_msg_and_die(bb_msg_memory_exhausted);
447 sprintf((char *)cf, "%s/%s", path, httpd_conf);
450 while ((f = fopen(cf, "r")) == NULL) {
451 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
452 /* config file not found, no changes to config */
455 if (configFile && flag == FIRST_PARSE) /* if -c option given */
456 bb_perror_msg_and_die("%s", cf);
457 flag = FIND_FROM_HTTPD_ROOT;
461 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
464 /* This could stand some work */
465 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
467 for (p = p0; *p0 != '\0' && *p0 != '#'; p0++) {
470 if (*p0 == ':' && c == NULL)
476 /* test for empty or strange line */
477 if (c == NULL || *c == '\0')
484 /* memorize deny all */
487 /* skip default other "word:*" config lines */
493 else if (*p0 != 'D' && *p0 != 'A'
494 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
497 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
500 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
505 if (*p0 == 'A' || *p0 == 'D') {
506 /* storing current config IP line */
507 pip = xzalloc(sizeof(Htaccess_IP));
509 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
510 /* syntax IP{/mask} error detected, protect all */
514 pip->allow_deny = *p0;
516 /* Deny:from_IP move top */
520 /* add to bottom A:form_IP config line */
521 Htaccess_IP *prev_IP = ip_a_d;
523 if (prev_IP == NULL) {
526 while (prev_IP->next)
527 prev_IP = prev_IP->next;
534 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
536 /* make full path from httpd root / current_path / config_line_path */
537 cf = (flag == SUBDIR_PARSE ? path : "");
538 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
542 sprintf(p0, "/%s%s", cf, buf);
544 /* another call bb_simplify_path */
549 if (*cf == '/') { /* skip duplicate (or initial) slash */
551 } else if (*cf == '.') {
552 if (cf[1] == '/' || cf[1] == '\0') { /* remove extra '.' */
554 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == '\0')) {
557 while (*--p != '/') /* omit previous dir */;
566 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
567 ++p; /* so keep last character */
570 sprintf(p0, "%s:%s", p0, c);
574 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
575 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
576 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
577 /* storing current config line */
578 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
580 cf = strcpy(cur->before_colon, p0);
583 cur->after_colon = c;
584 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
586 /* config .mime line move top for overwrite previous */
592 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
593 if (*cf == '*' && cf[1] == '.') {
594 /* config script interpreter line move top for overwrite previous */
595 cur->next = script_i;
600 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
606 /* sort path, if current lenght eq or bigger then move up */
607 Htaccess *prev_hti = g_auth;
608 size_t l = strlen(cf);
611 for (hti = prev_hti; hti; hti = hti->next) {
612 if (l >= strlen(hti->before_colon)) {
613 /* insert before hti */
615 if (prev_hti != hti) {
616 prev_hti->next = cur;
624 prev_hti = prev_hti->next;
626 if (!hti) { /* not inserted, add to bottom */
638 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
640 * Given a string, html-encode special characters.
641 * This is used for the -e command line option to provide an easy way
642 * for scripts to encode result data without confusing browsers. The
643 * returned string pointer is memory allocated by malloc().
645 * Returns a pointer to the encoded string (malloced).
647 static char *encodeString(const char *string)
649 /* take the simple route and encode everything */
650 /* could possibly scan once to get length. */
651 int len = strlen(string);
652 char *out = xmalloc(len * 6 + 1);
656 while ((ch = *string++)) {
657 // very simple check for what to encode
658 if (isalnum(ch)) *p++ = ch;
659 else p += sprintf(p, "&#%d;", (unsigned char) ch);
664 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
667 * Given a URL encoded string, convert it to plain ascii.
668 * Since decoding always makes strings smaller, the decode is done in-place.
669 * Thus, callers should strdup() the argument if they do not want the
670 * argument modified. The return is the original pointer, allowing this
671 * function to be easily used as arguments to other functions.
673 * string The first string to decode.
674 * option_d 1 if called for httpd -d
676 * Returns a pointer to the decoded string (same as input).
678 static unsigned hex_to_bin(unsigned char c)
680 unsigned v = c | 0x20; /* lowercase */
690 void t(char c) { printf("'%c' %u\n", c, hex_to_bin(c)); }
691 int main() { t('0'); t('9'); t('A'); t('F'); t('a'); t('f');
692 t('0'-1); t('9'+1); t('A'-1); t('F'+1); t('a'-1); t('f'+1); return 0; }
694 static char *decodeString(char *orig, int option_d)
696 /* note that decoded string is always shorter than original */
701 while ((c = *ptr++) != '\0') {
704 if (option_d && c == '+') {
712 v = hex_to_bin(ptr[0]);
720 v = (v * 16) | hex_to_bin(ptr[1]);
723 if (!option_d && (v == '/' || v == '\0')) {
724 /* caller takes it as indication of invalid
725 * (dangerous wrt exploits) chars */
735 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
737 * Decode a base64 data stream as per rfc1521.
738 * Note that the rfc states that non base64 chars are to be ignored.
739 * Since the decode always results in a shorter size than the input,
740 * it is OK to pass the input arg as an output arg.
741 * Parameter: a pointer to a base64 encoded string.
742 * Decoded data is stored in-place.
744 static void decodeBase64(char *Data)
746 const unsigned char *in = (const unsigned char *)Data;
747 /* The decoded size will be at most 3/4 the size of the encoded */
754 if (t >= '0' && t <= '9')
756 else if (t >= 'A' && t <= 'Z')
758 else if (t >= 'a' && t <= 'z')
772 *Data++ = (char) (ch >> 16);
773 *Data++ = (char) (ch >> 8);
783 * Create a listen server socket on the designated port.
785 static int openServer(void)
787 int n = bb_strtou(bind_addr_or_port, NULL, 10);
788 if (!errno && n && n <= 0xffff)
789 n = create_and_bind_stream_or_die(NULL, n);
791 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
797 * Log the connection closure and exit.
799 static void log_and_exit(void) ATTRIBUTE_NORETURN;
800 static void log_and_exit(void)
802 /* Paranoia. IE said to be buggy. It may send some extra data
803 * or be confused by us just exiting without SHUT_WR. Oh well. */
804 shutdown(1, SHUT_WR);
806 while (read(0, iobuf, IOBUF_SIZE) > 0)
810 bb_error_msg("closed");
811 _exit(xfunc_error_retval);
815 * Create and send HTTP response headers.
816 * The arguments are combined and sent as one write operation. Note that
817 * IE will puke big-time if the headers are not sent in one packet and the
818 * second packet is delayed for any reason.
819 * responseNum - the result code to send.
820 * Return result of write().
822 static void send_headers(HttpResponseNum responseNum)
824 static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
826 const char *responseString = "";
827 const char *infoString = NULL;
828 const char *mime_type;
830 time_t timer = time(0);
834 for (i = 0; i < ARRAY_SIZE(httpResponseNames); i++) {
835 if (httpResponseNames[i].type == responseNum) {
836 responseString = httpResponseNames[i].name;
837 infoString = httpResponseNames[i].info;
841 /* error message is HTML */
842 mime_type = responseNum == HTTP_OK ?
843 found_mime_type : "text/html";
846 bb_error_msg("response:%u", responseNum);
848 /* emit the current date */
849 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
851 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
852 "Date: %s\r\nConnection: close\r\n",
853 responseNum, responseString, mime_type, tmp_str);
855 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
856 if (responseNum == HTTP_UNAUTHORIZED) {
857 len += sprintf(iobuf + len,
858 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
862 if (responseNum == HTTP_MOVED_TEMPORARILY) {
863 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
864 found_moved_temporarily,
865 (g_query ? "?" : ""),
866 (g_query ? g_query : ""));
869 if (ContentLength != -1) { /* file */
870 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
871 len += sprintf(iobuf + len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
872 tmp_str, "Content-length:", ContentLength);
877 len += sprintf(iobuf + len,
878 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
879 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
880 responseNum, responseString,
881 responseNum, responseString, infoString);
884 fprintf(stderr, "headers: '%s'\n", iobuf);
885 if (full_write(1, iobuf, len) != len) {
887 bb_perror_msg("error");
892 static void send_headers_and_exit(HttpResponseNum responseNum) ATTRIBUTE_NORETURN;
893 static void send_headers_and_exit(HttpResponseNum responseNum)
895 send_headers(responseNum);
900 * Read from the socket until '\n' or EOF. '\r' chars are removed.
901 * '\n' is replaced with NUL.
902 * Return number of characters read or 0 if nothing is read
903 * ('\r' and '\n' are not counted).
904 * Data is returned in iobuf.
906 static int get_line(void)
913 hdr_cnt = safe_read(0, hdr_buf, sizeof(hdr_buf));
918 iobuf[count] = c = *hdr_ptr++;
927 if (count < (IOBUF_SIZE - 1)) /* check overflow */
933 #if ENABLE_FEATURE_HTTPD_CGI
934 static void setenv1(const char *name, const char *value)
936 setenv(name, value ? value : "", 1);
940 * Spawn CGI script, forward CGI's stdin/out <=> network
942 * Environment variables are set up and the script is invoked with pipes
943 * for stdin/stdout. If a post is being done the script is fed the POST
944 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
947 * const char *url The requested URL (with leading /).
948 * int bodyLen Length of the post body.
949 * const char *cookie For set HTTP_COOKIE.
950 * const char *content_type For set CONTENT_TYPE.
952 static void send_cgi_and_exit(
957 const char *content_type) ATTRIBUTE_NORETURN;
958 static void send_cgi_and_exit(
963 const char *content_type)
965 struct { int rd; int wr; } fromCgi; /* CGI -> httpd pipe */
966 struct { int rd; int wr; } toCgi; /* httpd -> CGI pipe */
975 * We are mucking with environment _first_ and then vfork/exec,
976 * this allows us to use vfork safely. Parent don't care about
977 * these environment changes anyway.
985 while ((script = strchr(script + 1, '/')) != NULL) {
986 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
990 if (!is_directory(purl + 1, 1, &sb)) {
991 /* not directory, found script.cgi/PATH_INFO */
995 *script = '/'; /* is directory, find next '/' */
997 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
998 setenv1("REQUEST_METHOD", request);
1000 putenv(xasprintf("%s=%s?%s", "REQUEST_URI", purl, g_query));
1002 setenv1("REQUEST_URI", purl);
1005 *script = '\0'; /* cut off /PATH_INFO */
1007 /* SCRIPT_FILENAME required by PHP in CGI mode */
1008 fullpath = concat_path_file(home_httpd, purl);
1009 setenv1("SCRIPT_FILENAME", fullpath);
1010 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1011 setenv1("SCRIPT_NAME", purl);
1012 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1013 * QUERY_STRING: The information which follows the ? in the URL
1014 * which referenced this script. This is the query information.
1015 * It should not be decoded in any fashion. This variable
1016 * should always be set when there is query information,
1017 * regardless of command line decoding. */
1018 /* (Older versions of bbox seem to do some decoding) */
1019 setenv1("QUERY_STRING", g_query);
1020 putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1021 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1022 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1023 /* Having _separate_ variables for IP and port defeats
1024 * the purpose of having socket abstraction. Which "port"
1025 * are you using on Unix domain socket?
1026 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1029 char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
1030 char *cp = strrchr(p, ':');
1031 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1033 if (cp) *cp = '\0'; /* delete :PORT */
1034 setenv1("REMOTE_ADDR", p);
1037 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1038 setenv1("REMOTE_PORT", cp + 1);
1042 setenv1("HTTP_USER_AGENT", user_agent);
1044 putenv(xasprintf("CONTENT_LENGTH=%d", bodyLen));
1046 setenv1("HTTP_COOKIE", cookie);
1048 setenv1("CONTENT_TYPE", content_type);
1049 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1051 setenv1("REMOTE_USER", remoteuser);
1052 putenv((char*)"AUTH_TYPE=Basic");
1056 setenv1("HTTP_REFERER", referer);
1063 /* TODO: log perror? */
1069 xfunc_error_retval = 242;
1071 xmove_fd(toCgi.rd, 0); /* replace stdin with the pipe */
1072 xmove_fd(fromCgi.wr, 1); /* replace stdout with the pipe */
1075 /* User seeing stderr output can be a security problem.
1076 * If CGI really wants that, it can always do dup itself. */
1079 /* script must have absolute path */
1080 script = strrchr(fullpath, '/');
1082 goto error_execing_cgi;
1084 /* chdiring to script's dir */
1085 if (chdir(fullpath) == 0) {
1087 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1088 char *interpr = NULL;
1089 char *suffix = strrchr(purl, '.');
1093 for (cur = script_i; cur; cur = cur->next) {
1094 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1095 interpr = cur->after_colon;
1102 /* set argv[0] to name without path */
1103 argv[0] = (char*)bb_basename(purl);
1105 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1107 execv(interpr, argv);
1110 execv(fullpath, argv);
1114 * (we are CGI here, our stdout is pumped to the net) */
1115 send_headers_and_exit(HTTP_NOT_FOUND);
1118 /* Parent process */
1120 /* First, restore variables possibly changed by child */
1121 xfunc_error_retval = 0;
1123 /* Prepare for pumping data.
1124 * iobuf is used for CGI -> network data,
1125 * hdr_buf is for network -> CGI data (POSTDATA) */
1130 /* If CGI dies, we still want to correctly finish reading its output
1131 * and send it to the peer. So please no SIGPIPEs! */
1132 signal(SIGPIPE, SIG_IGN);
1134 /* This loop still looks messy. What is an exit criteria?
1135 * "CGI's output closed"? Or "CGI has exited"?
1136 * What to do if CGI has closed both input and output, but
1137 * didn't exit? etc... */
1139 /* NB: breaking out of this loop jumps to log_and_exit() */
1148 FD_SET(fromCgi.rd, &readSet);
1149 if (bodyLen > 0 || hdr_cnt > 0) {
1150 FD_SET(toCgi.wr, &writeSet);
1151 nfound = toCgi.wr > fromCgi.rd ? toCgi.wr : fromCgi.rd;
1153 FD_SET(0, &readSet);
1154 /* Now wait on the set of sockets! */
1155 nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1158 close(toCgi.wr); /* no more POST data to CGI */
1161 nfound = select(fromCgi.rd + 1, &readSet, NULL, NULL, NULL);
1165 if (waitpid(pid, &status, WNOHANG) <= 0) {
1166 /* Weird. CGI didn't exit and no fd's
1167 * are ready, yet select returned?! */
1171 if (DEBUG && WIFEXITED(status))
1172 bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
1173 if (DEBUG && WIFSIGNALED(status))
1174 bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
1178 if (hdr_cnt > 0 && FD_ISSET(toCgi.wr, &writeSet)) {
1179 /* Have data from peer and can write to CGI */
1180 count = safe_write(toCgi.wr, hdr_ptr, hdr_cnt);
1181 /* Doesn't happen, we dont use nonblocking IO here
1182 *if (count < 0 && errno == EAGAIN) {
1189 hdr_cnt = bodyLen = 0; /* EOF/broken pipe to CGI */
1191 } else if (bodyLen > 0 && hdr_cnt == 0
1192 && FD_ISSET(0, &readSet)
1194 /* We expect data, prev data portion is eaten by CGI
1195 * and there *is* data to read from the peer
1197 count = bodyLen > (int)sizeof(hdr_buf) ? (int)sizeof(hdr_buf) : bodyLen;
1198 count = safe_read(0, hdr_buf, count);
1204 bodyLen = 0; /* closed */
1208 #define PIPESIZE PIPE_BUF
1209 #if PIPESIZE >= IOBUF_SIZE
1210 # error "PIPESIZE >= IOBUF_SIZE"
1212 if (FD_ISSET(fromCgi.rd, &readSet)) {
1213 /* There is something to read from CGI */
1216 /* Are we still buffering CGI output? */
1217 if (buf_count >= 0) {
1218 /* HTTP_200[] has single "\r\n" at the end.
1219 * According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1220 * CGI scripts MUST send their own header terminated by
1221 * empty line, then data. That's why we have only one
1222 * <cr><lf> pair here. We will output "200 OK" line
1223 * if needed, but CGI still has to provide blank line
1224 * between header and body */
1226 /* Must use safe_read, not full_read, because
1227 * CGI may output a few first bytes and then wait
1228 * for POSTDATA without closing stdout.
1229 * With full_read we may wait here forever. */
1230 count = safe_read(fromCgi.rd, rbuf + buf_count, PIPESIZE - 8);
1232 /* eof (or error) and there was no "HTTP",
1233 * so write it, then write received data */
1235 full_write(1, HTTP_200, sizeof(HTTP_200)-1);
1236 full_write(1, rbuf, buf_count);
1238 break; /* CGI stdout is closed, exiting */
1242 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1243 if (buf_count >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1244 /* send "HTTP/1.0 " */
1245 if (full_write(1, HTTP_200, 9) != 9)
1247 rbuf += 8; /* skip "Status: " */
1248 count = buf_count - 8;
1249 buf_count = -1; /* buffering off */
1250 } else if (buf_count >= 4) {
1251 /* Did CGI add "HTTP"? */
1252 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1253 /* there is no "HTTP", do it ourself */
1254 if (full_write(1, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1258 if (!strstr(rbuf, "ontent-")) {
1259 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1261 * Counter-example of valid CGI without Content-type:
1262 * echo -en "HTTP/1.0 302 Found\r\n"
1263 * echo -en "Location: http://www.busybox.net\r\n"
1267 buf_count = -1; /* buffering off */
1270 count = safe_read(fromCgi.rd, rbuf, PIPESIZE);
1272 break; /* eof (or error) */
1274 if (full_write(1, rbuf, count) != count)
1277 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1278 } /* if (FD_ISSET(fromCgi.rd)) */
1282 #endif /* FEATURE_HTTPD_CGI */
1285 * Send a file response to a HTTP request, and exit
1287 static void send_file_and_exit(const char *url) ATTRIBUTE_NORETURN;
1288 static void send_file_and_exit(const char *url)
1290 static const char *const suffixTable[] = {
1291 /* Warning: shorter equivalent suffix in one line must be first */
1292 ".htm.html", "text/html",
1293 ".jpg.jpeg", "image/jpeg",
1294 ".gif", "image/gif",
1295 ".png", "image/png",
1296 ".txt.h.c.cc.cpp", "text/plain",
1298 ".wav", "audio/wav",
1299 ".avi", "video/x-msvideo",
1300 ".qt.mov", "video/quicktime",
1301 ".mpe.mpeg", "video/mpeg",
1302 ".mid.midi", "audio/midi",
1303 ".mp3", "audio/mpeg",
1304 #if 0 /* unpopular */
1305 ".au", "audio/basic",
1306 ".pac", "application/x-ns-proxy-autoconfig",
1307 ".vrml.wrl", "model/vrml",
1314 const char *const *table;
1315 const char *try_suffix;
1317 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1321 suffix = strrchr(url, '.');
1323 /* If not found, set default as "application/octet-stream"; */
1324 found_mime_type = "application/octet-stream";
1326 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1329 for (table = suffixTable; *table; table += 2) {
1330 try_suffix = strstr(table[0], suffix);
1332 try_suffix += strlen(suffix);
1333 if (*try_suffix == '\0' || *try_suffix == '.') {
1334 found_mime_type = table[1];
1339 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1340 for (cur = mime_a; cur; cur = cur->next) {
1341 if (strcmp(cur->before_colon, suffix) == 0) {
1342 found_mime_type = cur->after_colon;
1350 bb_error_msg("sending file '%s' content-type: %s",
1351 url, found_mime_type);
1353 f = open(url, O_RDONLY);
1356 bb_perror_msg("cannot open '%s'", url);
1357 send_headers_and_exit(HTTP_NOT_FOUND);
1360 send_headers(HTTP_OK);
1362 /* If you want to know about EPIPE below
1363 * (happens if you abort downloads from local httpd): */
1364 signal(SIGPIPE, SIG_IGN);
1366 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1368 /* byte count (3rd arg) is rounded down to 64k */
1369 count = sendfile(1, f, &offset, MAXINT(ssize_t) - 0xffff);
1375 } while (count > 0);
1380 while ((count = safe_read(f, iobuf, IOBUF_SIZE)) > 0) {
1382 count = full_write(1, iobuf, count);
1386 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1389 if (count < 0 && verbose > 1)
1390 bb_perror_msg("error");
1394 static int checkPermIP(void)
1398 /* This could stand some work */
1399 for (cur = ip_a_d; cur; cur = cur->next) {
1402 "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1404 (unsigned char)(cur->ip >> 24),
1405 (unsigned char)(cur->ip >> 16),
1406 (unsigned char)(cur->ip >> 8),
1407 (unsigned char)(cur->ip),
1408 (unsigned char)(cur->mask >> 24),
1409 (unsigned char)(cur->mask >> 16),
1410 (unsigned char)(cur->mask >> 8),
1411 (unsigned char)(cur->mask)
1414 if ((rmt_ip & cur->mask) == cur->ip)
1415 return cur->allow_deny == 'A'; /* Allow/Deny */
1418 /* if unconfigured, return 1 - access from all */
1419 return !flg_deny_all;
1422 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1424 * Check the permission file for access password protected.
1426 * If config file isn't present, everything is allowed.
1427 * Entries are of the form you can see example from header source
1429 * path The file path.
1430 * request User information to validate.
1432 * Returns 1 if request is OK.
1434 static int checkPerm(const char *path, const char *request)
1440 const char *prev = NULL;
1442 /* This could stand some work */
1443 for (cur = g_auth; cur; cur = cur->next) {
1446 p0 = cur->before_colon;
1447 if (prev != NULL && strcmp(prev, p0) != 0)
1448 continue; /* find next identical */
1449 p = cur->after_colon;
1451 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1454 if (strncmp(p0, path, l) == 0
1455 && (l == 1 || path[l] == '/' || path[l] == '\0')
1458 /* path match found. Check request */
1459 /* for check next /path:user:password */
1461 u = strchr(request, ':');
1463 /* bad request, ':' required */
1467 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1471 if (strncmp(p, request, u - request) != 0) {
1472 /* user doesn't match */
1475 pp = strchr(p, ':');
1476 if (pp && pp[1] == '$' && pp[2] == '1'
1477 && pp[3] == '$' && pp[4]
1480 cipher = pw_encrypt(u+1, pp);
1481 if (strcmp(cipher, pp) == 0)
1482 goto set_remoteuser_var; /* Ok */
1488 if (strcmp(p, request) == 0) {
1490 remoteuser = strdup(request);
1492 remoteuser[u - request] = '\0';
1499 return prev == NULL;
1501 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1506 static void exit_on_signal(int sig) ATTRIBUTE_NORETURN;
1507 static void exit_on_signal(int sig)
1509 send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
1513 * Handle an incoming http request and exit.
1515 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr) ATTRIBUTE_NORETURN;
1516 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
1518 static const char request_GET[] ALIGN1 = "GET";
1524 int http_major_version;
1526 #if ENABLE_FEATURE_HTTPD_CGI
1527 const char *prequest;
1528 unsigned long length = 0;
1530 char *content_type = 0;
1532 struct sigaction sa;
1533 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1534 int credentials = -1; /* if not required this is Ok */
1537 /* Allocation of iobuf is postponed until now
1538 * (IOW, server process doesn't need to waste 8k) */
1539 iobuf = xmalloc(IOBUF_SIZE);
1542 if (fromAddr->sa.sa_family == AF_INET) {
1543 rmt_ip = ntohl(fromAddr->sin.sin_addr.s_addr);
1545 if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1546 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr->sa);
1549 /* this trick makes -v logging much simpler */
1550 applet_name = rmt_ip_str;
1552 bb_error_msg("connected");
1555 /* Install timeout handler */
1556 memset(&sa, 0, sizeof(sa));
1557 sa.sa_handler = exit_on_signal;
1558 /* sigemptyset(&sa.sa_mask); - memset should be enough */
1559 /*sa.sa_flags = 0; - no SA_RESTART */
1560 sigaction(SIGALRM, &sa, NULL);
1561 alarm(HEADER_READ_TIMEOUT);
1563 if (!get_line()) /* EOF or error or empty line */
1564 send_headers_and_exit(HTTP_BAD_REQUEST);
1566 /* Determine type of request (GET/POST) */
1567 urlp = strpbrk(iobuf, " \t");
1569 send_headers_and_exit(HTTP_BAD_REQUEST);
1571 #if ENABLE_FEATURE_HTTPD_CGI
1572 prequest = request_GET;
1573 if (strcasecmp(iobuf, prequest) != 0) {
1575 if (strcasecmp(iobuf, prequest) != 0)
1576 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1579 if (strcasecmp(iobuf, request_GET) != 0)
1580 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1582 urlp = skip_whitespace(urlp);
1584 send_headers_and_exit(HTTP_BAD_REQUEST);
1586 /* Find end of URL and parse HTTP version, if any */
1587 http_major_version = -1;
1588 tptr = strchrnul(urlp, ' ');
1589 /* Is it " HTTP/"? */
1590 if (tptr[0] && strncmp(tptr + 1, HTTP_200, 5) == 0)
1591 http_major_version = (tptr[6] - '0');
1594 /* Copy URL from after "GET "/"POST " to stack-allocated char[] */
1595 urlcopy = alloca((tptr - urlp) + sizeof("/index.html"));
1596 /*if (urlcopy == NULL)
1597 * send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);*/
1598 strcpy(urlcopy, urlp);
1599 /* NB: urlcopy ptr is never changed after this */
1601 /* Extract url args if present */
1602 tptr = strchr(urlcopy, '?');
1609 /* Decode URL escape sequences */
1610 tptr = decodeString(urlcopy, 0);
1612 send_headers_and_exit(HTTP_BAD_REQUEST);
1613 if (tptr == urlcopy + 1) {
1614 /* '/' or NUL is encoded */
1615 send_headers_and_exit(HTTP_NOT_FOUND);
1618 /* Canonicalize path */
1619 /* Algorithm stolen from libbb bb_simplify_path(),
1620 * but don't strdup and reducing trailing slash and protect out root */
1621 urlp = tptr = urlcopy;
1624 /* skip duplicate (or initial) slash */
1629 /* skip extra '.' */
1630 if (tptr[1] == '/' || !tptr[1]) {
1633 /* '..': be careful */
1634 if (tptr[1] == '.' && (tptr[2] == '/' || !tptr[2])) {
1636 if (urlp == urlcopy) /* protect root */
1637 send_headers_and_exit(HTTP_BAD_REQUEST);
1638 while (*--urlp != '/') /* omit previous dir */;
1645 *++urlp = '\0'; /* so keep last character */
1646 tptr = urlp; /* end ptr */
1648 /* If URL is a directory, add '/' */
1649 if (tptr[-1] != '/') {
1650 if (is_directory(urlcopy + 1, 1, &sb)) {
1651 found_moved_temporarily = urlcopy;
1657 bb_error_msg("url:%s", urlcopy);
1660 ip_allowed = checkPermIP();
1661 while (ip_allowed && (tptr = strchr(tptr + 1, '/')) != NULL) {
1662 /* have path1/path2 */
1664 if (is_directory(urlcopy + 1, 1, &sb)) {
1665 /* may be having subdir config */
1666 parse_conf(urlcopy + 1, SUBDIR_PARSE);
1667 ip_allowed = checkPermIP();
1671 if (http_major_version >= 0) {
1672 /* Request was with "... HTTP/nXXX", and n >= 0 */
1674 /* Read until blank line for HTTP version specified, else parse immediate */
1676 alarm(HEADER_READ_TIMEOUT);
1678 break; /* EOF or error or empty line */
1680 bb_error_msg("header: '%s'", iobuf);
1682 #if ENABLE_FEATURE_HTTPD_CGI
1683 /* try and do our best to parse more lines */
1684 if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
1685 /* extra read only for POST */
1686 if (prequest != request_GET) {
1687 tptr = iobuf + sizeof("Content-length:") - 1;
1689 send_headers_and_exit(HTTP_BAD_REQUEST);
1691 /* not using strtoul: it ignores leading minus! */
1692 length = strtol(tptr, &tptr, 10);
1693 /* length is "ulong", but we need to pass it to int later */
1694 /* so we check for negative or too large values in one go: */
1695 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1696 if (tptr[0] || errno || length > INT_MAX)
1697 send_headers_and_exit(HTTP_BAD_REQUEST);
1699 } else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
1700 cookie = strdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
1701 } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
1702 content_type = strdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
1703 } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
1704 referer = strdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
1705 } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
1706 user_agent = strdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
1709 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1710 if (STRNCASECMP(iobuf, "Authorization:") == 0) {
1711 /* We only allow Basic credentials.
1712 * It shows up as "Authorization: Basic <userid:password>" where
1713 * the userid:password is base64 encoded.
1715 tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
1716 if (STRNCASECMP(tptr, "Basic") != 0)
1718 tptr += sizeof("Basic")-1;
1719 /* decodeBase64() skips whitespace itself */
1721 credentials = checkPerm(urlcopy, tptr);
1723 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1724 } /* while extra header reading */
1727 /* We read headers, disable peer timeout */
1730 if (strcmp(bb_basename(urlcopy), httpd_conf) == 0 || ip_allowed == 0) {
1731 /* protect listing [/path]/httpd_conf or IP deny */
1732 send_headers_and_exit(HTTP_FORBIDDEN);
1735 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1736 if (credentials <= 0 && checkPerm(urlcopy, ":") == 0) {
1737 send_headers_and_exit(HTTP_UNAUTHORIZED);
1741 if (found_moved_temporarily) {
1742 send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
1745 tptr = urlcopy + 1; /* skip first '/' */
1747 #if ENABLE_FEATURE_HTTPD_CGI
1748 if (strncmp(tptr, "cgi-bin/", 8) == 0) {
1749 if (tptr[8] == '\0') {
1750 /* protect listing "cgi-bin/" */
1751 send_headers_and_exit(HTTP_FORBIDDEN);
1753 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1755 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1757 char *suffix = strrchr(tptr, '.');
1760 for (cur = script_i; cur; cur = cur->next) {
1761 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1762 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1768 if (prequest != request_GET) {
1769 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1771 #endif /* FEATURE_HTTPD_CGI */
1773 if (urlp[-1] == '/')
1774 strcpy(urlp, "index.html");
1775 if (stat(tptr, &sb) == 0) {
1776 /* It's a dir URL and there is index.html */
1777 ContentLength = sb.st_size;
1778 last_mod = sb.st_mtime;
1780 #if ENABLE_FEATURE_HTTPD_CGI
1781 else if (urlp[-1] == '/') {
1782 /* It's a dir URL and there is no index.html
1783 * Try cgi-bin/index.cgi */
1784 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1787 send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1792 * fall through to send_file, it errors out if open fails
1796 send_file_and_exit(tptr);
1800 * The main http server function.
1801 * Given a socket, listen for new connections and farm out
1802 * the processing as a [v]forked process.
1806 static void mini_httpd(int server_socket) ATTRIBUTE_NORETURN;
1807 static void mini_httpd(int server_socket)
1809 /* NB: it's best to not use xfuncs in this loop before fork().
1810 * Otherwise server may die on transient errors (temporary
1811 * out-of-memory condition, etc), which is Bad(tm).
1812 * Try to do any dangerous calls after fork.
1816 len_and_sockaddr fromAddr;
1818 /* Wait for connections... */
1819 fromAddr.len = LSA_SIZEOF_SA;
1820 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1824 /* set the KEEPALIVE option to cull dead connections */
1825 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1829 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1830 /* Do not reload config on HUP */
1831 signal(SIGHUP, SIG_IGN);
1833 close(server_socket);
1837 handle_incoming_and_exit(&fromAddr);
1839 /* parent, or fork failed */
1845 static void mini_httpd_nommu(int server_socket, int argc, char **argv) ATTRIBUTE_NORETURN;
1846 static void mini_httpd_nommu(int server_socket, int argc, char **argv)
1848 char *argv_copy[argc + 2];
1850 argv_copy[0] = argv[0];
1851 argv_copy[1] = (char*)"-i";
1852 memcpy(&argv_copy[2], &argv[1], argc * sizeof(argv[0]));
1854 /* NB: it's best to not use xfuncs in this loop before vfork().
1855 * Otherwise server may die on transient errors (temporary
1856 * out-of-memory condition, etc), which is Bad(tm).
1857 * Try to do any dangerous calls after fork.
1861 len_and_sockaddr fromAddr;
1863 /* Wait for connections... */
1864 fromAddr.len = LSA_SIZEOF_SA;
1865 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1869 /* set the KEEPALIVE option to cull dead connections */
1870 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1874 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1875 /* Do not reload config on HUP */
1876 signal(SIGHUP, SIG_IGN);
1878 close(server_socket);
1882 /* Run a copy of ourself in inetd mode */
1885 /* parent, or vfork failed */
1893 * Process a HTTP connection on stdin/out.
1896 static void mini_httpd_inetd(void) ATTRIBUTE_NORETURN;
1897 static void mini_httpd_inetd(void)
1899 len_and_sockaddr fromAddr;
1901 fromAddr.len = LSA_SIZEOF_SA;
1902 getpeername(0, &fromAddr.sa, &fromAddr.len);
1903 handle_incoming_and_exit(&fromAddr);
1906 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1907 static void sighup_handler(int sig)
1909 struct sigaction sa;
1911 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1913 memset(&sa, 0, sizeof(sa));
1914 sa.sa_handler = sighup_handler;
1915 /*sigemptyset(&sa.sa_mask); - memset should be enough */
1916 sa.sa_flags = SA_RESTART;
1917 sigaction(SIGHUP, &sa, NULL);
1922 c_opt_config_file = 0,
1925 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1926 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1927 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1928 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1933 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1934 OPT_DECODE_URL = 1 << d_opt_decode_url,
1935 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1936 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1937 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1938 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1939 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1940 OPT_PORT = 1 << p_opt_port,
1941 OPT_INETD = 1 << p_opt_inetd,
1942 OPT_FOREGROUND = 1 << p_opt_foreground,
1943 OPT_VERBOSE = 1 << p_opt_verbose,
1947 int httpd_main(int argc, char **argv);
1948 int httpd_main(int argc, char **argv)
1950 int server_socket = server_socket; /* for gcc */
1952 char *url_for_decode;
1953 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1954 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1955 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1956 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1960 #if ENABLE_LOCALE_SUPPORT
1961 /* Undo busybox.c: we want to speak English in http (dates etc) */
1962 setlocale(LC_TIME, "C");
1965 home_httpd = xrealloc_getcwd_or_warn(NULL);
1966 /* -v counts, -i implies -f */
1967 opt_complementary = "vv:if";
1968 /* We do not "absolutize" path given by -h (home) opt.
1969 * If user gives relative path in -h, $SCRIPT_FILENAME can end up
1971 opt = getopt32(argv, "c:d:h:"
1972 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1973 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1974 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1975 USE_FEATURE_HTTPD_SETUID("u:")
1977 &configFile, &url_for_decode, &home_httpd
1978 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1979 USE_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
1980 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1981 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1982 , &bind_addr_or_port
1985 if (opt & OPT_DECODE_URL) {
1986 fputs(decodeString(url_for_decode, 1), stdout);
1989 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1990 if (opt & OPT_ENCODE_URL) {
1991 fputs(encodeString(url_for_encode), stdout);
1995 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1996 if (opt & OPT_MD5) {
1997 puts(pw_encrypt(pass, "$1$"));
2001 #if ENABLE_FEATURE_HTTPD_SETUID
2002 if (opt & OPT_SETUID) {
2003 if (!get_uidgid(&ugid, s_ugid, 1))
2004 bb_error_msg_and_die("unrecognized user[:group] "
2005 "name '%s'", s_ugid);
2010 if (!(opt & OPT_FOREGROUND)) {
2011 bb_daemonize_or_rexec(0, argv); /* don't change current directory */
2016 if (!(opt & OPT_INETD)) {
2017 signal(SIGCHLD, SIG_IGN);
2018 server_socket = openServer();
2019 #if ENABLE_FEATURE_HTTPD_SETUID
2020 /* drop privileges */
2021 if (opt & OPT_SETUID) {
2022 if (ugid.gid != (gid_t)-1) {
2023 if (setgroups(1, &ugid.gid) == -1)
2024 bb_perror_msg_and_die("setgroups");
2032 #if ENABLE_FEATURE_HTTPD_CGI
2034 char *p = getenv("PATH");
2035 /* env strings themself are not freed, no need to strdup(p): */
2039 // if (!(opt & OPT_INETD))
2040 // setenv_long("SERVER_PORT", ???);
2044 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2045 if (!(opt & OPT_INETD))
2047 else /* do not install HUP handler in inetd mode */
2049 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2051 xfunc_error_retval = 0;
2052 if (opt & OPT_INETD)
2055 if (!(opt & OPT_FOREGROUND))
2056 bb_daemonize(0); /* don't change current directory */
2057 mini_httpd(server_socket); /* never returns */
2059 mini_httpd_nommu(server_socket, argc, argv); /* never returns */