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 MAX_MEMORY_BUF 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";
114 typedef struct has_next_ptr {
115 struct has_next_ptr *next;
118 /* Must have "next" as a first member */
119 typedef struct Htaccess {
120 struct Htaccess *next;
122 char before_colon[1]; /* really bigger, must be last */
125 /* Must have "next" as a first member */
126 typedef struct Htaccess_IP {
127 struct Htaccess_IP *next;
134 int verbose; /* must be int (used by getopt32) */
135 smallint flg_deny_all;
138 unsigned rmt_port; /* for set env REMOTE_PORT */
139 char *rmt_ip_str; /* for set env REMOTE_ADDR */
140 const char *bind_addr_or_port;
143 const char *configFile;
144 const char *home_httpd;
146 const char *found_mime_type;
147 const char *found_moved_temporarily;
149 off_t ContentLength; /* -1 - unknown */
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; /* [MAX_MEMORY_BUF] */
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 rmt_port (G.rmt_port )
176 #define bind_addr_or_port (G.bind_addr_or_port)
177 #define g_query (G.g_query )
178 #define configFile (G.configFile )
179 #define home_httpd (G.home_httpd )
180 #define found_mime_type (G.found_mime_type )
181 #define found_moved_temporarily (G.found_moved_temporarily)
182 #define ContentLength (G.ContentLength )
183 #define last_mod (G.last_mod )
184 #define ip_a_d (G.ip_a_d )
185 #define g_realm (G.g_realm )
186 #define remoteuser (G.remoteuser )
187 #define referer (G.referer )
188 #define user_agent (G.user_agent )
189 #define rmt_ip_str (G.rmt_ip_str )
190 #define g_auth (G.g_auth )
191 #define mime_a (G.mime_a )
192 #define script_i (G.script_i )
193 #define iobuf (G.iobuf )
194 #define hdr_ptr (G.hdr_ptr )
195 #define hdr_cnt (G.hdr_cnt )
196 #define INIT_G() do { \
197 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
198 USE_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
199 bind_addr_or_port = "80"; \
200 ContentLength = -1; \
206 HTTP_MOVED_TEMPORARILY = 302,
207 HTTP_BAD_REQUEST = 400, /* malformed syntax */
208 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
209 HTTP_NOT_FOUND = 404,
210 HTTP_FORBIDDEN = 403,
211 HTTP_REQUEST_TIMEOUT = 408,
212 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
213 HTTP_INTERNAL_SERVER_ERROR = 500,
214 #if 0 /* future use */
216 HTTP_SWITCHING_PROTOCOLS = 101,
219 HTTP_NON_AUTHORITATIVE_INFO = 203,
220 HTTP_NO_CONTENT = 204,
221 HTTP_MULTIPLE_CHOICES = 300,
222 HTTP_MOVED_PERMANENTLY = 301,
223 HTTP_NOT_MODIFIED = 304,
224 HTTP_PAYMENT_REQUIRED = 402,
225 HTTP_BAD_GATEWAY = 502,
226 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
227 HTTP_RESPONSE_SETSIZE = 0xffffffff
232 HttpResponseNum type;
237 static const HttpEnumString httpResponseNames[] = {
238 { HTTP_OK, "OK", NULL },
239 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
240 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
241 "No request appeared within a reasonable time period." },
242 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
243 "The requested method is not recognized by this server." },
244 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
245 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
247 { HTTP_NOT_FOUND, "Not Found",
248 "The requested URL was not found on this server." },
249 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
250 { HTTP_FORBIDDEN, "Forbidden", "" },
251 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
252 "Internal Server Error" },
253 #if 0 /* not implemented */
254 { HTTP_CREATED, "Created" },
255 { HTTP_ACCEPTED, "Accepted" },
256 { HTTP_NO_CONTENT, "No Content" },
257 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
258 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
259 { HTTP_NOT_MODIFIED, "Not Modified" },
260 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
261 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
266 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
268 static void free_llist(has_next_ptr **pptr)
270 has_next_ptr *cur = *pptr;
272 has_next_ptr *t = cur;
279 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
280 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
281 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
282 static ALWAYS_INLINE void free_Htaccess_list(Htaccess **pptr)
284 free_llist((has_next_ptr**)pptr);
288 static ALWAYS_INLINE void free_Htaccess_IP_list(Htaccess_IP **pptr)
290 free_llist((has_next_ptr**)pptr);
293 static int scan_ip(const char **ep, unsigned *ip, unsigned char endc)
300 for (j = 0; j < 4; j++) {
303 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != '\0')
306 while (*p >= '0' && *p <= '9') {
315 if (*p != '/' && *p != '\0')
317 *ip = ((*ip) << 8) | octet;
330 static int scan_ip_mask(const char *ipm, unsigned *ip, unsigned *mask)
335 i = scan_ip(&ipm, ip, '/');
343 if (*p < '0' || *p > '9') {
345 i = scan_ip(&ipm, mask, 0);
368 * Parse configuration file into in-memory linked list.
370 * The first non-white character is examined to determine if the config line
371 * is one of the following:
372 * .ext:mime/type # new mime type not compiled into httpd
373 * [adAD]:from # ip address allow/deny, * for wildcard
374 * /path:user:pass # username/password
376 * Any previous IP rules are discarded.
377 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
378 * are also discarded. That is, previous settings are retained if flag is
381 * path Path where to look for httpd.conf (without filename).
382 * flag Type of the parse request.
385 #define FIRST_PARSE 0
386 #define SUBDIR_PARSE 1
387 #define SIGNALED_PARSE 2
388 #define FIND_FROM_HTTPD_ROOT 3
389 static void parse_conf(const char *path, int flag)
392 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
395 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
396 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
397 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
400 const char *cf = configFile;
406 /* discard old rules */
407 free_Htaccess_IP_list(&ip_a_d);
409 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
410 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
411 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
412 /* retain previous auth and mime config only for subdir parse */
413 if (flag != SUBDIR_PARSE) {
414 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
415 free_Htaccess_list(&g_auth);
417 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
418 free_Htaccess_list(&mime_a);
420 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
421 free_Htaccess_list(&script_i);
426 if (flag == SUBDIR_PARSE || cf == NULL) {
427 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
429 if (flag == FIRST_PARSE)
430 bb_error_msg_and_die(bb_msg_memory_exhausted);
433 sprintf((char *)cf, "%s/%s", path, httpd_conf);
436 while ((f = fopen(cf, "r")) == NULL) {
437 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
438 /* config file not found, no changes to config */
441 if (configFile && flag == FIRST_PARSE) /* if -c option given */
442 bb_perror_msg_and_die("%s", cf);
443 flag = FIND_FROM_HTTPD_ROOT;
447 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
450 /* This could stand some work */
451 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
453 for (p = p0; *p0 != '\0' && *p0 != '#'; p0++) {
456 if (*p0 == ':' && c == NULL)
462 /* test for empty or strange line */
463 if (c == NULL || *c == '\0')
470 /* memorize deny all */
473 /* skip default other "word:*" config lines */
479 else if (*p0 != 'D' && *p0 != 'A'
480 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
483 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
486 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
491 if (*p0 == 'A' || *p0 == 'D') {
492 /* storing current config IP line */
493 pip = xzalloc(sizeof(Htaccess_IP));
495 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
496 /* syntax IP{/mask} error detected, protect all */
500 pip->allow_deny = *p0;
502 /* Deny:from_IP move top */
506 /* add to bottom A:form_IP config line */
507 Htaccess_IP *prev_IP = ip_a_d;
509 if (prev_IP == NULL) {
512 while (prev_IP->next)
513 prev_IP = prev_IP->next;
520 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
522 /* make full path from httpd root / current_path / config_line_path */
523 cf = (flag == SUBDIR_PARSE ? path : "");
524 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
528 sprintf(p0, "/%s%s", cf, buf);
530 /* another call bb_simplify_path */
535 if (*cf == '/') { /* skip duplicate (or initial) slash */
537 } else if (*cf == '.') {
538 if (cf[1] == '/' || cf[1] == '\0') { /* remove extra '.' */
540 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == '\0')) {
543 while (*--p != '/') /* omit previous dir */;
552 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
553 ++p; /* so keep last character */
556 sprintf(p0, "%s:%s", p0, c);
560 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
561 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
562 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
563 /* storing current config line */
564 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
566 cf = strcpy(cur->before_colon, p0);
569 cur->after_colon = c;
570 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
572 /* config .mime line move top for overwrite previous */
578 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
579 if (*cf == '*' && cf[1] == '.') {
580 /* config script interpreter line move top for overwrite previous */
581 cur->next = script_i;
586 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
592 /* sort path, if current lenght eq or bigger then move up */
593 Htaccess *prev_hti = g_auth;
594 size_t l = strlen(cf);
597 for (hti = prev_hti; hti; hti = hti->next) {
598 if (l >= strlen(hti->before_colon)) {
599 /* insert before hti */
601 if (prev_hti != hti) {
602 prev_hti->next = cur;
610 prev_hti = prev_hti->next;
612 if (!hti) { /* not inserted, add to bottom */
624 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
626 * Given a string, html-encode special characters.
627 * This is used for the -e command line option to provide an easy way
628 * for scripts to encode result data without confusing browsers. The
629 * returned string pointer is memory allocated by malloc().
631 * Returns a pointer to the encoded string (malloced).
633 static char *encodeString(const char *string)
635 /* take the simple route and encode everything */
636 /* could possibly scan once to get length. */
637 int len = strlen(string);
638 char *out = xmalloc(len * 6 + 1);
642 while ((ch = *string++)) {
643 // very simple check for what to encode
644 if (isalnum(ch)) *p++ = ch;
645 else p += sprintf(p, "&#%d;", (unsigned char) ch);
650 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
653 * Given a URL encoded string, convert it to plain ascii.
654 * Since decoding always makes strings smaller, the decode is done in-place.
655 * Thus, callers should strdup() the argument if they do not want the
656 * argument modified. The return is the original pointer, allowing this
657 * function to be easily used as arguments to other functions.
659 * string The first string to decode.
660 * option_d 1 if called for httpd -d
662 * Returns a pointer to the decoded string (same as input).
664 static char *decodeString(char *orig, int option_d)
666 /* note that decoded string is always shorter than original */
671 while ((c = *ptr++) != '\0') {
672 unsigned value1, value2;
674 if (option_d && c == '+') {
682 if (sscanf(ptr, "%1X", &value1) != 1
683 || sscanf(ptr+1, "%1X", &value2) != 1
690 value1 = value1 * 16 + value2;
691 if (!option_d && (value1 == '/' || value1 == '\0')) {
692 /* caller takes it as indication of invalid
693 * (dangerous wrt exploits) chars */
704 #if ENABLE_FEATURE_HTTPD_CGI
708 static void setenv1(const char *name, const char *value)
712 setenv(name, value, 1);
714 static void setenv_long(const char *name, long value)
716 char buf[sizeof(value)*3 + 2];
717 sprintf(buf, "%ld", value);
718 setenv(name, buf, 1);
722 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
724 * Decode a base64 data stream as per rfc1521.
725 * Note that the rfc states that non base64 chars are to be ignored.
726 * Since the decode always results in a shorter size than the input,
727 * it is OK to pass the input arg as an output arg.
728 * Parameter: a pointer to a base64 encoded string.
729 * Decoded data is stored in-place.
731 static void decodeBase64(char *Data)
733 const unsigned char *in = (const unsigned char *)Data;
734 // The decoded size will be at most 3/4 the size of the encoded
741 if (t >= '0' && t <= '9')
743 else if (t >= 'A' && t <= 'Z')
745 else if (t >= 'a' && t <= 'z')
759 *Data++ = (char) (ch >> 16);
760 *Data++ = (char) (ch >> 8);
770 * Create a listen server socket on the designated port.
772 static int openServer(void)
774 int n = bb_strtou(bind_addr_or_port, NULL, 10);
775 if (!errno && n && n <= 0xffff)
776 n = create_and_bind_stream_or_die(NULL, n);
778 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
784 * Log the connection closure and exit.
786 static void log_and_exit(void) ATTRIBUTE_NORETURN;
787 static void log_and_exit(void)
790 bb_error_msg("closed");
791 _exit(xfunc_error_retval);
795 * Create and send HTTP response headers.
796 * The arguments are combined and sent as one write operation. Note that
797 * IE will puke big-time if the headers are not sent in one packet and the
798 * second packet is delayed for any reason.
799 * responseNum - the result code to send.
800 * Return result of write().
802 static void send_headers(HttpResponseNum responseNum)
804 static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
806 const char *responseString = "";
807 const char *infoString = NULL;
808 const char *mime_type;
810 time_t timer = time(0);
814 for (i = 0; i < ARRAY_SIZE(httpResponseNames); i++) {
815 if (httpResponseNames[i].type == responseNum) {
816 responseString = httpResponseNames[i].name;
817 infoString = httpResponseNames[i].info;
821 /* error message is HTML */
822 mime_type = responseNum == HTTP_OK ?
823 found_mime_type : "text/html";
826 bb_error_msg("response:%u", responseNum);
828 /* emit the current date */
829 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
831 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
832 "Date: %s\r\nConnection: close\r\n",
833 responseNum, responseString, mime_type, tmp_str);
835 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
836 if (responseNum == HTTP_UNAUTHORIZED) {
837 len += sprintf(iobuf + len,
838 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
842 if (responseNum == HTTP_MOVED_TEMPORARILY) {
843 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
844 found_moved_temporarily,
845 (g_query ? "?" : ""),
846 (g_query ? g_query : ""));
849 if (ContentLength != -1) { /* file */
850 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
851 len += sprintf(iobuf + len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
852 tmp_str, "Content-length:", ContentLength);
857 len += sprintf(iobuf + len,
858 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
859 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
860 responseNum, responseString,
861 responseNum, responseString, infoString);
864 fprintf(stderr, "headers: '%s'\n", iobuf);
865 if (full_write(1, iobuf, len) != len) {
867 bb_perror_msg("error");
872 static void send_headers_and_exit(HttpResponseNum responseNum) ATTRIBUTE_NORETURN;
873 static void send_headers_and_exit(HttpResponseNum responseNum)
875 send_headers(responseNum);
880 * Read from the socket until '\n' or EOF. '\r' chars are removed.
881 * '\n' is replaced with NUL.
882 * Return number of characters read or 0 if nothing is read
883 * ('\r' and '\n' are not counted).
884 * Data is returned in iobuf.
886 static int get_line(void)
893 hdr_cnt = safe_read(0, hdr_buf, sizeof(hdr_buf));
898 iobuf[count] = c = *hdr_ptr++;
907 if (count < (MAX_MEMORY_BUF - 1)) /* check overflow */
913 #if ENABLE_FEATURE_HTTPD_CGI
915 * Spawn CGI script, forward CGI's stdin/out <=> network
917 * Environment variables are set up and the script is invoked with pipes
918 * for stdin/stdout. If a post is being done the script is fed the POST
919 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
922 * const char *url The requested URL (with leading /).
923 * int bodyLen Length of the post body.
924 * const char *cookie For set HTTP_COOKIE.
925 * const char *content_type For set CONTENT_TYPE.
927 static void send_cgi_and_exit(
932 const char *content_type) ATTRIBUTE_NORETURN;
933 static void send_cgi_and_exit(
938 const char *content_type)
940 struct { int rd; int wr; } fromCgi; /* CGI -> httpd pipe */
941 struct { int rd; int wr; } toCgi; /* httpd -> CGI pipe */
950 * We are mucking with environment _first_ and then vfork/exec,
951 * this allows us to use vfork safely. Parent don't care about
952 * these environment changes anyway.
960 while ((script = strchr(script + 1, '/')) != NULL) {
961 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
965 if (!is_directory(purl + 1, 1, &sb)) {
966 /* not directory, found script.cgi/PATH_INFO */
970 *script = '/'; /* is directory, find next '/' */
972 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
973 setenv1("REQUEST_METHOD", request);
975 putenv(xasprintf("%s=%s?%s", "REQUEST_URI", purl, g_query));
977 setenv1("REQUEST_URI", purl);
980 *script = '\0'; /* cut off /PATH_INFO */
982 /* SCRIPT_FILENAME required by PHP in CGI mode */
983 fullpath = concat_path_file(home_httpd, purl);
984 setenv1("SCRIPT_FILENAME", fullpath);
985 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
986 setenv1("SCRIPT_NAME", purl);
987 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
988 * QUERY_STRING: The information which follows the ? in the URL
989 * which referenced this script. This is the query information.
990 * It should not be decoded in any fashion. This variable
991 * should always be set when there is query information,
992 * regardless of command line decoding. */
993 /* (Older versions of bbox seem to do some decoding) */
994 setenv1("QUERY_STRING", g_query);
995 putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
996 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
997 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
998 /* Having _separate_ variables for IP and port defeats
999 * the purpose of having socket abstraction. Which "port"
1000 * are you using on Unix domain socket?
1001 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1004 char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
1005 char *cp = strrchr(p, ':');
1006 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1008 if (cp) *cp = '\0'; /* delete :PORT */
1009 setenv1("REMOTE_ADDR", p);
1012 setenv1("HTTP_USER_AGENT", user_agent);
1013 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1014 setenv_long("REMOTE_PORT", rmt_port);
1017 setenv_long("CONTENT_LENGTH", bodyLen);
1019 setenv1("HTTP_COOKIE", cookie);
1021 setenv1("CONTENT_TYPE", content_type);
1022 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1024 setenv1("REMOTE_USER", remoteuser);
1025 putenv((char*)"AUTH_TYPE=Basic");
1029 setenv1("HTTP_REFERER", referer);
1036 /* TODO: log perror? */
1042 xfunc_error_retval = 242;
1044 xmove_fd(toCgi.rd, 0); /* replace stdin with the pipe */
1045 xmove_fd(fromCgi.wr, 1); /* replace stdout with the pipe */
1048 /* User seeing stderr output can be a security problem.
1049 * If CGI really wants that, it can always do dup itself. */
1052 /* script must have absolute path */
1053 script = strrchr(fullpath, '/');
1055 goto error_execing_cgi;
1057 /* chdiring to script's dir */
1058 if (chdir(fullpath) == 0) {
1060 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1061 char *interpr = NULL;
1062 char *suffix = strrchr(purl, '.');
1066 for (cur = script_i; cur; cur = cur->next) {
1067 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1068 interpr = cur->after_colon;
1075 /* set argv[0] to name without path */
1076 argv[0] = (char*)bb_basename(purl);
1078 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1080 execv(interpr, argv);
1083 execv(fullpath, argv);
1087 * (we are CGI here, our stdout is pumped to the net) */
1088 send_headers_and_exit(HTTP_NOT_FOUND);
1091 /* Parent process */
1093 /* First, restore variables possibly changed by child */
1094 xfunc_error_retval = 0;
1096 /* Prepare for pumping data.
1097 * iobuf is used for CGI -> network data,
1098 * hdr_buf is for network -> CGI data (POSTDATA) */
1103 /* If CGI dies, we still want to correctly finish reading its output
1104 * and send it to the peer. So please no SIGPIPEs! */
1105 signal(SIGPIPE, SIG_IGN);
1107 /* This loop still looks messy. What is an exit criteria?
1108 * "CGI's output closed"? Or "CGI has exited"?
1109 * What to do if CGI has closed both input and output, but
1110 * didn't exit? etc... */
1112 /* NB: breaking out of this loop jumps to log_and_exit() */
1121 FD_SET(fromCgi.rd, &readSet);
1122 if (bodyLen > 0 || hdr_cnt > 0) {
1123 FD_SET(toCgi.wr, &writeSet);
1124 nfound = toCgi.wr > fromCgi.rd ? toCgi.wr : fromCgi.rd;
1126 FD_SET(0, &readSet);
1127 /* Now wait on the set of sockets! */
1128 nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1131 close(toCgi.wr); /* no more POST data to CGI */
1134 nfound = select(fromCgi.rd + 1, &readSet, NULL, NULL, NULL);
1138 if (waitpid(pid, &status, WNOHANG) <= 0) {
1139 /* Weird. CGI didn't exit and no fd's
1140 * are ready, yet select returned?! */
1144 if (DEBUG && WIFEXITED(status))
1145 bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
1146 if (DEBUG && WIFSIGNALED(status))
1147 bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
1151 if (hdr_cnt > 0 && FD_ISSET(toCgi.wr, &writeSet)) {
1152 /* Have data from peer and can write to CGI */
1153 count = safe_write(toCgi.wr, hdr_ptr, hdr_cnt);
1154 /* Doesn't happen, we dont use nonblocking IO here
1155 *if (count < 0 && errno == EAGAIN) {
1162 hdr_cnt = bodyLen = 0; /* EOF/broken pipe to CGI */
1164 } else if (bodyLen > 0 && hdr_cnt == 0
1165 && FD_ISSET(0, &readSet)
1167 /* We expect data, prev data portion is eaten by CGI
1168 * and there *is* data to read from the peer
1170 count = bodyLen > (int)sizeof(hdr_buf) ? (int)sizeof(hdr_buf) : bodyLen;
1171 count = safe_read(0, hdr_buf, count);
1177 bodyLen = 0; /* closed */
1181 #define PIPESIZE PIPE_BUF
1182 #if PIPESIZE >= MAX_MEMORY_BUF
1183 # error "PIPESIZE >= MAX_MEMORY_BUF"
1185 if (FD_ISSET(fromCgi.rd, &readSet)) {
1186 /* There is something to read from CGI */
1189 /* Are we still buffering CGI output? */
1190 if (buf_count >= 0) {
1191 /* According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1192 * CGI scripts MUST send their own header terminated by
1193 * empty line, then data. That's why we have only one
1194 * <cr><lf> pair here. We will output "200 OK" line
1195 * if needed, but CGI still has to provide blank line
1196 * between header and body */
1197 static const char HTTP_200[] ALIGN1 = "HTTP/1.0 200 OK\r\n";
1199 /* Must use safe_read, not full_read, because
1200 * CGI may output a few first bytes and then wait
1201 * for POSTDATA without closing stdout.
1202 * With full_read we may wait here forever. */
1203 count = safe_read(fromCgi.rd, rbuf + buf_count, PIPESIZE - 8);
1205 /* eof (or error) and there was no "HTTP",
1206 * so write it, then write received data */
1208 full_write(1, HTTP_200, sizeof(HTTP_200)-1);
1209 full_write(1, rbuf, buf_count);
1211 break; /* CGI stdout is closed, exiting */
1215 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1216 if (buf_count >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1217 /* send "HTTP/1.0 " */
1218 if (full_write(1, HTTP_200, 9) != 9)
1220 rbuf += 8; /* skip "Status: " */
1221 count = buf_count - 8;
1222 buf_count = -1; /* buffering off */
1223 } else if (buf_count >= 4) {
1224 /* Did CGI add "HTTP"? */
1225 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1226 /* there is no "HTTP", do it ourself */
1227 if (full_write(1, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1231 if (!strstr(rbuf, "ontent-")) {
1232 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1234 * Counter-example of valid CGI without Content-type:
1235 * echo -en "HTTP/1.0 302 Found\r\n"
1236 * echo -en "Location: http://www.busybox.net\r\n"
1240 buf_count = -1; /* buffering off */
1243 count = safe_read(fromCgi.rd, rbuf, PIPESIZE);
1245 break; /* eof (or error) */
1247 if (full_write(1, rbuf, count) != count)
1250 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1251 } /* if (FD_ISSET(fromCgi.rd)) */
1255 #endif /* FEATURE_HTTPD_CGI */
1258 * Send a file response to a HTTP request, and exit
1260 static void send_file_and_exit(const char *url) ATTRIBUTE_NORETURN;
1261 static void send_file_and_exit(const char *url)
1263 static const char *const suffixTable[] = {
1264 /* Warning: shorter equivalent suffix in one line must be first */
1265 ".htm.html", "text/html",
1266 ".jpg.jpeg", "image/jpeg",
1267 ".gif", "image/gif",
1268 ".png", "image/png",
1269 ".txt.h.c.cc.cpp", "text/plain",
1271 ".wav", "audio/wav",
1272 ".avi", "video/x-msvideo",
1273 ".qt.mov", "video/quicktime",
1274 ".mpe.mpeg", "video/mpeg",
1275 ".mid.midi", "audio/midi",
1276 ".mp3", "audio/mpeg",
1277 #if 0 /* unpopular */
1278 ".au", "audio/basic",
1279 ".pac", "application/x-ns-proxy-autoconfig",
1280 ".vrml.wrl", "model/vrml",
1287 const char *const *table;
1288 const char *try_suffix;
1290 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1294 suffix = strrchr(url, '.');
1296 /* If not found, set default as "application/octet-stream"; */
1297 found_mime_type = "application/octet-stream";
1299 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1302 for (table = suffixTable; *table; table += 2) {
1303 try_suffix = strstr(table[0], suffix);
1305 try_suffix += strlen(suffix);
1306 if (*try_suffix == '\0' || *try_suffix == '.') {
1307 found_mime_type = table[1];
1312 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1313 for (cur = mime_a; cur; cur = cur->next) {
1314 if (strcmp(cur->before_colon, suffix) == 0) {
1315 found_mime_type = cur->after_colon;
1323 bb_error_msg("sending file '%s' content-type: %s",
1324 url, found_mime_type);
1326 f = open(url, O_RDONLY);
1329 bb_perror_msg("cannot open '%s'", url);
1330 send_headers_and_exit(HTTP_NOT_FOUND);
1333 send_headers(HTTP_OK);
1335 /* If you want to know about EPIPE below
1336 * (happens if you abort downloads from local httpd): */
1337 signal(SIGPIPE, SIG_IGN);
1339 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1341 /* byte count (3rd arg) is rounded down to 64k */
1342 count = sendfile(1, f, &offset, MAXINT(ssize_t) - 0xffff);
1348 } while (count > 0);
1353 while ((count = safe_read(f, iobuf, MAX_MEMORY_BUF)) > 0) {
1355 count = full_write(1, iobuf, count);
1359 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1362 if (count < 0 && verbose > 1)
1363 bb_perror_msg("error");
1367 static int checkPermIP(void)
1371 /* This could stand some work */
1372 for (cur = ip_a_d; cur; cur = cur->next) {
1375 "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1377 (unsigned char)(cur->ip >> 24),
1378 (unsigned char)(cur->ip >> 16),
1379 (unsigned char)(cur->ip >> 8),
1380 (unsigned char)(cur->ip),
1381 (unsigned char)(cur->mask >> 24),
1382 (unsigned char)(cur->mask >> 16),
1383 (unsigned char)(cur->mask >> 8),
1384 (unsigned char)(cur->mask)
1387 if ((rmt_ip & cur->mask) == cur->ip)
1388 return cur->allow_deny == 'A'; /* Allow/Deny */
1391 /* if unconfigured, return 1 - access from all */
1392 return !flg_deny_all;
1395 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1397 * Check the permission file for access password protected.
1399 * If config file isn't present, everything is allowed.
1400 * Entries are of the form you can see example from header source
1402 * path The file path.
1403 * request User information to validate.
1405 * Returns 1 if request is OK.
1407 static int checkPerm(const char *path, const char *request)
1413 const char *prev = NULL;
1415 /* This could stand some work */
1416 for (cur = g_auth; cur; cur = cur->next) {
1419 p0 = cur->before_colon;
1420 if (prev != NULL && strcmp(prev, p0) != 0)
1421 continue; /* find next identical */
1422 p = cur->after_colon;
1424 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1427 if (strncmp(p0, path, l) == 0
1428 && (l == 1 || path[l] == '/' || path[l] == '\0')
1431 /* path match found. Check request */
1432 /* for check next /path:user:password */
1434 u = strchr(request, ':');
1436 /* bad request, ':' required */
1440 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1444 if (strncmp(p, request, u - request) != 0) {
1445 /* user uncompared */
1448 pp = strchr(p, ':');
1449 if (pp && pp[1] == '$' && pp[2] == '1' &&
1450 pp[3] == '$' && pp[4]) {
1452 cipher = pw_encrypt(u+1, pp);
1453 if (strcmp(cipher, pp) == 0)
1454 goto set_remoteuser_var; /* Ok */
1460 if (strcmp(p, request) == 0) {
1462 remoteuser = strdup(request);
1464 remoteuser[(u - request)] = '\0';
1471 return prev == NULL;
1473 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1478 static void exit_on_signal(int sig) ATTRIBUTE_NORETURN;
1479 static void exit_on_signal(int sig)
1481 send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
1485 * Handle an incoming http request and exit.
1487 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr) ATTRIBUTE_NORETURN;
1488 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
1490 static const char request_GET[] ALIGN1 = "GET";
1495 int http_major_version;
1499 #if ENABLE_FEATURE_HTTPD_CGI
1500 const char *prequest;
1501 unsigned long length = 0;
1503 char *content_type = 0;
1505 struct sigaction sa;
1506 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1507 int credentials = -1; /* if not required this is Ok */
1510 /* Allocation of iobuf is postponed until now
1511 * (IOW, server process doesn't need to waste 8k) */
1512 iobuf = xmalloc(MAX_MEMORY_BUF);
1514 rmt_port = get_nport(&fromAddr->sa);
1515 rmt_port = ntohs(rmt_port);
1517 if (fromAddr->sa.sa_family == AF_INET) {
1518 rmt_ip = ntohl(fromAddr->sin.sin_addr.s_addr);
1520 if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1521 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr->sa);
1524 /* this trick makes -v logging much simpler */
1525 applet_name = rmt_ip_str;
1527 bb_error_msg("connected");
1530 /* Install timeout handler */
1531 memset(&sa, 0, sizeof(sa));
1532 sa.sa_handler = exit_on_signal;
1533 /* sigemptyset(&sa.sa_mask); - memset should be enough */
1534 /*sa.sa_flags = 0; - no SA_RESTART */
1535 sigaction(SIGALRM, &sa, NULL);
1536 alarm(HEADER_READ_TIMEOUT);
1539 /* EOF or error or empty line */
1540 send_headers_and_exit(HTTP_BAD_REQUEST);
1543 /* Determine type of request (GET/POST) */
1544 purl = strpbrk(iobuf, " \t");
1546 send_headers_and_exit(HTTP_BAD_REQUEST);
1549 #if ENABLE_FEATURE_HTTPD_CGI
1550 prequest = request_GET;
1551 if (strcasecmp(iobuf, prequest) != 0) {
1553 if (strcasecmp(iobuf, prequest) != 0) {
1554 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1558 if (strcasecmp(iobuf, request_GET) != 0) {
1559 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1564 /* Copy URL from after "GET "/"POST " to stack-allocated char[] */
1565 http_major_version = -1;
1566 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", iobuf, &http_major_version);
1567 if (count < 1 || iobuf[0] != '/') {
1568 /* Garbled request/URL */
1569 send_headers_and_exit(HTTP_BAD_REQUEST);
1571 url = alloca(strlen(iobuf) + sizeof("/index.html"));
1573 send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
1577 /* Extract url args if present */
1578 test = strchr(url, '?');
1585 /* Decode URL escape sequences */
1586 test = decodeString(url, 0);
1588 send_headers_and_exit(HTTP_BAD_REQUEST);
1589 if (test == url + 1) {
1590 /* '/' or NUL is encoded */
1591 send_headers_and_exit(HTTP_NOT_FOUND);
1594 /* Canonicalize path */
1595 /* Algorithm stolen from libbb bb_simplify_path(),
1596 * but don't strdup and reducing trailing slash and protect out root */
1600 /* skip duplicate (or initial) slash */
1605 /* skip extra '.' */
1606 if (test[1] == '/' || !test[1]) {
1609 /* '..': be careful */
1610 if (test[1] == '.' && (test[2] == '/' || !test[2])) {
1614 send_headers_and_exit(HTTP_BAD_REQUEST);
1616 while (*--purl != '/') /* omit previous dir */;
1623 *++purl = '\0'; /* so keep last character */
1624 test = purl; /* end ptr */
1626 /* If URL is a directory, add '/' */
1627 if (test[-1] != '/') {
1628 if (is_directory(url + 1, 1, &sb)) {
1629 found_moved_temporarily = url;
1635 bb_error_msg("url:%s", url);
1638 ip_allowed = checkPermIP();
1639 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1640 /* have path1/path2 */
1642 if (is_directory(url + 1, 1, &sb)) {
1643 /* may be having subdir config */
1644 parse_conf(url + 1, SUBDIR_PARSE);
1645 ip_allowed = checkPermIP();
1649 if (http_major_version >= 0) {
1650 /* Request was with "... HTTP/n.m", and n >= 0 */
1652 /* Read until blank line for HTTP version specified, else parse immediate */
1654 alarm(HEADER_READ_TIMEOUT);
1656 break; /* EOF or error or empty line */
1658 bb_error_msg("header: '%s'", iobuf);
1660 #if ENABLE_FEATURE_HTTPD_CGI
1661 /* try and do our best to parse more lines */
1662 if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
1663 /* extra read only for POST */
1664 if (prequest != request_GET) {
1665 test = iobuf + sizeof("Content-length:") - 1;
1667 send_headers_and_exit(HTTP_BAD_REQUEST);
1669 /* not using strtoul: it ignores leading minus! */
1670 length = strtol(test, &test, 10);
1671 /* length is "ulong", but we need to pass it to int later */
1672 /* so we check for negative or too large values in one go: */
1673 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1674 if (test[0] || errno || length > INT_MAX)
1675 send_headers_and_exit(HTTP_BAD_REQUEST);
1677 } else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
1678 cookie = strdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
1679 } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
1680 content_type = strdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
1681 } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
1682 referer = strdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
1683 } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
1684 user_agent = strdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
1687 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1688 if (STRNCASECMP(iobuf, "Authorization:") == 0) {
1689 /* We only allow Basic credentials.
1690 * It shows up as "Authorization: Basic <userid:password>" where
1691 * the userid:password is base64 encoded.
1693 test = skip_whitespace(iobuf + sizeof("Authorization:")-1);
1694 if (STRNCASECMP(test, "Basic") != 0)
1696 test += sizeof("Basic")-1;
1697 /* decodeBase64() skips whitespace itself */
1699 credentials = checkPerm(url, test);
1701 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1702 } /* while extra header reading */
1705 /* We read headers, disable peer timeout */
1708 if (strcmp(bb_basename(url), httpd_conf) == 0 || ip_allowed == 0) {
1709 /* protect listing [/path]/httpd_conf or IP deny */
1710 send_headers_and_exit(HTTP_FORBIDDEN);
1713 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1714 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1715 send_headers_and_exit(HTTP_UNAUTHORIZED);
1719 if (found_moved_temporarily) {
1720 send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
1723 test = url + 1; /* skip first '/' */
1725 #if ENABLE_FEATURE_HTTPD_CGI
1726 if (strncmp(test, "cgi-bin/", 8) == 0) {
1727 if (test[8] == '\0') {
1728 /* protect listing "cgi-bin/" */
1729 send_headers_and_exit(HTTP_FORBIDDEN);
1731 send_cgi_and_exit(url, prequest, length, cookie, content_type);
1733 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1735 char *suffix = strrchr(test, '.');
1738 for (cur = script_i; cur; cur = cur->next) {
1739 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1740 send_cgi_and_exit(url, prequest, length, cookie, content_type);
1746 if (prequest != request_GET) {
1747 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1749 #endif /* FEATURE_HTTPD_CGI */
1751 if (purl[-1] == '/')
1752 strcpy(purl, "index.html");
1753 if (stat(test, &sb) == 0) {
1754 /* It's a dir URL and there is index.html */
1755 ContentLength = sb.st_size;
1756 last_mod = sb.st_mtime;
1758 #if ENABLE_FEATURE_HTTPD_CGI
1759 else if (purl[-1] == '/') {
1760 /* It's a dir URL and there is no index.html
1761 * Try cgi-bin/index.cgi */
1762 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1765 send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1770 * fall through to send_file, it errors out if open fails
1774 send_file_and_exit(test);
1776 #if 0 /* Is this needed? Why? */
1778 fprintf(stderr, "closing socket\n");
1779 #if ENABLE_FEATURE_HTTPD_CGI
1784 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1789 /* Properly wait for remote to closed */
1791 shutdown(1, SHUT_WR);
1799 retval = select(1, &s_fd, NULL, NULL, &tv);
1800 } while (retval > 0 && read(0, iobuf, sizeof(iobuf) > 0));
1801 shutdown(0, SHUT_RD);
1807 * The main http server function.
1808 * Given a socket, listen for new connections and farm out
1809 * the processing as a [v]forked process.
1813 static void mini_httpd(int server_socket) ATTRIBUTE_NORETURN;
1814 static void mini_httpd(int server_socket)
1816 /* NB: it's best to not use xfuncs in this loop before fork().
1817 * Otherwise server may die on transient errors (temporary
1818 * out-of-memory condition, etc), which is Bad(tm).
1819 * Try to do any dangerous calls after fork.
1823 len_and_sockaddr fromAddr;
1825 /* Wait for connections... */
1826 fromAddr.len = LSA_SIZEOF_SA;
1827 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1831 /* set the KEEPALIVE option to cull dead connections */
1832 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1836 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1837 /* Do not reload config on HUP */
1838 signal(SIGHUP, SIG_IGN);
1840 close(server_socket);
1844 handle_incoming_and_exit(&fromAddr);
1846 /* parent, or fork failed */
1852 static void mini_httpd_nommu(int server_socket, int argc, char **argv) ATTRIBUTE_NORETURN;
1853 static void mini_httpd_nommu(int server_socket, int argc, char **argv)
1855 char *argv_copy[argc + 2];
1857 argv_copy[0] = argv[0];
1858 argv_copy[1] = (char*)"-i";
1859 memcpy(&argv_copy[2], &argv[1], argc * sizeof(argv[0]));
1861 /* NB: it's best to not use xfuncs in this loop before vfork().
1862 * Otherwise server may die on transient errors (temporary
1863 * out-of-memory condition, etc), which is Bad(tm).
1864 * Try to do any dangerous calls after fork.
1868 len_and_sockaddr fromAddr;
1870 /* Wait for connections... */
1871 fromAddr.len = LSA_SIZEOF_SA;
1872 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1876 /* set the KEEPALIVE option to cull dead connections */
1877 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1881 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1882 /* Do not reload config on HUP */
1883 signal(SIGHUP, SIG_IGN);
1885 close(server_socket);
1889 /* Run a copy of ourself in inetd mode */
1892 /* parent, or fork failed */
1900 * Process a HTTP connection on stdin/out.
1903 static void mini_httpd_inetd(void) ATTRIBUTE_NORETURN;
1904 static void mini_httpd_inetd(void)
1906 len_and_sockaddr fromAddr;
1908 fromAddr.len = LSA_SIZEOF_SA;
1909 getpeername(0, &fromAddr.sa, &fromAddr.len);
1910 handle_incoming_and_exit(&fromAddr);
1913 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1914 static void sighup_handler(int sig)
1916 struct sigaction sa;
1918 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1920 memset(&sa, 0, sizeof(sa));
1921 sa.sa_handler = sighup_handler;
1922 /*sigemptyset(&sa.sa_mask); - memset should be enough */
1923 sa.sa_flags = SA_RESTART;
1924 sigaction(SIGHUP, &sa, NULL);
1929 c_opt_config_file = 0,
1932 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1933 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1934 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1935 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1940 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1941 OPT_DECODE_URL = 1 << d_opt_decode_url,
1942 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1943 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1944 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1945 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1946 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1947 OPT_PORT = 1 << p_opt_port,
1948 OPT_INETD = 1 << p_opt_inetd,
1949 OPT_FOREGROUND = 1 << p_opt_foreground,
1950 OPT_VERBOSE = 1 << p_opt_verbose,
1954 int httpd_main(int argc, char **argv);
1955 int httpd_main(int argc, char **argv)
1957 int server_socket = server_socket; /* for gcc */
1959 char *url_for_decode;
1960 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1961 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1962 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1963 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1967 #if ENABLE_LOCALE_SUPPORT
1968 /* Undo busybox.c: we want to speak English in http (dates etc) */
1969 setlocale(LC_TIME, "C");
1972 home_httpd = xrealloc_getcwd_or_warn(NULL);
1973 /* -v counts, -i implies -f */
1974 opt_complementary = "vv:if";
1975 /* We do not "absolutize" path given by -h (home) opt.
1976 * If user gives relative path in -h, $SCRIPT_FILENAME can end up
1978 opt = getopt32(argv, "c:d:h:"
1979 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1980 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1981 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1982 USE_FEATURE_HTTPD_SETUID("u:")
1984 &configFile, &url_for_decode, &home_httpd
1985 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1986 USE_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
1987 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1988 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1989 , &bind_addr_or_port
1992 if (opt & OPT_DECODE_URL) {
1993 fputs(decodeString(url_for_decode, 1), stdout);
1996 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1997 if (opt & OPT_ENCODE_URL) {
1998 fputs(encodeString(url_for_encode), stdout);
2002 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
2003 if (opt & OPT_MD5) {
2004 puts(pw_encrypt(pass, "$1$"));
2008 #if ENABLE_FEATURE_HTTPD_SETUID
2009 if (opt & OPT_SETUID) {
2010 if (!get_uidgid(&ugid, s_ugid, 1))
2011 bb_error_msg_and_die("unrecognized user[:group] "
2012 "name '%s'", s_ugid);
2017 if (!(opt & OPT_FOREGROUND)) {
2018 bb_daemonize_or_rexec(0, argv); /* don't change current directory */
2023 if (!(opt & OPT_INETD)) {
2024 signal(SIGCHLD, SIG_IGN);
2025 server_socket = openServer();
2026 #if ENABLE_FEATURE_HTTPD_SETUID
2027 /* drop privileges */
2028 if (opt & OPT_SETUID) {
2029 if (ugid.gid != (gid_t)-1) {
2030 if (setgroups(1, &ugid.gid) == -1)
2031 bb_perror_msg_and_die("setgroups");
2039 #if ENABLE_FEATURE_HTTPD_CGI
2041 char *p = getenv("PATH");
2042 /* env strings themself are not freed, no need to strdup(p): */
2046 // if (!(opt & OPT_INETD))
2047 // setenv_long("SERVER_PORT", ???);
2051 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2052 if (!(opt & OPT_INETD))
2054 else /* do not install HUP handler in inetd mode */
2056 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2058 xfunc_error_retval = 0;
2059 if (opt & OPT_INETD)
2062 if (!(opt & OPT_FOREGROUND))
2063 bb_daemonize(0); /* don't change current directory */
2064 mini_httpd(server_socket); /* never returns */
2066 mini_httpd_nommu(server_socket, argc, argv); /* never returns */