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 contains "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>
99 /* amount of buffering in a pipe */
101 # define PIPE_BUF 4096
104 static const char default_path_httpd_conf[] ALIGN1 = "/etc";
105 static const char httpd_conf[] ALIGN1 = "httpd.conf";
109 // Note: busybox xfuncs are not used because we want the server to keep running
110 // if something bad happens due to a malformed user request.
111 // As a result, all memory allocations after daemonize
112 // are checked rigorously
117 #define MAX_MEMORY_BUF 8192 /* IO buffer */
119 typedef struct Htaccess {
121 struct Htaccess *next;
122 char before_colon[1]; /* really bigger, must be last */
125 typedef struct Htaccess_IP {
129 struct Htaccess_IP *next;
136 smallint flg_deny_all;
139 unsigned tcp_port; /* for set env REMOTE_PORT */
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 char *rmt_ip_str; /* for set env REMOTE_ADDR */
159 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
160 Htaccess *g_auth; /* config user:password lines */
162 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
163 Htaccess *mime_a; /* config mime types */
165 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
166 Htaccess *script_i; /* config script interpreters */
168 char iobuf[MAX_MEMORY_BUF];
170 #define G (*ptr_to_globals)
171 #define server_socket (G.server_socket )
172 #define accepted_socket (G.accepted_socket )
173 #define verbose (G.verbose )
174 #define flg_deny_all (G.flg_deny_all )
175 #define rmt_ip (G.rmt_ip )
176 #define tcp_port (G.tcp_port )
177 #define bind_addr_or_port (G.bind_addr_or_port)
178 #define g_query (G.g_query )
179 #define configFile (G.configFile )
180 #define home_httpd (G.home_httpd )
181 #define found_mime_type (G.found_mime_type )
182 #define found_moved_temporarily (G.found_moved_temporarily)
183 #define ContentLength (G.ContentLength )
184 #define last_mod (G.last_mod )
185 #define ip_a_d (G.ip_a_d )
186 #define g_realm (G.g_realm )
187 #define remoteuser (G.remoteuser )
188 #define referer (G.referer )
189 #define user_agent (G.user_agent )
190 #define rmt_ip_str (G.rmt_ip_str )
191 #define g_auth (G.g_auth )
192 #define mime_a (G.mime_a )
193 #define script_i (G.script_i )
194 #define iobuf (G.iobuf )
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; \
202 static const char request_GET[] ALIGN1 = "GET"; /* size algorithmic optimize */
204 static const char *const suffixTable[] = {
205 /* Warning: shorter equivalent suffix in one line must be first */
206 ".htm.html", "text/html",
207 ".jpg.jpeg", "image/jpeg",
210 ".txt.h.c.cc.cpp", "text/plain",
213 ".avi", "video/x-msvideo",
214 ".qt.mov", "video/quicktime",
215 ".mpe.mpeg", "video/mpeg",
216 ".mid.midi", "audio/midi",
217 ".mp3", "audio/mpeg",
218 #if 0 /* unpopular */
219 ".au", "audio/basic",
220 ".pac", "application/x-ns-proxy-autoconfig",
221 ".vrml.wrl", "model/vrml",
223 0, "application/octet-stream" /* default */
228 HTTP_MOVED_TEMPORARILY = 302,
229 HTTP_BAD_REQUEST = 400, /* malformed syntax */
230 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
231 HTTP_NOT_FOUND = 404,
232 HTTP_FORBIDDEN = 403,
233 HTTP_REQUEST_TIMEOUT = 408,
234 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
235 HTTP_INTERNAL_SERVER_ERROR = 500,
236 #if 0 /* future use */
238 HTTP_SWITCHING_PROTOCOLS = 101,
241 HTTP_NON_AUTHORITATIVE_INFO = 203,
242 HTTP_NO_CONTENT = 204,
243 HTTP_MULTIPLE_CHOICES = 300,
244 HTTP_MOVED_PERMANENTLY = 301,
245 HTTP_NOT_MODIFIED = 304,
246 HTTP_PAYMENT_REQUIRED = 402,
247 HTTP_BAD_GATEWAY = 502,
248 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
249 HTTP_RESPONSE_SETSIZE = 0xffffffff
254 HttpResponseNum type;
259 static const HttpEnumString httpResponseNames[] = {
260 { HTTP_OK, "OK", NULL },
261 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
262 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
263 "No request appeared within a reasonable time period." },
264 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
265 "The requested method is not recognized by this server." },
266 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
267 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
269 { HTTP_NOT_FOUND, "Not Found",
270 "The requested URL was not found on this server." },
271 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
272 { HTTP_FORBIDDEN, "Forbidden", "" },
273 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
274 "Internal Server Error" },
275 #if 0 /* not implemented */
276 { HTTP_CREATED, "Created" },
277 { HTTP_ACCEPTED, "Accepted" },
278 { HTTP_NO_CONTENT, "No Content" },
279 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
280 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
281 { HTTP_NOT_MODIFIED, "Not Modified" },
282 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
283 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
288 static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
291 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
294 static int scan_ip(const char **ep, unsigned *ip, unsigned char endc)
301 for (j = 0; j < 4; j++) {
304 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
307 while (*p >= '0' && *p <= '9') {
316 if (*p != '/' && *p != 0)
318 *ip = ((*ip) << 8) | octet;
331 static int scan_ip_mask(const char *ipm, unsigned *ip, unsigned *mask)
336 i = scan_ip(&ipm, ip, '/');
344 if (*p < '0' || *p > '9') {
346 i = scan_ip(&ipm, mask, 0);
368 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
369 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
370 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
371 static void free_config_lines(Htaccess **pprev)
373 Htaccess *prev = *pprev;
376 Htaccess *cur = prev;
386 #define FIRST_PARSE 0
387 #define SUBDIR_PARSE 1
388 #define SIGNALED_PARSE 2
389 #define FIND_FROM_HTTPD_ROOT 3
390 /****************************************************************************
392 > $Function: parse_conf()
394 * $Description: parse configuration file into in-memory linked list.
396 * The first non-white character is examined to determine if the config line
397 * is one of the following:
398 * .ext:mime/type # new mime type not compiled into httpd
399 * [adAD]:from # ip address allow/deny, * for wildcard
400 * /path:user:pass # username/password
402 * Any previous IP rules are discarded.
403 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
404 * are also discarded. That is, previous settings are retained if flag is
408 * (const char *) path . . null for ip address checks, path for password
410 * (int) flag . . . . . . the source of the parse request.
414 ****************************************************************************/
415 static void parse_conf(const char *path, int flag)
418 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
421 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
422 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
423 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
427 const char *cf = configFile;
432 /* free previous ip setup if present */
433 Htaccess_IP *pip = ip_a_d;
436 Htaccess_IP *cur_ipl = pip;
445 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
446 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
447 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
448 /* retain previous auth and mime config only for subdir parse */
449 if (flag != SUBDIR_PARSE) {
450 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
451 free_config_lines(&g_auth);
453 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
454 free_config_lines(&mime_a);
456 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
457 free_config_lines(&script_i);
462 if (flag == SUBDIR_PARSE || cf == NULL) {
463 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
465 if (flag == FIRST_PARSE)
466 bb_error_msg_and_die(bb_msg_memory_exhausted);
469 sprintf((char *)cf, "%s/%s", path, httpd_conf);
472 while ((f = fopen(cf, "r")) == NULL) {
473 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
474 /* config file not found, no changes to config */
477 if (configFile && flag == FIRST_PARSE) /* if -c option given */
478 bb_perror_msg_and_die("%s", cf);
479 flag = FIND_FROM_HTTPD_ROOT;
483 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
486 /* This could stand some work */
487 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
489 for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
492 if (*p0 == ':' && c == NULL)
498 /* test for empty or strange line */
499 if (c == NULL || *c == 0)
506 /* memorize deny all */
509 /* skip default other "word:*" config lines */
515 else if (*p0 != 'D' && *p0 != 'A'
516 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
519 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
522 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
527 if (*p0 == 'A' || *p0 == 'D') {
528 /* storing current config IP line */
529 pip = xzalloc(sizeof(Htaccess_IP));
531 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
532 /* syntax IP{/mask} error detected, protect all */
536 pip->allow_deny = *p0;
538 /* Deny:form_IP move top */
542 /* add to bottom A:form_IP config line */
543 Htaccess_IP *prev_IP = ip_a_d;
545 if (prev_IP == NULL) {
548 while (prev_IP->next)
549 prev_IP = prev_IP->next;
556 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
558 /* make full path from httpd root / curent_path / config_line_path */
559 cf = flag == SUBDIR_PARSE ? path : "";
560 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
564 sprintf(p0, "/%s%s", cf, buf);
566 /* another call bb_simplify_path */
571 if (*cf == '/') { /* skip duplicate (or initial) slash */
573 } else if (*cf == '.') {
574 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
576 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
579 while (*--p != '/') /* omit previous dir */;
588 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
589 ++p; /* so keep last character */
592 sprintf(p0, "%s:%s", p0, c);
596 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
597 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
598 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
599 /* storing current config line */
600 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
602 cf = strcpy(cur->before_colon, p0);
605 cur->after_colon = c;
606 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
608 /* config .mime line move top for overwrite previous */
614 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
615 if (*cf == '*' && cf[1] == '.') {
616 /* config script interpreter line move top for overwrite previous */
617 cur->next = script_i;
622 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
628 /* sort path, if current lenght eq or bigger then move up */
629 Htaccess *prev_hti = g_auth;
630 size_t l = strlen(cf);
633 for (hti = prev_hti; hti; hti = hti->next) {
634 if (l >= strlen(hti->before_colon)) {
635 /* insert before hti */
637 if (prev_hti != hti) {
638 prev_hti->next = cur;
646 prev_hti = prev_hti->next;
648 if (!hti) { /* not inserted, add to bottom */
660 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
661 /****************************************************************************
663 > $Function: encodeString()
665 * $Description: Given a string, html encode special characters.
666 * This is used for the -e command line option to provide an easy way
667 * for scripts to encode result data without confusing browsers. The
668 * returned string pointer is memory allocated by malloc().
671 * (const char *) string . . The first string to encode.
673 * $Return: (char *) . . . .. . . A pointer to the encoded string.
675 * $Errors: Returns a null string ("") if memory is not available.
677 ****************************************************************************/
678 static char *encodeString(const char *string)
680 /* take the simple route and encode everything */
681 /* could possibly scan once to get length. */
682 int len = strlen(string);
683 char *out = xmalloc(len * 6 + 1);
687 while ((ch = *string++)) {
688 // very simple check for what to encode
689 if (isalnum(ch)) *p++ = ch;
690 else p += sprintf(p, "&#%d;", (unsigned char) ch);
695 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
697 /****************************************************************************
699 > $Function: decodeString()
701 * $Description: Given a URL encoded string, convert it to plain ascii.
702 * Since decoding always makes strings smaller, the decode is done in-place.
703 * Thus, callers should strdup() the argument if they do not want the
704 * argument modified. The return is the original pointer, allowing this
705 * function to be easily used as arguments to other functions.
708 * (char *) string . . . The first string to decode.
709 * (int) option_d . . 1 if called for httpd -d
711 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
715 ****************************************************************************/
716 static char *decodeString(char *orig, int option_d)
718 /* note that decoded string is always shorter than original */
723 while ((c = *ptr++) != '\0') {
724 unsigned value1, value2;
726 if (option_d && c == '+') {
734 if (sscanf(ptr, "%1X", &value1) != 1
735 || sscanf(ptr+1, "%1X", &value2) != 1
742 value1 = value1 * 16 + value2;
743 if (!option_d && (value1 == '/' || value1 == '\0')) {
744 /* caller takes it as indication of invalid
745 * (dangerous wrt exploits) chars */
756 #if ENABLE_FEATURE_HTTPD_CGI
757 /****************************************************************************
759 ****************************************************************************/
760 static void setenv1(const char *name, const char *value)
764 setenv(name, value, 1);
766 static void setenv_long(const char *name, long value)
768 char buf[sizeof(value)*3 + 2];
769 sprintf(buf, "%ld", value);
770 setenv(name, buf, 1);
774 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
776 * Decode a base 64 data stream as per rfc1521.
777 * Note that the rfc states that non base64 chars are to be ignored.
778 * Since the decode always results in a shorter size than the input, it is
779 * OK to pass the input arg as an output arg.
780 * Parameter: a pointer to a base64 encoded string.
781 * Decoded data is stored in-place.
783 static void decodeBase64(char *Data)
785 const unsigned char *in = (const unsigned char *)Data;
786 // The decoded size will be at most 3/4 the size of the encoded
793 if (t >= '0' && t <= '9')
795 else if (t >= 'A' && t <= 'Z')
797 else if (t >= 'a' && t <= 'z')
811 *Data++ = (char) (ch >> 16);
812 *Data++ = (char) (ch >> 8);
822 /****************************************************************************
824 > $Function: openServer()
826 * $Description: create a listen server socket on the designated port.
828 * $Return: (int) . . . A connection socket. -1 for errors.
832 ****************************************************************************/
834 static int openServer(void)
836 int n = bb_strtou(bind_addr_or_port, NULL, 10);
837 if (!errno && n && n <= 0xffff)
838 n = create_and_bind_stream_or_die(NULL, n);
840 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
847 * Create and send HTTP response headers.
848 * The arguments are combined and sent as one write operation. Note that
849 * IE will puke big-time if the headers are not sent in one packet and the
850 * second packet is delayed for any reason.
851 * responseNum - the result code to send.
852 * Return result of write().
854 static int sendHeaders(HttpResponseNum responseNum)
856 const char *responseString = "";
857 const char *infoString = NULL;
858 const char *mime_type;
860 time_t timer = time(0);
864 for (i = 0; i < ARRAY_SIZE(httpResponseNames); i++) {
865 if (httpResponseNames[i].type == responseNum) {
866 responseString = httpResponseNames[i].name;
867 infoString = httpResponseNames[i].info;
871 /* error message is HTML */
872 mime_type = responseNum == HTTP_OK ?
873 found_mime_type : "text/html";
876 bb_error_msg("response:%u", responseNum);
878 /* emit the current date */
879 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
881 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
882 "Date: %s\r\nConnection: close\r\n",
883 responseNum, responseString, mime_type, tmp_str);
885 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
886 if (responseNum == HTTP_UNAUTHORIZED) {
887 len += sprintf(iobuf + len,
888 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
892 if (responseNum == HTTP_MOVED_TEMPORARILY) {
893 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
894 found_moved_temporarily,
895 (g_query ? "?" : ""),
896 (g_query ? g_query : ""));
899 if (ContentLength != -1) { /* file */
900 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
901 len += sprintf(iobuf + len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
902 tmp_str, "Content-length:", ContentLength);
904 strcat(iobuf, "\r\n");
907 len += sprintf(iobuf + len,
908 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
909 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
910 responseNum, responseString,
911 responseNum, responseString, infoString);
914 fprintf(stderr, "headers: '%s'\n", iobuf);
917 i++; /* write to fd #1 in inetd mode */
918 return full_write(i, iobuf, len);
921 static void send_headers_and_exit(HttpResponseNum responseNum) ATTRIBUTE_NORETURN;
922 static void send_headers_and_exit(HttpResponseNum responseNum)
924 sendHeaders(responseNum);
929 * Read from the socket until '\n' or EOF. '\r' chars are removed.
930 * '\n' is replaced with NUL.
931 * Return number of characters read or 0 if nothing is read
932 * ('\r' and '\n' are not counted).
933 * Data is returned in iobuf.
935 static int get_line(void)
939 /* We must not read extra chars. Reading byte-by-byte... */
940 while (read(accepted_socket, iobuf + count, 1) == 1) {
941 if (iobuf[count] == '\r')
943 if (iobuf[count] == '\n') {
947 if (count < (MAX_MEMORY_BUF - 1)) /* check overflow */
953 #if ENABLE_FEATURE_HTTPD_CGI
955 * Spawn CGI script, forward CGI's stdin/out <=> network
957 * Environment variables are set up and the script is invoked with pipes
958 * for stdin/stdout. If a post is being done the script is fed the POST
959 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
962 * const char *url The requested URL (with leading /).
963 * int bodyLen Length of the post body.
964 * const char *cookie For set HTTP_COOKIE.
965 * const char *content_type For set CONTENT_TYPE.
967 static void send_cgi_and_exit(
972 const char *content_type) ATTRIBUTE_NORETURN;
973 static void send_cgi_and_exit(
978 const char *content_type)
980 struct { int rd; int wr; } fromCgi; /* CGI -> httpd pipe */
981 struct { int rd; int wr; } toCgi; /* httpd -> CGI pipe */
982 char *argp[] = { NULL, NULL };
986 size_t post_read_size, post_read_idx;
992 * Note: We can use vfork() here in the no-mmu case, although
993 * the child modifies the parent's variables, due to:
994 * 1) The parent does not use the child-modified variables.
995 * 2) The allocated memory (in the child) is freed when the process
996 * exits. This happens instantly after the child finishes,
997 * since httpd is run from inetd (and it can't run standalone
999 * TODO: we can muck with environment _first_ and then fork/exec,
1000 * that will be more understandable, and safer wrt vfork!
1017 xfunc_error_retval = 242;
1019 if (accepted_socket > 1)
1020 close(accepted_socket);
1021 if (server_socket > 1)
1022 close(server_socket);
1024 xmove_fd(toCgi.rd, 0); /* replace stdin with the pipe */
1025 xmove_fd(fromCgi.wr, 1); /* replace stdout with the pipe */
1028 /* Huh? User seeing stderr can be a security problem.
1029 * If CGI really wants that, it can always do dup itself. */
1035 purl = xstrdup(url);
1037 while ((script = strchr(script + 1, '/')) != NULL) {
1038 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1042 if (!is_directory(purl + 1, 1, &sb)) {
1043 /* not directory, found script.cgi/PATH_INFO */
1047 *script = '/'; /* is directory, find next '/' */
1049 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1050 setenv1("REQUEST_METHOD", request);
1052 putenv(xasprintf("%s=%s?%s", "REQUEST_URI", purl, g_query));
1054 setenv1("REQUEST_URI", purl);
1057 *script = '\0'; /* cut off /PATH_INFO */
1059 /* SCRIPT_FILENAME required by PHP in CGI mode */
1060 fullpath = concat_path_file(home_httpd, purl);
1061 setenv1("SCRIPT_FILENAME", fullpath);
1062 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1063 setenv1("SCRIPT_NAME", purl);
1064 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1065 * QUERY_STRING: The information which follows the ? in the URL
1066 * which referenced this script. This is the query information.
1067 * It should not be decoded in any fashion. This variable
1068 * should always be set when there is query information,
1069 * regardless of command line decoding. */
1070 /* (Older versions of bbox seem to do some decoding) */
1071 setenv1("QUERY_STRING", g_query);
1072 putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1073 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1074 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1075 /* Having _separate_ variables for IP and port defeats
1076 * the purpose of having socket abstraction. Which "port"
1077 * are you using on Unix domain socket?
1078 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1081 char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
1082 char *cp = strrchr(p, ':');
1083 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1085 if (cp) *cp = '\0'; /* delete :PORT */
1086 setenv1("REMOTE_ADDR", p);
1089 setenv1("HTTP_USER_AGENT", user_agent);
1090 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1091 setenv_long("REMOTE_PORT", tcp_port);
1094 setenv_long("CONTENT_LENGTH", bodyLen);
1096 setenv1("HTTP_COOKIE", cookie);
1098 setenv1("CONTENT_TYPE", content_type);
1099 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1101 setenv1("REMOTE_USER", remoteuser);
1102 putenv((char*)"AUTH_TYPE=Basic");
1106 setenv1("HTTP_REFERER", referer);
1108 /* set execve argp[0] without path */
1109 argp[0] = (char*)bb_basename(purl);
1110 /* but script argp[0] must have absolute path */
1111 script = strrchr(fullpath, '/');
1113 goto error_execing_cgi;
1115 /* chdiring to script's dir */
1116 if (chdir(fullpath) == 0) {
1117 /* Now run the program. If it fails,
1118 * use _exit() so no destructors
1119 * get called and make a mess. */
1120 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1121 char *interpr = NULL;
1122 char *suffix = strrchr(purl, '.');
1126 for (cur = script_i; cur; cur = cur->next) {
1127 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1128 interpr = cur->after_colon;
1135 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1137 execv(interpr, argp);
1140 execv(fullpath, argp);
1144 * (we are CGI here, our stdout is pumped to the net) */
1145 accepted_socket = 1;
1146 sendHeaders(HTTP_NOT_FOUND);
1150 /* parent process */
1153 post_read_idx = 0; /* for gcc */
1157 /* If CGI dies, we still want to correctly finish reading its output
1158 * and send it to the peer. So please no SIGPIPEs! */
1159 signal(SIGPIPE, SIG_IGN);
1168 /* This loop still looks messy. What is an exit criteria?
1169 * "CGI's output closed"? Or "CGI has exited"?
1170 * What to do if CGI has closed both input and output, but
1171 * didn't exit? etc... */
1175 FD_SET(fromCgi.rd, &readSet);
1176 if (bodyLen > 0 || post_read_size > 0) {
1177 FD_SET(toCgi.wr, &writeSet);
1178 nfound = toCgi.wr > fromCgi.rd ? toCgi.wr : fromCgi.rd;
1179 if (post_read_size == 0) {
1180 FD_SET(accepted_socket, &readSet);
1181 if (nfound < accepted_socket)
1182 nfound = accepted_socket;
1184 /* Now wait on the set of sockets! */
1185 nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1188 close(toCgi.wr); /* no more POST data to CGI */
1191 nfound = select(fromCgi.rd + 1, &readSet, NULL, NULL, NULL);
1195 if (waitpid(pid, &status, WNOHANG) <= 0) {
1196 /* Weird. CGI didn't exit and no fd's
1197 * are ready, yet select returned?! */
1201 if (DEBUG && WIFEXITED(status))
1202 bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
1203 if (DEBUG && WIFSIGNALED(status))
1204 bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
1208 if (post_read_size > 0 && FD_ISSET(toCgi.wr, &writeSet)) {
1209 /* Have data from peer and can write to CGI */
1210 count = safe_write(toCgi.wr, wbuf + post_read_idx, post_read_size);
1211 /* Doesn't happen, we dont use nonblocking IO here
1212 *if (count < 0 && errno == EAGAIN) {
1216 post_read_idx += count;
1217 post_read_size -= count;
1219 post_read_size = bodyLen = 0; /* EOF/broken pipe to CGI */
1221 } else if (bodyLen > 0 && post_read_size == 0
1222 && FD_ISSET(accepted_socket, &readSet)
1224 /* We expect data, prev data portion is eaten by CGI
1225 * and there *is* data to read from the peer
1227 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1228 count = safe_read(accepted_socket, wbuf, count);
1230 post_read_size = count;
1234 bodyLen = 0; /* closed */
1238 #define PIPESIZE PIPE_BUF
1239 #if PIPESIZE >= MAX_MEMORY_BUF
1240 # error "PIPESIZE >= MAX_MEMORY_BUF"
1242 if (FD_ISSET(fromCgi.rd, &readSet)) {
1243 /* There is something to read from CGI */
1244 int s = accepted_socket;
1247 /* Are we still buffering CGI output? */
1248 if (buf_count >= 0) {
1249 /* According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1250 * CGI scripts MUST send their own header terminated by
1251 * empty line, then data. That's why we have only one
1252 * <cr><lf> pair here. We will output "200 OK" line
1253 * if needed, but CGI still has to provide blank line
1254 * between header and body */
1255 static const char HTTP_200[] ALIGN1 = "HTTP/1.0 200 OK\r\n";
1257 /* Must use safe_read, not full_read, because
1258 * CGI may output a few first bytes and then wait
1259 * for POSTDATA without closing stdout.
1260 * With full_read we may wait here forever. */
1261 count = safe_read(fromCgi.rd, rbuf + buf_count, PIPESIZE - 8);
1263 /* eof (or error) and there was no "HTTP",
1264 * so write it, then write received data */
1266 full_write(s, HTTP_200, sizeof(HTTP_200)-1);
1267 full_write(s, rbuf, buf_count);
1273 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1274 if (buf_count >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1275 /* send "HTTP/1.0 " */
1276 if (full_write(s, HTTP_200, 9) != 9)
1278 rbuf += 8; /* skip "Status: " */
1279 count = buf_count - 8;
1280 buf_count = -1; /* buffering off */
1281 } else if (buf_count >= 4) {
1282 /* Did CGI add "HTTP"? */
1283 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1284 /* there is no "HTTP", do it ourself */
1285 if (full_write(s, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1289 if (!strstr(rbuf, "ontent-")) {
1290 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1292 * Counter-example of valid CGI without Content-type:
1293 * echo -en "HTTP/1.0 302 Found\r\n"
1294 * echo -en "Location: http://www.busybox.net\r\n"
1298 buf_count = -1; /* buffering off */
1301 count = safe_read(fromCgi.rd, rbuf, PIPESIZE);
1303 break; /* eof (or error) */
1305 if (full_write(s, rbuf, count) != count)
1308 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1309 } /* if (FD_ISSET(fromCgi.rd)) */
1313 #endif /* FEATURE_HTTPD_CGI */
1316 * Send a file response to a HTTP request, and exit
1318 static void send_file_and_exit(const char *url) ATTRIBUTE_NORETURN;
1319 static void send_file_and_exit(const char *url)
1324 const char *const *table;
1325 const char *try_suffix;
1327 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1331 suffix = strrchr(url, '.');
1333 for (table = suffixTable; *table; table += 2)
1334 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1335 try_suffix += strlen(suffix);
1336 if (*try_suffix == 0 || *try_suffix == '.')
1339 /* also, if not found, set default as "application/octet-stream"; */
1340 found_mime_type = table[1];
1341 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1344 for (cur = mime_a; cur; cur = cur->next) {
1345 if (strcmp(cur->before_colon, suffix) == 0) {
1346 found_mime_type = cur->after_colon;
1351 #endif /* FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1354 bb_error_msg("sending file '%s' content-type: %s",
1355 url, found_mime_type);
1357 f = open(url, O_RDONLY);
1360 bb_perror_msg("cannot open '%s'", url);
1361 send_headers_and_exit(HTTP_NOT_FOUND);
1364 sendHeaders(HTTP_OK);
1365 fd = accepted_socket;
1367 fd++; /* write to fd #1 in inetd mode */
1369 /* If you want to know about EPIPE below
1370 * (happens if you abort downloads from local httpd): */
1371 /* signal(SIGPIPE, SIG_IGN); */
1373 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1375 /* byte count (3rd arg) is rounded down to 64k */
1376 count = sendfile(fd, f, &offset, MAXINT(ssize_t) - 0xffff);
1382 } while (count > 0);
1387 while ((count = safe_read(f, iobuf, MAX_MEMORY_BUF)) > 0) {
1389 count = full_write(fd, iobuf, count);
1393 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1396 if (count < 0 && verbose > 1)
1397 bb_perror_msg("error");
1401 static int checkPermIP(void)
1405 /* This could stand some work */
1406 for (cur = ip_a_d; cur; cur = cur->next) {
1409 "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1411 (unsigned char)(cur->ip >> 24),
1412 (unsigned char)(cur->ip >> 16),
1413 (unsigned char)(cur->ip >> 8),
1414 (unsigned char)(cur->ip),
1415 (unsigned char)(cur->mask >> 24),
1416 (unsigned char)(cur->mask >> 16),
1417 (unsigned char)(cur->mask >> 8),
1418 (unsigned char)(cur->mask)
1421 if ((rmt_ip & cur->mask) == cur->ip)
1422 return cur->allow_deny == 'A'; /* Allow/Deny */
1425 /* if unconfigured, return 1 - access from all */
1426 return !flg_deny_all;
1429 /****************************************************************************
1431 > $Function: checkPerm()
1433 * $Description: Check the permission file for access password protected.
1435 * If config file isn't present, everything is allowed.
1436 * Entries are of the form you can see example from header source
1439 * (const char *) path . . . . The file path.
1440 * (const char *) request . . . User information to validate.
1442 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1444 ****************************************************************************/
1446 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1447 static int checkPerm(const char *path, const char *request)
1453 const char *prev = NULL;
1455 /* This could stand some work */
1456 for (cur = g_auth; cur; cur = cur->next) {
1459 p0 = cur->before_colon;
1460 if (prev != NULL && strcmp(prev, p0) != 0)
1461 continue; /* find next identical */
1462 p = cur->after_colon;
1464 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1467 if (strncmp(p0, path, l) == 0
1468 && (l == 1 || path[l] == '/' || path[l] == '\0')
1471 /* path match found. Check request */
1472 /* for check next /path:user:password */
1474 u = strchr(request, ':');
1476 /* bad request, ':' required */
1480 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1484 if (strncmp(p, request, u-request) != 0) {
1485 /* user uncompared */
1488 pp = strchr(p, ':');
1489 if (pp && pp[1] == '$' && pp[2] == '1' &&
1490 pp[3] == '$' && pp[4]) {
1492 cipher = pw_encrypt(u+1, pp);
1493 if (strcmp(cipher, pp) == 0)
1494 goto set_remoteuser_var; /* Ok */
1500 if (strcmp(p, request) == 0) {
1502 remoteuser = strdup(request);
1504 remoteuser[(u - request)] = '\0';
1511 return prev == NULL;
1514 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1519 static void exit_on_signal(int sig) ATTRIBUTE_NORETURN;
1520 static void exit_on_signal(int sig)
1522 send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
1526 * Handle an incoming http request and exit.
1528 static void handle_incoming_and_exit(void) ATTRIBUTE_NORETURN;
1529 static void handle_incoming_and_exit(void)
1538 #if ENABLE_FEATURE_HTTPD_CGI
1539 const char *prequest = request_GET;
1540 unsigned long length = 0;
1542 char *content_type = 0;
1544 struct sigaction sa;
1546 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1547 int credentials = -1; /* if not required this is Ok */
1550 sa.sa_handler = exit_on_signal;
1551 sigemptyset(&sa.sa_mask);
1552 sa.sa_flags = 0; /* no SA_RESTART */
1553 sigaction(SIGALRM, &sa, NULL);
1555 /* It's not a real loop (it ends with while(0)).
1556 * Break from this "loop" jumps to exit(0) */
1560 _exit(0); /* EOF or error or empty line */
1562 purl = strpbrk(iobuf, " \t");
1564 send_headers_and_exit(HTTP_BAD_REQUEST);
1567 #if ENABLE_FEATURE_HTTPD_CGI
1568 if (strcasecmp(iobuf, prequest) != 0) {
1570 if (strcasecmp(iobuf, prequest) != 0) {
1571 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1575 if (strcasecmp(iobuf, request_GET) != 0) {
1576 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1580 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", iobuf, &blank);
1582 if (count < 1 || iobuf[0] != '/') {
1583 /* Garbled request/URL */
1584 send_headers_and_exit(HTTP_BAD_REQUEST);
1586 url = alloca(strlen(iobuf) + sizeof("/index.html"));
1588 send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
1591 /* extract url args if present */
1592 test = strchr(url, '?');
1599 test = decodeString(url, 0);
1601 send_headers_and_exit(HTTP_BAD_REQUEST);
1602 if (test == url + 1) {
1603 /* '/' or NUL is encoded */
1604 send_headers_and_exit(HTTP_NOT_FOUND);
1607 /* algorithm stolen from libbb bb_simplify_path(),
1608 * but don't strdup and reducing trailing slash and protect out root */
1612 /* skip duplicate (or initial) slash */
1617 /* skip extra '.' */
1618 if (test[1] == '/' || !test[1]) {
1621 /* '..': be careful */
1622 if (test[1] == '.' && (test[2] == '/' || !test[2])) {
1626 send_headers_and_exit(HTTP_BAD_REQUEST);
1628 while (*--purl != '/') /* omit previous dir */;
1635 *++purl = '\0'; /* so keep last character */
1636 test = purl; /* end ptr */
1638 /* If URL is directory, adding '/' */
1639 if (test[-1] != '/') {
1640 if (is_directory(url + 1, 1, &sb)) {
1641 found_moved_temporarily = url;
1645 bb_error_msg("url:%s", url);
1648 ip_allowed = checkPermIP();
1649 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1650 /* have path1/path2 */
1652 if (is_directory(url + 1, 1, &sb)) {
1653 /* may be having subdir config */
1654 parse_conf(url + 1, SUBDIR_PARSE);
1655 ip_allowed = checkPermIP();
1660 /* read until blank line for HTTP version specified, else parse immediate */
1664 break; /* EOF or error or empty line */
1667 bb_error_msg("header: '%s'", iobuf);
1668 #if ENABLE_FEATURE_HTTPD_CGI
1669 /* try and do our best to parse more lines */
1670 if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
1671 /* extra read only for POST */
1672 if (prequest != request_GET) {
1673 test = iobuf + sizeof("Content-length:") - 1;
1677 /* not using strtoul: it ignores leading minus! */
1678 length = strtol(test, &test, 10);
1679 /* length is "ulong", but we need to pass it to int later */
1680 /* so we check for negative or too large values in one go: */
1681 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1682 if (test[0] || errno || length > INT_MAX)
1685 } else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
1686 cookie = strdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
1687 } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
1688 content_type = strdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
1689 } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
1690 referer = strdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
1691 } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
1692 user_agent = strdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
1695 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1696 if (STRNCASECMP(iobuf, "Authorization:") == 0) {
1697 /* We only allow Basic credentials.
1698 * It shows up as "Authorization: Basic <userid:password>" where
1699 * the userid:password is base64 encoded.
1701 test = skip_whitespace(iobuf + sizeof("Authorization:")-1);
1702 if (STRNCASECMP(test, "Basic") != 0)
1704 test += sizeof("Basic")-1;
1705 /* decodeBase64() skips whitespace itself */
1707 credentials = checkPerm(url, test);
1709 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1710 } /* while extra header reading */
1714 if (strcmp(bb_basename(url), httpd_conf) == 0 || ip_allowed == 0) {
1715 /* protect listing [/path]/httpd_conf or IP deny */
1716 send_headers_and_exit(HTTP_FORBIDDEN);
1719 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1720 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1721 send_headers_and_exit(HTTP_UNAUTHORIZED);
1725 if (found_moved_temporarily) {
1726 send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
1729 test = url + 1; /* skip first '/' */
1731 #if ENABLE_FEATURE_HTTPD_CGI
1732 if (strncmp(test, "cgi-bin", 7) == 0) {
1733 if (test[7] == '/' && test[8] == '\0') {
1734 /* protect listing cgi-bin/ */
1735 send_headers_and_exit(HTTP_FORBIDDEN);
1737 send_cgi_and_exit(url, prequest, length, cookie, content_type);
1739 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1741 char *suffix = strrchr(test, '.');
1744 for (cur = script_i; cur; cur = cur->next) {
1745 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1746 send_cgi_and_exit(url, prequest, length, cookie, content_type);
1752 if (prequest != request_GET) {
1753 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1755 #endif /* FEATURE_HTTPD_CGI */
1756 if (purl[-1] == '/')
1757 strcpy(purl, "index.html");
1758 if (stat(test, &sb) == 0) {
1759 /* It's a dir URL and there is index.html */
1760 ContentLength = sb.st_size;
1761 last_mod = sb.st_mtime;
1763 #if ENABLE_FEATURE_HTTPD_CGI
1764 else if (purl[-1] == '/') {
1765 /* It's a dir URL and there is no index.html
1766 * Try cgi-bin/index.cgi */
1767 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1770 send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1773 #endif /* FEATURE_HTTPD_CGI */
1774 send_file_and_exit(test);
1779 #if 0 /* Is this needed? Why? */
1781 fprintf(stderr, "closing socket\n");
1782 #if ENABLE_FEATURE_HTTPD_CGI
1787 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1792 /* Properly wait for remote to closed */
1794 shutdown(accepted_socket, SHUT_WR);
1799 FD_SET(accepted_socket, &s_fd);
1802 retval = select(accepted_socket + 1, &s_fd, NULL, NULL, &tv);
1803 } while (retval > 0 && read(accepted_socket, iobuf, sizeof(iobuf) > 0));
1804 shutdown(accepted_socket, SHUT_RD);
1805 close(accepted_socket);
1812 * The main http server function.
1813 * Given an open socket, listen for new connections and farm out
1814 * the processing as a forked process.
1817 static void mini_httpd(int server) ATTRIBUTE_NORETURN;
1818 static void mini_httpd(int server)
1820 /* copy the ports we are watching to the readfd set */
1823 len_and_sockaddr fromAddr;
1825 /* Wait for connections... */
1826 fromAddr.len = LSA_SIZEOF_SA;
1827 n = accept(server, &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));
1833 accepted_socket = n;
1835 n = get_nport(&fromAddr.sa);
1836 tcp_port = ntohs(n);
1838 if (fromAddr.sa.sa_family == AF_INET) {
1839 rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1841 if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1843 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddr.len);
1848 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1849 /* Do not reload config on HUP */
1850 signal(SIGHUP, SIG_IGN);
1853 /* this trick makes -v logging much simpler */
1854 applet_name = rmt_ip_str;
1856 bb_error_msg("connected");
1858 handle_incoming_and_exit();
1860 /* parent, or fork failed */
1861 close(accepted_socket);
1868 static void mini_httpd_inetd(void) ATTRIBUTE_NORETURN;
1869 static void mini_httpd_inetd(void)
1872 len_and_sockaddr fromAddr;
1874 fromAddr.len = LSA_SIZEOF_SA;
1875 getpeername(0, &fromAddr.sa, &fromAddr.len);
1876 n = get_nport(&fromAddr.sa);
1877 tcp_port = ntohs(n);
1879 if (fromAddr.sa.sa_family == AF_INET) {
1880 rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1882 if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1883 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddr.len);
1885 handle_incoming_and_exit();
1888 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1889 static void sighup_handler(int sig)
1892 struct sigaction sa;
1894 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1895 sa.sa_handler = sighup_handler;
1896 sigemptyset(&sa.sa_mask);
1897 sa.sa_flags = SA_RESTART;
1898 sigaction(SIGHUP, &sa, NULL);
1903 c_opt_config_file = 0,
1906 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1907 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1908 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1909 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1914 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1915 OPT_DECODE_URL = 1 << d_opt_decode_url,
1916 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1917 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1918 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1919 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1920 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1921 OPT_PORT = 1 << p_opt_port,
1922 OPT_INETD = 1 << p_opt_inetd,
1923 OPT_FOREGROUND = 1 << p_opt_foreground,
1924 OPT_VERBOSE = 1 << p_opt_verbose,
1928 int httpd_main(int argc, char **argv);
1929 int httpd_main(int argc, char **argv)
1932 char *url_for_decode;
1933 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1934 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1935 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1936 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1938 #if ENABLE_LOCALE_SUPPORT
1939 /* Undo busybox.c: we want to speak English in http (dates etc) */
1940 setlocale(LC_TIME, "C");
1944 home_httpd = xrealloc_getcwd_or_warn(NULL);
1945 opt_complementary = "vv"; /* counter */
1946 /* We do not "absolutize" path given by -h (home) opt.
1947 * If user gives relative path in -h, $SCRIPT_FILENAME can end up
1949 opt = getopt32(argc, argv, "c:d:h:"
1950 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1951 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1952 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1953 USE_FEATURE_HTTPD_SETUID("u:")
1955 &configFile, &url_for_decode, &home_httpd
1956 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1957 USE_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
1958 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1959 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1960 , &bind_addr_or_port
1963 if (opt & OPT_DECODE_URL) {
1964 printf("%s", decodeString(url_for_decode, 1));
1967 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1968 if (opt & OPT_ENCODE_URL) {
1969 printf("%s", encodeString(url_for_encode));
1973 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1974 if (opt & OPT_MD5) {
1975 puts(pw_encrypt(pass, "$1$"));
1979 #if ENABLE_FEATURE_HTTPD_SETUID
1980 if (opt & OPT_SETUID) {
1981 if (!get_uidgid(&ugid, s_ugid, 1))
1982 bb_error_msg_and_die("unrecognized user[:group] "
1983 "name '%s'", s_ugid);
1988 if (!(opt & OPT_INETD)) {
1990 signal(SIGCHLD, SIG_IGN);
1991 server_socket = openServer();
1992 #if ENABLE_FEATURE_HTTPD_SETUID
1993 /* drop privileges */
1994 if (opt & OPT_SETUID) {
1995 if (ugid.gid != (gid_t)-1) {
1996 if (setgroups(1, &ugid.gid) == -1)
1997 bb_perror_msg_and_die("setgroups");
2004 bb_error_msg_and_die("-i is required");
2008 #if ENABLE_FEATURE_HTTPD_CGI
2010 char *p = getenv("PATH");
2011 /* env strings themself are not freed, no need to strdup(p): */
2015 if (!(opt & OPT_INETD))
2016 setenv_long("SERVER_PORT", tcp_port);
2020 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2023 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2027 if (opt & OPT_INETD)
2029 if (!(opt & OPT_FOREGROUND))
2030 bb_daemonize(0); /* don't change current directory */
2031 mini_httpd(server_socket); /* never returns */
2033 mini_httpd_inetd(); /* never returns */