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.
96 /* amount of buffering in a pipe */
98 # define PIPE_BUF 4096
101 static const char default_path_httpd_conf[] = "/etc";
102 static const char httpd_conf[] = "httpd.conf";
106 // Note: busybox xfuncs are not used because we want the server to keep running
107 // if something bad happens due to a malformed user request.
108 // As a result, all memory allocation after daemonize
109 // is checked rigorously
114 #define MAX_MEMORY_BUFF 8192 /* IO buffer */
116 typedef struct HT_ACCESS {
118 struct HT_ACCESS *next;
119 char before_colon[1]; /* really bigger, must last */
122 typedef struct HT_ACCESS_IP {
126 struct HT_ACCESS_IP *next;
132 volatile smallint alarm_signaled;
133 smallint flg_deny_all;
135 const char *configFile;
136 const char *home_httpd;
139 const char *found_mime_type;
140 const char *found_moved_temporarily;
141 off_t ContentLength; /* -1 - unknown */
143 Htaccess_IP *ip_a_d; /* config allow/deny lines */
145 USE_FEATURE_HTTPD_BASIC_AUTH(const char *g_realm;)
146 USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
147 USE_FEATURE_HTTPD_CGI(char *referer;)
149 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
150 char *rmt_ip_str; /* for set env REMOTE_ADDR */
152 unsigned tcp_port; /* server initial port and for
153 set env REMOTE_PORT */
154 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
155 Htaccess *g_auth; /* config user:password lines */
157 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
158 Htaccess *mime_a; /* config mime types */
160 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
161 Htaccess *script_i; /* config script interpreters */
163 char iobuf[MAX_MEMORY_BUFF];
165 #define G (*ptr_to_globals)
166 #define server_socket (G.server_socket )
167 #define accepted_socket (G.accepted_socket)
168 #define alarm_signaled (G.alarm_signaled )
169 #define flg_deny_all (G.flg_deny_all )
170 #define g_query (G.g_query )
171 #define configFile (G.configFile )
172 #define home_httpd (G.home_httpd )
173 #define rmt_ip (G.rmt_ip )
174 #define found_mime_type (G.found_mime_type)
175 #define found_moved_temporarily (G.found_moved_temporarily)
176 #define ContentLength (G.ContentLength )
177 #define last_mod (G.last_mod )
178 #define ip_a_d (G.ip_a_d )
179 #define g_realm (G.g_realm )
180 #define remoteuser (G.remoteuser )
181 #define referer (G.referer )
182 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
183 #define rmt_ip_str (G.rmt_ip_str )
185 #define tcp_port (G.tcp_port )
186 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
187 #define g_auth (G.g_auth )
189 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
190 #define mime_a (G.mime_a )
192 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
193 #define script_i (G.script_i )
195 #define iobuf (G.iobuf )
196 #define INIT_G() do { \
197 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
198 USE_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
200 ContentLength = -1; \
203 static const char request_GET[] = "GET"; /* size algorithmic optimize */
205 static const char* const suffixTable [] = {
206 /* Warning: shorted equivalent suffix in one line must be first */
207 ".htm.html", "text/html",
208 ".jpg.jpeg", "image/jpeg",
211 ".txt.h.c.cc.cpp", "text/plain",
214 ".avi", "video/x-msvideo",
215 ".qt.mov", "video/quicktime",
216 ".mpe.mpeg", "video/mpeg",
217 ".mid.midi", "audio/midi",
218 ".mp3", "audio/mpeg",
219 #if 0 /* unpopular */
220 ".au", "audio/basic",
221 ".pac", "application/x-ns-proxy-autoconfig",
222 ".vrml.wrl", "model/vrml",
224 0, "application/octet-stream" /* default */
229 HTTP_MOVED_TEMPORARILY = 302,
230 HTTP_BAD_REQUEST = 400, /* malformed syntax */
231 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
232 HTTP_NOT_FOUND = 404,
233 HTTP_FORBIDDEN = 403,
234 HTTP_REQUEST_TIMEOUT = 408,
235 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
236 HTTP_INTERNAL_SERVER_ERROR = 500,
237 #if 0 /* future use */
239 HTTP_SWITCHING_PROTOCOLS = 101,
242 HTTP_NON_AUTHORITATIVE_INFO = 203,
243 HTTP_NO_CONTENT = 204,
244 HTTP_MULTIPLE_CHOICES = 300,
245 HTTP_MOVED_PERMANENTLY = 301,
246 HTTP_NOT_MODIFIED = 304,
247 HTTP_PAYMENT_REQUIRED = 402,
248 HTTP_BAD_GATEWAY = 502,
249 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
250 HTTP_RESPONSE_SETSIZE = 0xffffffff
255 HttpResponseNum type;
260 static const HttpEnumString httpResponseNames[] = {
261 { HTTP_OK, "OK", NULL },
262 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
263 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
264 "No request appeared within a reasonable time period." },
265 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
266 "The requested method is not recognized by this server." },
267 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
268 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
270 { HTTP_NOT_FOUND, "Not Found",
271 "The requested URL was not found on this server." },
272 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
273 { HTTP_FORBIDDEN, "Forbidden", "" },
274 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
275 "Internal Server Error" },
276 #if 0 /* not implemented */
277 { HTTP_CREATED, "Created" },
278 { HTTP_ACCEPTED, "Accepted" },
279 { HTTP_NO_CONTENT, "No Content" },
280 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
281 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
282 { HTTP_NOT_MODIFIED, "Not Modified" },
283 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
284 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
289 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
292 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
295 static int scan_ip(const char **ep, unsigned *ip, unsigned char endc)
302 for (j = 0; j < 4; j++) {
305 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
308 while (*p >= '0' && *p <= '9') {
317 if (*p != '/' && *p != 0)
319 *ip = ((*ip) << 8) | octet;
332 static int scan_ip_mask(const char *ipm, unsigned *ip, unsigned *mask)
337 i = scan_ip(&ipm, ip, '/');
345 if (*p < '0' || *p > '9') {
347 i = scan_ip(&ipm, mask, 0);
369 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
370 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
371 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
372 static void free_config_lines(Htaccess **pprev)
374 Htaccess *prev = *pprev;
377 Htaccess *cur = prev;
387 #define FIRST_PARSE 0
388 #define SUBDIR_PARSE 1
389 #define SIGNALED_PARSE 2
390 #define FIND_FROM_HTTPD_ROOT 3
391 /****************************************************************************
393 > $Function: parse_conf()
395 * $Description: parse configuration file into in-memory linked list.
397 * The first non-white character is examined to determine if the config line
398 * is one of the following:
399 * .ext:mime/type # new mime type not compiled into httpd
400 * [adAD]:from # ip address allow/deny, * for wildcard
401 * /path:user:pass # username/password
403 * Any previous IP rules are discarded.
404 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
405 * are also discarded. That is, previous settings are retained if flag is
409 * (const char *) path . . null for ip address checks, path for password
411 * (int) flag . . . . . . the source of the parse request.
415 ****************************************************************************/
416 static void parse_conf(const char *path, int flag)
419 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
422 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
423 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
424 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
428 const char *cf = configFile;
433 /* free previous ip setup if present */
434 Htaccess_IP *pip = ip_a_d;
437 Htaccess_IP *cur_ipl = pip;
446 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
447 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
448 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
449 /* retain previous auth and mime config only for subdir parse */
450 if (flag != SUBDIR_PARSE) {
451 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
452 free_config_lines(&g_auth);
454 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
455 free_config_lines(&mime_a);
457 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
458 free_config_lines(&script_i);
463 if (flag == SUBDIR_PARSE || cf == NULL) {
464 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
466 if (flag == FIRST_PARSE)
467 bb_error_msg_and_die(bb_msg_memory_exhausted);
470 sprintf((char *)cf, "%s/%s", path, httpd_conf);
473 while ((f = fopen(cf, "r")) == NULL) {
474 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
475 /* config file not found, no changes to config */
478 if (configFile && flag == FIRST_PARSE) /* if -c option given */
479 bb_perror_msg_and_die("%s", cf);
480 flag = FIND_FROM_HTTPD_ROOT;
484 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
487 /* This could stand some work */
488 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
490 for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
493 if (*p0 == ':' && c == NULL)
499 /* test for empty or strange line */
500 if (c == NULL || *c == 0)
507 /* memorize deny all */
510 /* skip default other "word:*" config lines */
516 else if (*p0 != 'D' && *p0 != 'A'
517 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
520 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
523 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
528 if (*p0 == 'A' || *p0 == 'D') {
529 /* storing current config IP line */
530 pip = xzalloc(sizeof(Htaccess_IP));
532 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
533 /* syntax IP{/mask} error detected, protect all */
537 pip->allow_deny = *p0;
539 /* Deny:form_IP move top */
543 /* add to bottom A:form_IP config line */
544 Htaccess_IP *prev_IP = ip_a_d;
546 if (prev_IP == NULL) {
549 while (prev_IP->next)
550 prev_IP = prev_IP->next;
557 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
559 /* make full path from httpd root / curent_path / config_line_path */
560 cf = flag == SUBDIR_PARSE ? path : "";
561 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
565 sprintf(p0, "/%s%s", cf, buf);
567 /* another call bb_simplify_path */
572 if (*cf == '/') { /* skip duplicate (or initial) slash */
574 } else if (*cf == '.') {
575 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
577 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
580 while (*--p != '/') /* omit previous dir */;
589 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
590 ++p; /* so keep last character */
593 sprintf(p0, "%s:%s", p0, c);
597 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
598 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
599 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
600 /* storing current config line */
601 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
603 cf = strcpy(cur->before_colon, p0);
606 cur->after_colon = c;
607 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
609 /* config .mime line move top for overwrite previous */
615 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
616 if (*cf == '*' && cf[1] == '.') {
617 /* config script interpreter line move top for overwrite previous */
618 cur->next = script_i;
623 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
629 /* sort path, if current lenght eq or bigger then move up */
630 Htaccess *prev_hti = g_auth;
631 size_t l = strlen(cf);
634 for (hti = prev_hti; hti; hti = hti->next) {
635 if (l >= strlen(hti->before_colon)) {
636 /* insert before hti */
638 if (prev_hti != hti) {
639 prev_hti->next = cur;
647 prev_hti = prev_hti->next;
649 if (!hti) { /* not inserted, add to bottom */
661 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
662 /****************************************************************************
664 > $Function: encodeString()
666 * $Description: Given a string, html encode special characters.
667 * This is used for the -e command line option to provide an easy way
668 * for scripts to encode result data without confusing browsers. The
669 * returned string pointer is memory allocated by malloc().
672 * (const char *) string . . The first string to encode.
674 * $Return: (char *) . . . .. . . A pointer to the encoded string.
676 * $Errors: Returns a null string ("") if memory is not available.
678 ****************************************************************************/
679 static char *encodeString(const char *string)
681 /* take the simple route and encode everything */
682 /* could possibly scan once to get length. */
683 int len = strlen(string);
684 char *out = xmalloc(len * 6 + 1);
688 while ((ch = *string++)) {
689 // very simple check for what to encode
690 if (isalnum(ch)) *p++ = ch;
691 else p += sprintf(p, "&#%d;", (unsigned char) ch);
696 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
698 /****************************************************************************
700 > $Function: decodeString()
702 * $Description: Given a URL encoded string, convert it to plain ascii.
703 * Since decoding always makes strings smaller, the decode is done in-place.
704 * Thus, callers should strdup() the argument if they do not want the
705 * argument modified. The return is the original pointer, allowing this
706 * function to be easily used as arguments to other functions.
709 * (char *) string . . . The first string to decode.
710 * (int) option_d . . 1 if called for httpd -d
712 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
716 ****************************************************************************/
717 static char *decodeString(char *orig, int option_d)
719 /* note that decoded string is always shorter than original */
724 while ((c = *ptr++) != '\0') {
725 unsigned value1, value2;
727 if (option_d && c == '+') {
735 if (sscanf(ptr, "%1X", &value1) != 1
736 || sscanf(ptr+1, "%1X", &value2) != 1
743 value1 = value1 * 16 + value2;
744 if (!option_d && (value1 == '/' || value1 == '\0')) {
745 /* caller takes it as indication of invalid
746 * (dangerous wrt exploits) chars */
757 #if ENABLE_FEATURE_HTTPD_CGI
758 /****************************************************************************
760 ****************************************************************************/
761 static void setenv1(const char *name, const char *value)
765 setenv(name, value, 1);
767 static void setenv_long(const char *name, long value)
769 char buf[sizeof(value)*3 + 1];
770 sprintf(buf, "%ld", value);
771 setenv(name, buf, 1);
775 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
776 /****************************************************************************
778 > $Function: decodeBase64()
780 > $Description: Decode a base 64 data stream as per rfc1521.
781 * Note that the rfc states that none base64 chars are to be ignored.
782 * Since the decode always results in a shorter size than the input, it is
783 * OK to pass the input arg as an output arg.
786 * (char *) Data . . . . A pointer to a base64 encoded string.
787 * Where to place the decoded data.
793 ****************************************************************************/
794 static void decodeBase64(char *Data)
796 const unsigned char *in = (const unsigned char *)Data;
797 // The decoded size will be at most 3/4 the size of the encoded
804 if (t >= '0' && t <= '9')
806 else if (t >= 'A' && t <= 'Z')
808 else if (t >= 'a' && t <= 'z')
822 *Data++ = (char) (ch >> 16);
823 *Data++ = (char) (ch >> 8);
833 /****************************************************************************
835 > $Function: openServer()
837 * $Description: create a listen server socket on the designated port.
839 * $Return: (int) . . . A connection socket. -1 for errors.
843 ****************************************************************************/
844 static int openServer(void)
848 /* create the socket right now */
849 fd = create_and_bind_stream_or_die(NULL, tcp_port);
854 /****************************************************************************
856 > $Function: sendHeaders()
858 * $Description: Create and send HTTP response headers.
859 * The arguments are combined and sent as one write operation. Note that
860 * IE will puke big-time if the headers are not sent in one packet and the
861 * second packet is delayed for any reason.
864 * (HttpResponseNum) responseNum . . . The result code to send.
866 * $Return: (int) . . . . writing errors
868 ****************************************************************************/
869 static int sendHeaders(HttpResponseNum responseNum)
872 const char *responseString = "";
873 const char *infoString = 0;
874 const char *mime_type;
876 time_t timer = time(0);
880 numNames = sizeof(httpResponseNames) / sizeof(httpResponseNames[0])
883 for (i = 0; i < numNames; i++) {
884 if (httpResponseNames[i].type == responseNum) {
885 responseString = httpResponseNames[i].name;
886 infoString = httpResponseNames[i].info;
890 /* error message is HTML */
891 mime_type = responseNum == HTTP_OK ?
892 found_mime_type : "text/html";
894 /* emit the current date */
895 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
897 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
898 "Date: %s\r\nConnection: close\r\n",
899 responseNum, responseString, mime_type, timeStr);
901 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
902 if (responseNum == HTTP_UNAUTHORIZED) {
903 len += sprintf(buf+len,
904 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
908 if (responseNum == HTTP_MOVED_TEMPORARILY) {
909 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
910 found_moved_temporarily,
911 (g_query ? "?" : ""),
912 (g_query ? g_query : ""));
915 if (ContentLength != -1) { /* file */
916 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&last_mod));
917 len += sprintf(buf+len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
918 timeStr, "Content-length:", ContentLength);
923 len += sprintf(buf+len,
924 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
925 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
926 responseNum, responseString,
927 responseNum, responseString, infoString);
930 fprintf(stderr, "headers: '%s'\n", buf);
932 if (i == 0) i++; /* write to fd# 1 in inetd mode */
933 return full_write(i, buf, len);
936 /****************************************************************************
938 > $Function: getLine()
940 * $Description: Read from the socket until an end of line char found.
942 * Characters are read one at a time until an eol sequence is found.
944 * $Return: (int) . . . . number of characters read. -1 if error.
946 ****************************************************************************/
947 static int getLine(void)
952 while (read(accepted_socket, buf + count, 1) == 1) {
953 if (buf[count] == '\r') continue;
954 if (buf[count] == '\n') {
958 if (count < (MAX_MEMORY_BUFF-1)) /* check overflow */
961 if (count) return count;
965 #if ENABLE_FEATURE_HTTPD_CGI
966 /****************************************************************************
968 > $Function: sendCgi()
970 * $Description: Execute a CGI script and send it's stdout back
972 * Environment variables are set up and the script is invoked with pipes
973 * for stdin/stdout. If a post is being done the script is fed the POST
974 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
977 * (const char *) url . . . . . . The requested URL (with leading /).
978 * (int bodyLen) . . . . . . . . Length of the post body.
979 * (const char *cookie) . . . . . For set HTTP_COOKIE.
980 * (const char *content_type) . . For set CONTENT_TYPE.
982 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
986 ****************************************************************************/
987 static int sendCgi(const char *url,
988 const char *request, int bodyLen, const char *cookie,
989 const char *content_type)
991 int fromCgi[2]; /* pipe for reading data from CGI */
992 int toCgi[2]; /* pipe for sending data to CGI */
994 char *argp[] = { NULL, NULL };
1000 size_t post_read_size, post_read_idx;
1002 if (pipe(fromCgi) != 0)
1004 if (pipe(toCgi) != 0)
1008 * Note: We can use vfork() here in the no-mmu case, although
1009 * the child modifies the parent's variables, due to:
1010 * 1) The parent does not use the child-modified variables.
1011 * 2) The allocated memory (in the child) is freed when the process
1012 * exits. This happens instantly after the child finishes,
1013 * since httpd is run from inetd (and it can't run standalone
1017 // FIXME: setenv leaks memory! (old values of env vars are leaked)
1018 // Thus we have a bug on NOMMU.
1019 // Need to use this instead:
1020 // [malloc +] putenv + (in child: exec) + (in parent: unsetenv [+ free])
1036 if (accepted_socket > 1)
1037 close(accepted_socket);
1038 if (server_socket > 1)
1039 close(server_socket);
1041 xmove_fd(toCgi[0], 0); /* replace stdin with the pipe */
1042 xmove_fd(fromCgi[1], 1); /* replace stdout with the pipe */
1045 /* Huh? User seeing stderr can be a security problem...
1046 * and if CGI really wants that, it can always dup2(1,2)...
1047 * dup2(fromCgi[1], 2); */
1052 xfunc_error_retval = 242;
1053 purl = xstrdup(url);
1055 while ((script = strchr(script + 1, '/')) != NULL) {
1056 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1060 if (is_directory(purl + 1, 1, &sb) == 0) {
1061 /* not directory, found script.cgi/PATH_INFO */
1065 *script = '/'; /* is directory, find next '/' */
1067 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1068 setenv1("REQUEST_METHOD", request);
1070 char *uri = alloca(strlen(purl) + 2 + strlen(g_query));
1072 sprintf(uri, "%s?%s", purl, g_query);
1073 setenv1("REQUEST_URI", uri);
1075 setenv1("REQUEST_URI", purl);
1078 *script = '\0'; /* cut off /PATH_INFO */
1080 /* SCRIPT_FILENAME required by PHP in CGI mode */
1081 fullpath = concat_path_file(home_httpd, purl);
1082 setenv1("SCRIPT_FILENAME", fullpath);
1083 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1084 setenv1("SCRIPT_NAME", purl);
1085 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1086 * QUERY_STRING: The information which follows the ? in the URL
1087 * which referenced this script. This is the query information.
1088 * It should not be decoded in any fashion. This variable
1089 * should always be set when there is query information,
1090 * regardless of command line decoding. */
1091 /* (Older versions of bbox seem to do some decoding) */
1092 setenv1("QUERY_STRING", g_query);
1093 putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1094 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1095 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1096 /* Having _separate_ variables for IP and port defeats
1097 * the purpose of having socket abstraction. Which "port"
1098 * are you using on Unix domain socket?
1099 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1102 char *p = rmt_ip_str ? : (char*)"";
1103 char *cp = strrchr(p, ':');
1104 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1106 if (cp) *cp = '\0'; /* delete :PORT */
1107 setenv1("REMOTE_ADDR", p);
1110 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1111 setenv_long("REMOTE_PORT", tcp_port);
1114 setenv_long("CONTENT_LENGTH", bodyLen);
1116 setenv1("HTTP_COOKIE", cookie);
1118 setenv1("CONTENT_TYPE", content_type);
1119 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1121 setenv1("REMOTE_USER", remoteuser);
1122 putenv((char*)"AUTH_TYPE=Basic");
1126 setenv1("HTTP_REFERER", referer);
1128 /* set execve argp[0] without path */
1129 argp[0] = strrchr(purl, '/') + 1;
1130 /* but script argp[0] must have absolute path and chdiring to this */
1131 script = strrchr(fullpath, '/');
1133 goto error_execing_cgi;
1135 if (chdir(fullpath) == 0) {
1136 // Now run the program. If it fails,
1137 // use _exit() so no destructors
1138 // get called and make a mess.
1139 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1140 char *interpr = NULL;
1141 char *suffix = strrchr(purl, '.');
1145 for (cur = script_i; cur; cur = cur->next) {
1146 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1147 interpr = cur->after_colon;
1154 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1156 execv(interpr, argp);
1159 execv(fullpath, argp);
1162 /* send to stdout (even if we are not from inetd) */
1163 accepted_socket = 1;
1164 sendHeaders(HTTP_NOT_FOUND);
1168 /* parent process */
1175 post_read_idx = 0; /* for gcc */
1180 signal(SIGPIPE, SIG_IGN);
1191 FD_SET(inFd, &readSet);
1192 if (bodyLen > 0 || post_read_size > 0) {
1193 FD_SET(outFd, &writeSet);
1194 nfound = outFd > inFd ? outFd : inFd;
1195 if (post_read_size == 0) {
1196 FD_SET(accepted_socket, &readSet);
1197 if (nfound < accepted_socket)
1198 nfound = accepted_socket;
1200 /* Now wait on the set of sockets! */
1201 nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1204 close(outFd); /* no more POST data to CGI */
1207 nfound = select(inFd + 1, &readSet, NULL, NULL, NULL);
1211 if (waitpid(pid, &status, WNOHANG) <= 0) {
1212 /* Weird. CGI didn't exit and no fd's
1213 * are ready, yet select returned?! */
1217 if (DEBUG && WIFEXITED(status))
1218 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1219 if (DEBUG && WIFSIGNALED(status))
1220 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1224 if (post_read_size > 0 && FD_ISSET(outFd, &writeSet)) {
1225 /* Have data from peer and can write to CGI */
1226 // huh? why full_write? what if we will block?
1227 // (imagine that CGI does not read its stdin...)
1228 count = full_write(outFd, wbuf + post_read_idx, post_read_size);
1230 post_read_idx += count;
1231 post_read_size -= count;
1233 post_read_size = bodyLen = 0; /* broken pipe to CGI */
1235 } else if (bodyLen > 0 && post_read_size == 0
1236 && FD_ISSET(accepted_socket, &readSet)
1238 /* We expect data, prev data portion is eaten by CGI
1239 * and there *is* data to read from the peer
1241 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1242 count = safe_read(accepted_socket, wbuf, count);
1244 post_read_size = count;
1248 bodyLen = 0; /* closed */
1252 #define PIPESIZE PIPE_BUF
1253 #if PIPESIZE >= MAX_MEMORY_BUFF
1254 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1256 if (FD_ISSET(inFd, &readSet)) {
1257 /* There is something to read from CGI */
1258 int s = accepted_socket;
1261 /* Are we still buffering CGI output? */
1262 if (buf_count >= 0) {
1263 static const char HTTP_200[] = "HTTP/1.0 200 OK\r\n";
1264 /* Must use safe_read, not full_read, because
1265 * CGI may output a few first bytes and then wait
1266 * for POSTDATA without closing stdout.
1267 * With full_read we may wait here forever. */
1268 count = safe_read(inFd, rbuf + buf_count, PIPESIZE - 4);
1270 /* eof (or error) and there was no "HTTP",
1271 * so add one and write out the received data */
1273 full_write(s, HTTP_200, sizeof(HTTP_200)-1);
1274 full_write(s, rbuf, buf_count);
1280 if (buf_count >= 4) {
1281 /* check to see if CGI added "HTTP" */
1282 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1283 /* there is no "HTTP", do it ourself */
1284 if (full_write(s, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1287 /* example of valid CGI without "Content-type:"
1288 * echo -en "HTTP/1.0 302 Found\r\n"
1289 * echo -en "Location: http://www.busybox.net\r\n"
1291 if (!strstr(rbuf, "ontent-")) {
1292 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1296 buf_count = -1; /* buffering off */
1299 count = safe_read(inFd, rbuf, PIPESIZE);
1301 break; /* eof (or error) */
1303 if (full_write(s, rbuf, count) != count)
1306 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1307 } /* if (FD_ISSET(inFd)) */
1311 #endif /* FEATURE_HTTPD_CGI */
1313 /****************************************************************************
1315 > $Function: sendFile()
1317 * $Description: Send a file response to a HTTP request
1320 * (const char *) url . . The URL requested.
1322 * $Return: (int) . . . . . . Always 0.
1324 ****************************************************************************/
1325 static int sendFile(const char *url)
1329 const char * const * table;
1330 const char * try_suffix;
1332 suffix = strrchr(url, '.');
1334 for (table = suffixTable; *table; table += 2)
1335 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1336 try_suffix += strlen(suffix);
1337 if (*try_suffix == 0 || *try_suffix == '.')
1340 /* also, if not found, set default as "application/octet-stream"; */
1341 found_mime_type = table[1];
1342 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1346 for (cur = mime_a; cur; cur = cur->next) {
1347 if (strcmp(cur->before_colon, suffix) == 0) {
1348 found_mime_type = cur->after_colon;
1353 #endif /* FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1356 fprintf(stderr, "sending file '%s' content-type: %s\n",
1357 url, found_mime_type);
1359 f = open(url, O_RDONLY);
1364 sendHeaders(HTTP_OK);
1365 /* TODO: sendfile() */
1366 while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1367 int fd = accepted_socket;
1368 if (fd == 0) fd++; /* write to fd# 1 in inetd mode */
1369 if (full_write(fd, buf, count) != count)
1375 bb_perror_msg("cannot open '%s'", url);
1376 sendHeaders(HTTP_NOT_FOUND);
1382 static int checkPermIP(void)
1386 /* This could stand some work */
1387 for (cur = ip_a_d; cur; cur = cur->next) {
1388 #if ENABLE_FEATURE_HTTPD_CGI && DEBUG
1389 fprintf(stderr, "checkPermIP: '%s' ? ", rmt_ip_str);
1392 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1393 (unsigned char)(cur->ip >> 24),
1394 (unsigned char)(cur->ip >> 16),
1395 (unsigned char)(cur->ip >> 8),
1396 (unsigned char)(cur->ip),
1397 (unsigned char)(cur->mask >> 24),
1398 (unsigned char)(cur->mask >> 16),
1399 (unsigned char)(cur->mask >> 8),
1400 (unsigned char)(cur->mask)
1403 if ((rmt_ip & cur->mask) == cur->ip)
1404 return cur->allow_deny == 'A'; /* Allow/Deny */
1407 /* if unconfigured, return 1 - access from all */
1408 return !flg_deny_all;
1411 /****************************************************************************
1413 > $Function: checkPerm()
1415 * $Description: Check the permission file for access password protected.
1417 * If config file isn't present, everything is allowed.
1418 * Entries are of the form you can see example from header source
1421 * (const char *) path . . . . The file path.
1422 * (const char *) request . . . User information to validate.
1424 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1426 ****************************************************************************/
1428 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1429 static int checkPerm(const char *path, const char *request)
1435 const char *prev = NULL;
1437 /* This could stand some work */
1438 for (cur = g_auth; cur; cur = cur->next) {
1441 p0 = cur->before_colon;
1442 if (prev != NULL && strcmp(prev, p0) != 0)
1443 continue; /* find next identical */
1444 p = cur->after_colon;
1446 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1449 if (strncmp(p0, path, l) == 0
1450 && (l == 1 || path[l] == '/' || path[l] == '\0')
1453 /* path match found. Check request */
1454 /* for check next /path:user:password */
1456 u = strchr(request, ':');
1458 /* bad request, ':' required */
1462 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1466 if (strncmp(p, request, u-request) != 0) {
1467 /* user uncompared */
1470 pp = strchr(p, ':');
1471 if (pp && pp[1] == '$' && pp[2] == '1' &&
1472 pp[3] == '$' && pp[4]) {
1474 cipher = pw_encrypt(u+1, pp);
1475 if (strcmp(cipher, pp) == 0)
1476 goto set_remoteuser_var; /* Ok */
1482 if (strcmp(p, request) == 0) {
1484 remoteuser = strdup(request);
1486 remoteuser[(u - request)] = 0;
1493 return prev == NULL;
1496 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1498 /****************************************************************************
1500 > $Function: handle_sigalrm()
1502 * $Description: Handle timeouts
1504 ****************************************************************************/
1506 static void handle_sigalrm(int sig)
1508 sendHeaders(HTTP_REQUEST_TIMEOUT);
1512 /****************************************************************************
1514 > $Function: handleIncoming()
1516 * $Description: Handle an incoming http request.
1518 ****************************************************************************/
1519 static void handleIncoming(void)
1528 #if ENABLE_FEATURE_HTTPD_CGI
1529 const char *prequest = request_GET;
1530 unsigned long length = 0;
1532 char *content_type = 0;
1537 struct sigaction sa;
1539 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1540 int credentials = -1; /* if not required this is Ok */
1543 sa.sa_handler = handle_sigalrm;
1544 sigemptyset(&sa.sa_mask);
1545 sa.sa_flags = 0; /* no SA_RESTART */
1546 sigaction(SIGALRM, &sa, NULL);
1551 (void) alarm(TIMEOUT);
1555 purl = strpbrk(buf, " \t");
1558 sendHeaders(HTTP_BAD_REQUEST);
1562 #if ENABLE_FEATURE_HTTPD_CGI
1563 if (strcasecmp(buf, prequest) != 0) {
1565 if (strcasecmp(buf, prequest) != 0) {
1566 sendHeaders(HTTP_NOT_IMPLEMENTED);
1571 if (strcasecmp(buf, request_GET) != 0) {
1572 sendHeaders(HTTP_NOT_IMPLEMENTED);
1577 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1579 if (count < 1 || buf[0] != '/') {
1580 /* Garbled request/URL */
1583 url = alloca(strlen(buf) + sizeof("/index.html"));
1585 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1589 /* extract url args if present */
1590 test = strchr(url, '?');
1597 test = decodeString(url, 0);
1600 if (test == url+1) {
1601 /* '/' or NUL is encoded */
1602 sendHeaders(HTTP_NOT_FOUND);
1606 /* algorithm stolen from libbb bb_simplify_path(),
1607 * but don't strdup and reducing trailing slash and protect out root */
1611 /* skip duplicate (or initial) slash */
1616 /* skip extra '.' */
1617 if (test[1] == '/' || !test[1]) {
1620 /* '..': be careful */
1621 if (test[1] == '.' && (test[2] == '/' || !test[2])) {
1624 /* protect out root */
1627 while (*--purl != '/') /* omit previous dir */;
1634 *++purl = '\0'; /* so keep last character */
1635 test = purl; /* end ptr */
1637 /* If URL is directory, adding '/' */
1638 if (test[-1] != '/') {
1639 if (is_directory(url + 1, 1, &sb)) {
1640 found_moved_temporarily = url;
1644 fprintf(stderr, "url='%s', args=%s\n", url, g_query);
1647 ip_allowed = checkPermIP();
1648 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1649 /* have path1/path2 */
1651 if (is_directory(url + 1, 1, &sb)) {
1652 /* may be having subdir config */
1653 parse_conf(url + 1, SUBDIR_PARSE);
1654 ip_allowed = checkPermIP();
1659 /* read until blank line for HTTP version specified, else parse immediate */
1667 fprintf(stderr, "header: '%s'\n", buf);
1669 #if ENABLE_FEATURE_HTTPD_CGI
1670 /* try and do our best to parse more lines */
1671 if ((STRNCASECMP(buf, "Content-length:") == 0)) {
1672 /* extra read only for POST */
1673 if (prequest != request_GET) {
1674 test = buf + sizeof("Content-length:")-1;
1678 /* not using strtoul: it ignores leading munis! */
1679 length = strtol(test, &test, 10);
1680 /* length is "ulong", but we need to pass it to int later */
1681 /* so we check for negative or too large values in one go: */
1682 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1683 if (test[0] || errno || length > INT_MAX)
1686 } else if ((STRNCASECMP(buf, "Cookie:") == 0)) {
1687 cookie = strdup(skip_whitespace(buf + sizeof("Cookie:")-1));
1688 } else if ((STRNCASECMP(buf, "Content-Type:") == 0)) {
1689 content_type = strdup(skip_whitespace(buf + sizeof("Content-Type:")-1));
1690 } else if ((STRNCASECMP(buf, "Referer:") == 0)) {
1691 referer = strdup(skip_whitespace(buf + sizeof("Referer:")-1));
1695 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1696 if (STRNCASECMP(buf, "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(buf + 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 */
1711 } /* while extra header reading */
1717 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1718 /* protect listing [/path]/httpd_conf or IP deny */
1719 #if ENABLE_FEATURE_HTTPD_CGI
1720 FORBIDDEN: /* protect listing /cgi-bin */
1722 sendHeaders(HTTP_FORBIDDEN);
1726 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1727 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1728 sendHeaders(HTTP_UNAUTHORIZED);
1733 if (found_moved_temporarily) {
1734 sendHeaders(HTTP_MOVED_TEMPORARILY);
1735 /* clear unforked memory flag */
1736 found_moved_temporarily = NULL;
1740 test = url + 1; /* skip first '/' */
1742 #if ENABLE_FEATURE_HTTPD_CGI
1743 if (strncmp(test, "cgi-bin", 7) == 0) {
1744 if (test[7] == '/' && test[8] == 0)
1745 goto FORBIDDEN; /* protect listing cgi-bin/ */
1746 sendCgi(url, prequest, length, cookie, content_type);
1749 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1751 char *suffix = strrchr(test, '.');
1754 for (cur = script_i; cur; cur = cur->next) {
1755 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1756 sendCgi(url, prequest, length, cookie, content_type);
1763 if (prequest != request_GET) {
1764 sendHeaders(HTTP_NOT_IMPLEMENTED);
1767 #endif /* FEATURE_HTTPD_CGI */
1768 if (purl[-1] == '/')
1769 strcpy(purl, "index.html");
1770 if (stat(test, &sb) == 0) {
1771 /* It's a dir URL and there is index.html */
1772 ContentLength = sb.st_size;
1773 last_mod = sb.st_mtime;
1775 #if ENABLE_FEATURE_HTTPD_CGI
1776 else if (purl[-1] == '/') {
1777 /* It's a dir URL and there is no index.html
1778 * Try cgi-bin/index.cgi */
1779 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1782 sendCgi("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1786 #endif /* FEATURE_HTTPD_CGI */
1791 #if ENABLE_FEATURE_HTTPD_CGI
1796 fprintf(stderr, "closing socket\n\n");
1797 #if ENABLE_FEATURE_HTTPD_CGI
1802 # if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1807 shutdown(accepted_socket, SHUT_WR);
1809 /* Properly wait for remote to closed */
1811 FD_SET(accepted_socket, &s_fd);
1816 retval = select(accepted_socket + 1, &s_fd, NULL, NULL, &tv);
1817 } while (retval > 0 && read(accepted_socket, buf, sizeof(iobuf) > 0));
1819 shutdown(accepted_socket, SHUT_RD);
1820 /* In inetd case, we close fd 1 (stdout) here. We will exit soon anyway */
1821 close(accepted_socket);
1824 /****************************************************************************
1826 > $Function: miniHttpd()
1828 * $Description: The main http server function.
1830 * Given an open socket fildes, listen for new connections and farm out
1831 * the processing as a forked process.
1834 * (int) server. . . The server socket fildes.
1836 * $Return: (int) . . . . Always 0.
1838 ****************************************************************************/
1839 static int miniHttpd(int server)
1841 fd_set readfd, portfd;
1844 FD_SET(server, &portfd);
1846 /* copy the ports we are watching to the readfd set */
1851 struct sockaddr_in sin;
1852 USE_FEATURE_IPV6(struct sockaddr_in6 sin6;)
1854 socklen_t fromAddrLen = sizeof(fromAddr);
1856 /* Now wait INDEFINITELY on the set of sockets! */
1858 if (select(server + 1, &readfd, 0, 0, 0) <= 0)
1860 if (!FD_ISSET(server, &readfd))
1862 s = accept(server, &fromAddr.sa, &fromAddrLen);
1865 accepted_socket = s;
1868 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1870 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddrLen);
1872 bb_error_msg("connection from '%s'", rmt_ip_str);
1874 #endif /* FEATURE_HTTPD_CGI */
1875 if (fromAddr.sa.sa_family == AF_INET) {
1876 rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1877 tcp_port = ntohs(fromAddr.sin.sin_port);
1879 #if ENABLE_FEATURE_IPV6
1880 if (fromAddr.sa.sa_family == AF_INET6) {
1881 //rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1882 tcp_port = ntohs(fromAddr.sin6.sin6_port);
1886 /* set the KEEPALIVE option to cull dead connections */
1887 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1889 if (DEBUG || fork() == 0) {
1891 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1892 /* protect reload config, may be confuse checking */
1893 signal(SIGHUP, SIG_IGN);
1905 static int miniHttpd_inetd(void)
1909 struct sockaddr_in sin;
1910 USE_FEATURE_IPV6(struct sockaddr_in6 sin6;)
1912 socklen_t fromAddrLen = sizeof(fromAddr);
1914 getpeername(0, &fromAddr.sa, &fromAddrLen);
1917 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1919 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddrLen);
1921 if (fromAddr.sa.sa_family == AF_INET) {
1922 rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1923 tcp_port = ntohs(fromAddr.sin.sin_port);
1925 #if ENABLE_FEATURE_IPV6
1926 if (fromAddr.sa.sa_family == AF_INET6) {
1927 //rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1928 tcp_port = ntohs(fromAddr.sin6.sin6_port);
1935 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1936 static void sighup_handler(int sig)
1939 struct sigaction sa;
1941 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1942 sa.sa_handler = sighup_handler;
1943 sigemptyset(&sa.sa_mask);
1944 sa.sa_flags = SA_RESTART;
1945 sigaction(SIGHUP, &sa, NULL);
1950 c_opt_config_file = 0,
1953 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1954 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1955 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1956 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1960 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1961 OPT_DECODE_URL = 1 << d_opt_decode_url,
1962 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1963 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1964 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1965 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1966 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1967 OPT_PORT = 1 << p_opt_port,
1968 OPT_INETD = 1 << p_opt_inetd,
1969 OPT_FOREGROUND = 1 << p_opt_foreground,
1973 int httpd_main(int argc, char **argv);
1974 int httpd_main(int argc, char **argv)
1977 char *url_for_decode;
1978 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1980 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1981 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1982 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1984 #if ENABLE_LOCALE_SUPPORT
1985 /* Undo busybox.c: we want to speak English in http (dates etc) */
1986 setlocale(LC_TIME, "C");
1990 home_httpd = xrealloc_getcwd_or_warn(NULL);
1991 /* We do not "absolutize" path given by -h (home) opt.
1992 * If user gives relative path in -h, $SCRIPT_FILENAME can end up
1994 opt = getopt32(argc, argv, "c:d:h:"
1995 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1996 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1997 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1998 USE_FEATURE_HTTPD_SETUID("u:")
2000 &(configFile), &url_for_decode, &home_httpd
2001 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
2002 USE_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
2003 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
2004 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
2007 if (opt & OPT_DECODE_URL) {
2008 printf("%s", decodeString(url_for_decode, 1));
2011 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
2012 if (opt & OPT_ENCODE_URL) {
2013 printf("%s", encodeString(url_for_encode));
2017 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
2018 if (opt & OPT_MD5) {
2019 puts(pw_encrypt(pass, "$1$"));
2024 tcp_port = xatou16(s_port);
2026 #if ENABLE_FEATURE_HTTPD_SETUID
2027 if (opt & OPT_SETUID) {
2028 if (!get_uidgid(&ugid, s_ugid, 1))
2029 bb_error_msg_and_die("unrecognized user[:group] "
2030 "name '%s'", s_ugid);
2035 if (!(opt & OPT_INETD)) {
2036 signal(SIGCHLD, SIG_IGN);
2037 server_socket = openServer();
2038 #if ENABLE_FEATURE_HTTPD_SETUID
2039 /* drop privileges */
2040 if (opt & OPT_SETUID) {
2041 if (ugid.gid != (gid_t)-1) {
2042 if (setgroups(1, &ugid.gid) == -1)
2043 bb_perror_msg_and_die("setgroups");
2051 #if ENABLE_FEATURE_HTTPD_CGI
2053 char *p = getenv("PATH");
2054 /* env strings themself are not freed, no need to strdup(p): */
2058 if (!(opt & OPT_INETD))
2059 setenv_long("SERVER_PORT", tcp_port);
2063 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2066 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2069 if (opt & OPT_INETD)
2070 return miniHttpd_inetd();
2072 if (!(opt & OPT_FOREGROUND))
2073 bb_daemonize(0); /* don't change current directory */
2074 return miniHttpd(server_socket);