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 httpdVersion[] = "busybox httpd/1.35 6-Oct-2004";
102 static const char default_path_httpd_conf[] = "/etc";
103 static const char httpd_conf[] = "httpd.conf";
104 static const char home[] = "./";
108 // Note: busybox xfuncs are not used because we want the server to keep running
109 // if something bad happens due to a malformed user request.
110 // As a result, all memory allocation after daemonize
111 // is checked rigorously
116 #define MAX_MEMORY_BUFF 8192 /* IO buffer */
118 typedef struct HT_ACCESS {
120 struct HT_ACCESS *next;
121 char before_colon[1]; /* really bigger, must last */
124 typedef struct HT_ACCESS_IP {
128 struct HT_ACCESS_IP *next;
132 char buf[MAX_MEMORY_BUFF];
134 USE_FEATURE_HTTPD_BASIC_AUTH(const char *realm;)
135 USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
139 USE_FEATURE_HTTPD_CGI(char *referer;)
141 const char *configFile;
144 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
145 char *rmt_ip_str; /* for set env REMOTE_ADDR */
147 unsigned port; /* server initial port and for
148 set env REMOTE_PORT */
149 const char *found_mime_type;
150 const char *found_moved_temporarily;
152 off_t ContentLength; /* -1 - unknown */
155 Htaccess_IP *ip_a_d; /* config allow/deny lines */
157 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
158 Htaccess *auth; /* config user:password lines */
160 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
161 Htaccess *mime_a; /* config mime types */
166 volatile int alarm_signaled;
168 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
169 Htaccess *script_i; /* config script interpreters */
173 static HttpdConfig *config;
175 static const char request_GET[] = "GET"; /* size algorithmic optimize */
177 static const char* const suffixTable [] = {
178 /* Warning: shorted equivalent suffix in one line must be first */
179 ".htm.html", "text/html",
180 ".jpg.jpeg", "image/jpeg",
183 ".txt.h.c.cc.cpp", "text/plain",
186 ".avi", "video/x-msvideo",
187 ".qt.mov", "video/quicktime",
188 ".mpe.mpeg", "video/mpeg",
189 ".mid.midi", "audio/midi",
190 ".mp3", "audio/mpeg",
191 #if 0 /* unpopular */
192 ".au", "audio/basic",
193 ".pac", "application/x-ns-proxy-autoconfig",
194 ".vrml.wrl", "model/vrml",
196 0, "application/octet-stream" /* default */
201 HTTP_MOVED_TEMPORARILY = 302,
202 HTTP_BAD_REQUEST = 400, /* malformed syntax */
203 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
204 HTTP_NOT_FOUND = 404,
205 HTTP_FORBIDDEN = 403,
206 HTTP_REQUEST_TIMEOUT = 408,
207 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
208 HTTP_INTERNAL_SERVER_ERROR = 500,
209 #if 0 /* future use */
211 HTTP_SWITCHING_PROTOCOLS = 101,
214 HTTP_NON_AUTHORITATIVE_INFO = 203,
215 HTTP_NO_CONTENT = 204,
216 HTTP_MULTIPLE_CHOICES = 300,
217 HTTP_MOVED_PERMANENTLY = 301,
218 HTTP_NOT_MODIFIED = 304,
219 HTTP_PAYMENT_REQUIRED = 402,
220 HTTP_BAD_GATEWAY = 502,
221 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
222 HTTP_RESPONSE_SETSIZE = 0xffffffff
227 HttpResponseNum type;
232 static const HttpEnumString httpResponseNames[] = {
233 { HTTP_OK, "OK", NULL },
234 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
235 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
236 "No request appeared within a reasonable time period." },
237 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
238 "The requested method is not recognized by this server." },
239 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
240 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
242 { HTTP_NOT_FOUND, "Not Found",
243 "The requested URL was not found on this server." },
244 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
245 { HTTP_FORBIDDEN, "Forbidden", "" },
246 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
247 "Internal Server Error" },
248 #if 0 /* not implemented */
249 { HTTP_CREATED, "Created" },
250 { HTTP_ACCEPTED, "Accepted" },
251 { HTTP_NO_CONTENT, "No Content" },
252 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
253 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
254 { HTTP_NOT_MODIFIED, "Not Modified" },
255 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
256 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
261 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
264 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
267 static int scan_ip(const char **ep, unsigned int *ip, unsigned char endc)
274 for (j = 0; j < 4; j++) {
277 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
280 while (*p >= '0' && *p <= '9') {
289 if (*p != '/' && *p != 0)
291 *ip = ((*ip) << 8) | octet;
304 static int scan_ip_mask(const char *ipm, unsigned int *ip, unsigned int *mask)
309 i = scan_ip(&ipm, ip, '/');
317 if (*p < '0' || *p > '9') {
319 i = scan_ip(&ipm, mask, 0);
341 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
342 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
343 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
344 static void free_config_lines(Htaccess **pprev)
346 Htaccess *prev = *pprev;
349 Htaccess *cur = prev;
359 #define FIRST_PARSE 0
360 #define SUBDIR_PARSE 1
361 #define SIGNALED_PARSE 2
362 #define FIND_FROM_HTTPD_ROOT 3
363 /****************************************************************************
365 > $Function: parse_conf()
367 * $Description: parse configuration file into in-memory linked list.
369 * The first non-white character is examined to determine if the config line
370 * is one of the following:
371 * .ext:mime/type # new mime type not compiled into httpd
372 * [adAD]:from # ip address allow/deny, * for wildcard
373 * /path:user:pass # username/password
375 * Any previous IP rules are discarded.
376 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
377 * are also discarded. That is, previous settings are retained if flag is
381 * (const char *) path . . null for ip address checks, path for password
383 * (int) flag . . . . . . the source of the parse request.
387 ****************************************************************************/
388 static void parse_conf(const char *path, int flag)
391 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
394 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
395 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
396 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
400 const char *cf = config->configFile;
405 /* free previous ip setup if present */
406 Htaccess_IP *pip = config->ip_a_d;
409 Htaccess_IP *cur_ipl = pip;
414 config->ip_a_d = NULL;
416 config->flg_deny_all = 0;
418 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
419 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
420 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
421 /* retain previous auth and mime config only for subdir parse */
422 if (flag != SUBDIR_PARSE) {
423 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
424 free_config_lines(&config->auth);
426 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
427 free_config_lines(&config->mime_a);
429 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
430 free_config_lines(&config->script_i);
435 if (flag == SUBDIR_PARSE || cf == NULL) {
436 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
438 if (flag == FIRST_PARSE)
439 bb_error_msg_and_die(bb_msg_memory_exhausted);
442 sprintf((char *)cf, "%s/%s", path, httpd_conf);
445 while ((f = fopen(cf, "r")) == NULL) {
446 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
447 /* config file not found, no changes to config */
450 if (config->configFile && flag == FIRST_PARSE) /* if -c option given */
451 bb_perror_msg_and_die("%s", cf);
452 flag = FIND_FROM_HTTPD_ROOT;
456 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
459 /* This could stand some work */
460 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
462 for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
465 if (*p0 == ':' && c == NULL)
471 /* test for empty or strange line */
472 if (c == NULL || *c == 0)
479 /* memorize deny all */
480 config->flg_deny_all++;
482 /* skip default other "word:*" config lines */
488 else if (*p0 != 'D' && *p0 != 'A'
489 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
492 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
495 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
500 if (*p0 == 'A' || *p0 == 'D') {
501 /* storing current config IP line */
502 pip = xzalloc(sizeof(Htaccess_IP));
504 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
505 /* syntax IP{/mask} error detected, protect all */
509 pip->allow_deny = *p0;
511 /* Deny:form_IP move top */
512 pip->next = config->ip_a_d;
513 config->ip_a_d = pip;
515 /* add to bottom A:form_IP config line */
516 Htaccess_IP *prev_IP = config->ip_a_d;
518 if (prev_IP == NULL) {
519 config->ip_a_d = pip;
521 while (prev_IP->next)
522 prev_IP = prev_IP->next;
529 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
531 /* make full path from httpd root / curent_path / config_line_path */
532 cf = flag == SUBDIR_PARSE ? path : "";
533 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
537 sprintf(p0, "/%s%s", cf, buf);
539 /* another call bb_simplify_path */
544 if (*cf == '/') { /* skip duplicate (or initial) slash */
546 } else if (*cf == '.') {
547 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
549 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
552 while (*--p != '/') /* omit previous dir */;
561 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
562 ++p; /* so keep last character */
565 sprintf(p0, "%s:%s", p0, c);
569 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
570 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
571 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
572 /* storing current config line */
573 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
575 cf = strcpy(cur->before_colon, p0);
578 cur->after_colon = c;
579 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
581 /* config .mime line move top for overwrite previous */
582 cur->next = config->mime_a;
583 config->mime_a = cur;
587 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
588 if (*cf == '*' && cf[1] == '.') {
589 /* config script interpreter line move top for overwrite previous */
590 cur->next = config->script_i;
591 config->script_i = cur;
595 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
599 config->auth = prev = cur;
601 /* sort path, if current lenght eq or bigger then move up */
602 Htaccess *prev_hti = config->auth;
603 size_t l = strlen(cf);
606 for (hti = prev_hti; hti; hti = hti->next) {
607 if (l >= strlen(hti->before_colon)) {
608 /* insert before hti */
610 if (prev_hti != hti) {
611 prev_hti->next = cur;
619 prev_hti = prev_hti->next;
621 if (!hti) { /* not inserted, add to bottom */
633 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
634 /****************************************************************************
636 > $Function: encodeString()
638 * $Description: Given a string, html encode special characters.
639 * This is used for the -e command line option to provide an easy way
640 * for scripts to encode result data without confusing browsers. The
641 * returned string pointer is memory allocated by malloc().
644 * (const char *) string . . The first string to encode.
646 * $Return: (char *) . . . .. . . A pointer to the encoded string.
648 * $Errors: Returns a null string ("") if memory is not available.
650 ****************************************************************************/
651 static char *encodeString(const char *string)
653 /* take the simple route and encode everything */
654 /* could possibly scan once to get length. */
655 int len = strlen(string);
656 char *out = xmalloc(len * 6 + 1);
660 while ((ch = *string++)) {
661 // very simple check for what to encode
662 if (isalnum(ch)) *p++ = ch;
663 else p += sprintf(p, "&#%d;", (unsigned char) ch);
668 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
670 /****************************************************************************
672 > $Function: decodeString()
674 * $Description: Given a URL encoded string, convert it to plain ascii.
675 * Since decoding always makes strings smaller, the decode is done in-place.
676 * Thus, callers should strdup() the argument if they do not want the
677 * argument modified. The return is the original pointer, allowing this
678 * function to be easily used as arguments to other functions.
681 * (char *) string . . . The first string to decode.
682 * (int) option_d . . 1 if called for httpd -d
684 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
688 ****************************************************************************/
689 static char *decodeString(char *orig, int option_d)
691 /* note that decoded string is always shorter than original */
696 while ((c = *ptr++) != '\0') {
697 unsigned value1, value2;
699 if (option_d && c == '+') {
707 if (sscanf(ptr, "%1X", &value1) != 1
708 || sscanf(ptr+1, "%1X", &value2) != 1
715 value1 = value1 * 16 + value2;
716 if (!option_d && (value1 == '/' || value1 == '\0')) {
717 /* caller takes it as indication of invalid
718 * (dangerous wrt exploits) chars */
729 #if ENABLE_FEATURE_HTTPD_CGI
730 /****************************************************************************
732 ****************************************************************************/
733 static void setenv1(const char *name, const char *value)
737 setenv(name, value, 1);
739 static void setenv_long(const char *name, long value)
741 char buf[sizeof(value)*3 + 1];
742 sprintf(buf, "%ld", value);
743 setenv(name, buf, 1);
747 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
748 /****************************************************************************
750 > $Function: decodeBase64()
752 > $Description: Decode a base 64 data stream as per rfc1521.
753 * Note that the rfc states that none base64 chars are to be ignored.
754 * Since the decode always results in a shorter size than the input, it is
755 * OK to pass the input arg as an output arg.
758 * (char *) Data . . . . A pointer to a base64 encoded string.
759 * Where to place the decoded data.
765 ****************************************************************************/
766 static void decodeBase64(char *Data)
769 const unsigned char *in = (const unsigned char *)Data;
770 // The decoded size will be at most 3/4 the size of the encoded
771 unsigned long ch = 0;
777 if (t >= '0' && t <= '9')
779 else if (t >= 'A' && t <= 'Z')
781 else if (t >= 'a' && t <= 'z')
795 *Data++ = (char) (ch >> 16);
796 *Data++ = (char) (ch >> 8);
806 /****************************************************************************
808 > $Function: openServer()
810 * $Description: create a listen server socket on the designated port.
812 * $Return: (int) . . . A connection socket. -1 for errors.
816 ****************************************************************************/
817 static int openServer(void)
821 /* create the socket right now */
822 fd = create_and_bind_stream_or_die(NULL, config->port);
827 /****************************************************************************
829 > $Function: sendHeaders()
831 * $Description: Create and send HTTP response headers.
832 * The arguments are combined and sent as one write operation. Note that
833 * IE will puke big-time if the headers are not sent in one packet and the
834 * second packet is delayed for any reason.
837 * (HttpResponseNum) responseNum . . . The result code to send.
839 * $Return: (int) . . . . writing errors
841 ****************************************************************************/
842 static int sendHeaders(HttpResponseNum responseNum)
844 char *buf = config->buf;
845 const char *responseString = "";
846 const char *infoString = 0;
847 const char *mime_type;
849 time_t timer = time(0);
853 numNames = sizeof(httpResponseNames) / sizeof(httpResponseNames[0])
856 for (i = 0; i < numNames; i++) {
857 if (httpResponseNames[i].type == responseNum) {
858 responseString = httpResponseNames[i].name;
859 infoString = httpResponseNames[i].info;
863 /* error message is HTML */
864 mime_type = responseNum == HTTP_OK ?
865 config->found_mime_type : "text/html";
867 /* emit the current date */
868 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
870 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
871 "Date: %s\r\nConnection: close\r\n",
872 responseNum, responseString, mime_type, timeStr);
874 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
875 if (responseNum == HTTP_UNAUTHORIZED) {
876 len += sprintf(buf+len,
877 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
881 if (responseNum == HTTP_MOVED_TEMPORARILY) {
882 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
883 config->found_moved_temporarily,
884 (config->query ? "?" : ""),
885 (config->query ? config->query : ""));
888 if (config->ContentLength != -1) { /* file */
889 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
890 len += sprintf(buf+len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
891 timeStr, "Content-length:", config->ContentLength);
896 len += sprintf(buf+len,
897 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
898 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
899 responseNum, responseString,
900 responseNum, responseString, infoString);
903 fprintf(stderr, "headers: '%s'\n", buf);
904 i = config->accepted_socket;
905 if (i == 0) i++; /* write to fd# 1 in inetd mode */
906 return full_write(i, buf, len);
909 /****************************************************************************
911 > $Function: getLine()
913 * $Description: Read from the socket until an end of line char found.
915 * Characters are read one at a time until an eol sequence is found.
917 * $Return: (int) . . . . number of characters read. -1 if error.
919 ****************************************************************************/
920 static int getLine(void)
923 char *buf = config->buf;
925 while (read(config->accepted_socket, buf + count, 1) == 1) {
926 if (buf[count] == '\r') continue;
927 if (buf[count] == '\n') {
931 if (count < (MAX_MEMORY_BUFF-1)) /* check overflow */
934 if (count) return count;
938 #if ENABLE_FEATURE_HTTPD_CGI
939 /****************************************************************************
941 > $Function: sendCgi()
943 * $Description: Execute a CGI script and send it's stdout back
945 * Environment variables are set up and the script is invoked with pipes
946 * for stdin/stdout. If a post is being done the script is fed the POST
947 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
950 * (const char *) url . . . . . . The requested URL (with leading /).
951 * (int bodyLen) . . . . . . . . Length of the post body.
952 * (const char *cookie) . . . . . For set HTTP_COOKIE.
953 * (const char *content_type) . . For set CONTENT_TYPE.
955 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
959 ****************************************************************************/
960 static int sendCgi(const char *url,
961 const char *request, int bodyLen, const char *cookie,
962 const char *content_type)
964 int fromCgi[2]; /* pipe for reading data from CGI */
965 int toCgi[2]; /* pipe for sending data to CGI */
967 static char * argp[] = { 0, 0 };
973 size_t post_read_size, post_read_idx;
975 if (pipe(fromCgi) != 0)
977 if (pipe(toCgi) != 0)
981 * Note: We can use vfork() here in the no-mmu case, although
982 * the child modifies the parent's variables, due to:
983 * 1) The parent does not use the child-modified variables.
984 * 2) The allocated memory (in the child) is freed when the process
985 * exits. This happens instantly after the child finishes,
986 * since httpd is run from inetd (and it can't run standalone
1001 char realpath_buff[MAXPATHLEN];
1003 if (config->accepted_socket > 1)
1004 close(config->accepted_socket);
1005 if (config->server_socket > 1)
1006 close(config->server_socket);
1008 dup2(toCgi[0], 0); // replace stdin with the pipe
1009 dup2(fromCgi[1], 1); // replace stdout with the pipe
1010 /* Huh? User seeing stderr can be a security problem...
1011 * and if CGI really wants that, it can always dup2(1,2)...
1013 dup2(fromCgi[1], 2); // replace stderr with the pipe
1015 /* I think we cannot inadvertently close 0, 1 here... */
1024 xfunc_error_retval = 242;
1025 purl = xstrdup(url);
1027 while ((script = strchr(script + 1, '/')) != NULL) {
1028 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1032 if (is_directory(purl + 1, 1, &sb) == 0) {
1033 /* not directory, found script.cgi/PATH_INFO */
1037 *script = '/'; /* is directory, find next '/' */
1039 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1040 /* setenv1("PATH", getenv("PATH")); redundant */
1041 setenv1("REQUEST_METHOD", request);
1042 if (config->query) {
1043 char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
1045 sprintf(uri, "%s?%s", purl, config->query);
1046 setenv1("REQUEST_URI", uri);
1048 setenv1("REQUEST_URI", purl);
1051 *script = '\0'; /* cut off /PATH_INFO */
1052 /* SCRIPT_FILENAME required by PHP in CGI mode */
1053 if (!realpath(purl + 1, realpath_buff))
1054 goto error_execing_cgi;
1055 setenv1("SCRIPT_FILENAME", realpath_buff);
1056 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1057 setenv1("SCRIPT_NAME", purl);
1058 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1059 * QUERY_STRING: The information which follows the ? in the URL
1060 * which referenced this script. This is the query information.
1061 * It should not be decoded in any fashion. This variable
1062 * should always be set when there is query information,
1063 * regardless of command line decoding. */
1064 /* (Older versions of bbox seem to do some decoding) */
1065 setenv1("QUERY_STRING", config->query);
1066 setenv1("SERVER_SOFTWARE", httpdVersion);
1067 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1068 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1069 /* Having _separate_ variables for IP and port defeats
1070 * the purpose of having socket abstraction. Which "port"
1071 * are you using on Unix domain socket?
1072 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1075 char *p = config->rmt_ip_str ? : (char*)"";
1076 char *cp = strrchr(p, ':');
1077 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1079 if (cp) *cp = '\0'; /* delete :PORT */
1080 setenv1("REMOTE_ADDR", p);
1082 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1083 setenv_long("REMOTE_PORT", config->port);
1086 setenv_long("CONTENT_LENGTH", bodyLen);
1088 setenv1("HTTP_COOKIE", cookie);
1090 setenv1("CONTENT_TYPE", content_type);
1091 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1092 if (config->remoteuser) {
1093 setenv1("REMOTE_USER", config->remoteuser);
1094 putenv((char*)"AUTH_TYPE=Basic");
1097 if (config->referer)
1098 setenv1("HTTP_REFERER", config->referer);
1100 /* set execve argp[0] without path */
1101 argp[0] = strrchr(purl, '/') + 1;
1102 /* but script argp[0] must have absolute path and chdiring to this */
1103 script = strrchr(realpath_buff, '/');
1105 goto error_execing_cgi;
1107 if (chdir(realpath_buff) == 0) {
1108 // Now run the program. If it fails,
1109 // use _exit() so no destructors
1110 // get called and make a mess.
1111 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1112 char *interpr = NULL;
1113 char *suffix = strrchr(purl, '.');
1117 for (cur = config->script_i; cur; cur = cur->next) {
1118 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1119 interpr = cur->after_colon;
1126 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1128 execv(interpr, argp);
1131 execv(realpath_buff, argp);
1134 /* send to stdout (even if we are not from inetd) */
1135 config->accepted_socket = 1;
1136 sendHeaders(HTTP_NOT_FOUND);
1140 /* parent process */
1144 post_read_idx = 0; /* for gcc */
1149 signal(SIGPIPE, SIG_IGN);
1160 FD_SET(inFd, &readSet);
1161 if (bodyLen > 0 || post_read_size > 0) {
1162 FD_SET(outFd, &writeSet);
1163 nfound = outFd > inFd ? outFd : inFd;
1164 if (post_read_size == 0) {
1165 FD_SET(config->accepted_socket, &readSet);
1166 if (nfound < config->accepted_socket)
1167 nfound = config->accepted_socket;
1169 /* Now wait on the set of sockets! */
1170 nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1173 close(outFd); /* no more POST data to CGI */
1176 nfound = select(inFd + 1, &readSet, NULL, NULL, NULL);
1180 if (waitpid(pid, &status, WNOHANG) <= 0) {
1181 /* Weird. CGI didn't exit and no fd's
1182 * are ready, yet select returned?! */
1186 if (DEBUG && WIFEXITED(status))
1187 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1188 if (DEBUG && WIFSIGNALED(status))
1189 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1193 if (post_read_size > 0 && FD_ISSET(outFd, &writeSet)) {
1194 /* Have data from peer and can write to CGI */
1195 // huh? why full_write? what if we will block?
1196 // (imagine that CGI does not read its stdin...)
1197 count = full_write(outFd, wbuf + post_read_idx, post_read_size);
1199 post_read_idx += count;
1200 post_read_size -= count;
1202 post_read_size = bodyLen = 0; /* broken pipe to CGI */
1204 } else if (bodyLen > 0 && post_read_size == 0
1205 && FD_ISSET(config->accepted_socket, &readSet)
1207 /* We expect data, prev data portion is eaten by CGI
1208 * and there *is* data to read from the peer
1210 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1211 count = safe_read(config->accepted_socket, wbuf, count);
1213 post_read_size = count;
1217 bodyLen = 0; /* closed */
1221 #define PIPESIZE PIPE_BUF
1222 #if PIPESIZE >= MAX_MEMORY_BUFF
1223 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1225 if (FD_ISSET(inFd, &readSet)) {
1226 /* There is something to read from CGI */
1227 int s = config->accepted_socket;
1228 char *rbuf = config->buf;
1230 /* Are we still buffering CGI output? */
1231 if (buf_count >= 0) {
1232 static const char HTTP_200[] = "HTTP/1.0 200 OK\r\n";
1233 /* Must use safe_read, not full_read, because
1234 * CGI may output a few first bytes and then wait
1235 * for POSTDATA without closing stdout.
1236 * With full_read we may wait here forever. */
1237 count = safe_read(inFd, rbuf + buf_count, PIPESIZE - 4);
1239 /* eof (or error) and there was no "HTTP",
1240 * so add one and write out the received data */
1242 full_write(s, HTTP_200, sizeof(HTTP_200)-1);
1243 full_write(s, rbuf, buf_count);
1249 if (buf_count >= 4) {
1250 /* check to see if CGI added "HTTP" */
1251 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1252 /* there is no "HTTP", do it ourself */
1253 if (full_write(s, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1256 /* example of valid CGI without "Content-type:"
1257 * echo -en "HTTP/1.0 302 Found\r\n"
1258 * echo -en "Location: http://www.busybox.net\r\n"
1260 if (!strstr(rbuf, "ontent-")) {
1261 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1265 buf_count = -1; /* buffering off */
1268 count = safe_read(inFd, rbuf, PIPESIZE);
1270 break; /* eof (or error) */
1272 if (full_write(s, rbuf, count) != count)
1275 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1276 } /* if (FD_ISSET(inFd)) */
1280 #endif /* FEATURE_HTTPD_CGI */
1282 /****************************************************************************
1284 > $Function: sendFile()
1286 * $Description: Send a file response to a HTTP request
1289 * (const char *) url . . The URL requested.
1291 * $Return: (int) . . . . . . Always 0.
1293 ****************************************************************************/
1294 static int sendFile(const char *url)
1298 const char * const * table;
1299 const char * try_suffix;
1301 suffix = strrchr(url, '.');
1303 for (table = suffixTable; *table; table += 2)
1304 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1305 try_suffix += strlen(suffix);
1306 if (*try_suffix == 0 || *try_suffix == '.')
1309 /* also, if not found, set default as "application/octet-stream"; */
1310 config->found_mime_type = table[1];
1311 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1315 for (cur = config->mime_a; cur; cur = cur->next) {
1316 if (strcmp(cur->before_colon, suffix) == 0) {
1317 config->found_mime_type = cur->after_colon;
1322 #endif /* FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1325 fprintf(stderr, "sending file '%s' content-type: %s\n",
1326 url, config->found_mime_type);
1328 f = open(url, O_RDONLY);
1331 char *buf = config->buf;
1333 sendHeaders(HTTP_OK);
1334 /* TODO: sendfile() */
1335 while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1336 int fd = config->accepted_socket;
1337 if (fd == 0) fd++; /* write to fd# 1 in inetd mode */
1338 if (full_write(fd, buf, count) != count)
1344 bb_perror_msg("cannot open '%s'", url);
1345 sendHeaders(HTTP_NOT_FOUND);
1351 static int checkPermIP(void)
1355 /* This could stand some work */
1356 for (cur = config->ip_a_d; cur; cur = cur->next) {
1357 #if ENABLE_FEATURE_HTTPD_CGI && DEBUG
1358 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1361 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1362 (unsigned char)(cur->ip >> 24),
1363 (unsigned char)(cur->ip >> 16),
1364 (unsigned char)(cur->ip >> 8),
1365 (unsigned char)(cur->ip),
1366 (unsigned char)(cur->mask >> 24),
1367 (unsigned char)(cur->mask >> 16),
1368 (unsigned char)(cur->mask >> 8),
1369 (unsigned char)(cur->mask)
1372 if ((config->rmt_ip & cur->mask) == cur->ip)
1373 return cur->allow_deny == 'A'; /* Allow/Deny */
1376 /* if unconfigured, return 1 - access from all */
1377 return !config->flg_deny_all;
1380 /****************************************************************************
1382 > $Function: checkPerm()
1384 * $Description: Check the permission file for access password protected.
1386 * If config file isn't present, everything is allowed.
1387 * Entries are of the form you can see example from header source
1390 * (const char *) path . . . . The file path.
1391 * (const char *) request . . . User information to validate.
1393 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1395 ****************************************************************************/
1397 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1398 static int checkPerm(const char *path, const char *request)
1404 const char *prev = NULL;
1406 /* This could stand some work */
1407 for (cur = config->auth; cur; cur = cur->next) {
1410 p0 = cur->before_colon;
1411 if (prev != NULL && strcmp(prev, p0) != 0)
1412 continue; /* find next identical */
1413 p = cur->after_colon;
1415 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1418 if (strncmp(p0, path, l) == 0
1419 && (l == 1 || path[l] == '/' || path[l] == '\0')
1422 /* path match found. Check request */
1423 /* for check next /path:user:password */
1425 u = strchr(request, ':');
1427 /* bad request, ':' required */
1431 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1435 if (strncmp(p, request, u-request) != 0) {
1436 /* user uncompared */
1439 pp = strchr(p, ':');
1440 if (pp && pp[1] == '$' && pp[2] == '1' &&
1441 pp[3] == '$' && pp[4]) {
1443 cipher = pw_encrypt(u+1, pp);
1444 if (strcmp(cipher, pp) == 0)
1445 goto set_remoteuser_var; /* Ok */
1451 if (strcmp(p, request) == 0) {
1453 config->remoteuser = strdup(request);
1454 if (config->remoteuser)
1455 config->remoteuser[(u - request)] = 0;
1462 return prev == NULL;
1465 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1467 /****************************************************************************
1469 > $Function: handle_sigalrm()
1471 * $Description: Handle timeouts
1473 ****************************************************************************/
1475 static void handle_sigalrm(int sig)
1477 sendHeaders(HTTP_REQUEST_TIMEOUT);
1478 config->alarm_signaled = sig;
1481 /****************************************************************************
1483 > $Function: handleIncoming()
1485 * $Description: Handle an incoming http request.
1487 ****************************************************************************/
1488 static void handleIncoming(void)
1490 char *buf = config->buf;
1497 #if ENABLE_FEATURE_HTTPD_CGI
1498 const char *prequest = request_GET;
1499 unsigned long length = 0;
1501 char *content_type = 0;
1506 struct sigaction sa;
1508 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1509 int credentials = -1; /* if not required this is Ok */
1512 sa.sa_handler = handle_sigalrm;
1513 sigemptyset(&sa.sa_mask);
1514 sa.sa_flags = 0; /* no SA_RESTART */
1515 sigaction(SIGALRM, &sa, NULL);
1520 (void) alarm(TIMEOUT);
1524 purl = strpbrk(buf, " \t");
1527 sendHeaders(HTTP_BAD_REQUEST);
1531 #if ENABLE_FEATURE_HTTPD_CGI
1532 if (strcasecmp(buf, prequest) != 0) {
1534 if (strcasecmp(buf, prequest) != 0) {
1535 sendHeaders(HTTP_NOT_IMPLEMENTED);
1540 if (strcasecmp(buf, request_GET) != 0) {
1541 sendHeaders(HTTP_NOT_IMPLEMENTED);
1546 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1548 if (count < 1 || buf[0] != '/') {
1549 /* Garbled request/URL */
1552 url = alloca(strlen(buf) + sizeof("/index.html"));
1554 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1558 /* extract url args if present */
1559 test = strchr(url, '?');
1560 config->query = NULL;
1563 config->query = test;
1566 test = decodeString(url, 0);
1569 if (test == url+1) {
1570 /* '/' or NUL is encoded */
1571 sendHeaders(HTTP_NOT_FOUND);
1575 /* algorithm stolen from libbb bb_simplify_path(),
1576 but don't strdup and reducing trailing slash and protect out root */
1580 /* skip duplicate (or initial) slash */
1585 /* skip extra '.' */
1586 if (test[1] == '/' || test[1] == 0) {
1589 /* '..': be careful */
1590 if (test[1] == '.' && (test[2] == '/' || test[2] == 0)) {
1593 /* protect out root */
1596 while (*--purl != '/') /* omit previous dir */;
1603 *++purl = '\0'; /* so keep last character */
1604 test = purl; /* end ptr */
1606 /* If URL is directory, adding '/' */
1607 if (test[-1] != '/') {
1608 if (is_directory(url + 1, 1, &sb)) {
1609 config->found_moved_temporarily = url;
1613 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1616 ip_allowed = checkPermIP();
1617 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1618 /* have path1/path2 */
1620 if (is_directory(url + 1, 1, &sb)) {
1621 /* may be having subdir config */
1622 parse_conf(url + 1, SUBDIR_PARSE);
1623 ip_allowed = checkPermIP();
1628 /* read until blank line for HTTP version specified, else parse immediate */
1636 fprintf(stderr, "header: '%s'\n", buf);
1638 #if ENABLE_FEATURE_HTTPD_CGI
1639 /* try and do our best to parse more lines */
1640 if ((STRNCASECMP(buf, "Content-length:") == 0)) {
1641 /* extra read only for POST */
1642 if (prequest != request_GET) {
1643 test = buf + sizeof("Content-length:")-1;
1647 /* not using strtoul: it ignores leading munis! */
1648 length = strtol(test, &test, 10);
1649 /* length is "ulong", but we need to pass it to int later */
1650 /* so we check for negative or too large values in one go: */
1651 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1652 if (test[0] || errno || length > INT_MAX)
1655 } else if ((STRNCASECMP(buf, "Cookie:") == 0)) {
1656 cookie = strdup(skip_whitespace(buf + sizeof("Cookie:")-1));
1657 } else if ((STRNCASECMP(buf, "Content-Type:") == 0)) {
1658 content_type = strdup(skip_whitespace(buf + sizeof("Content-Type:")-1));
1659 } else if ((STRNCASECMP(buf, "Referer:") == 0)) {
1660 config->referer = strdup(skip_whitespace(buf + sizeof("Referer:")-1));
1664 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1665 if (STRNCASECMP(buf, "Authorization:") == 0) {
1666 /* We only allow Basic credentials.
1667 * It shows up as "Authorization: Basic <userid:password>" where
1668 * the userid:password is base64 encoded.
1670 test = skip_whitespace(buf + sizeof("Authorization:")-1);
1671 if (STRNCASECMP(test, "Basic") != 0)
1673 test += sizeof("Basic")-1;
1674 /* decodeBase64() skips whitespace itself */
1676 credentials = checkPerm(url, test);
1678 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1680 } /* while extra header reading */
1683 if (config->alarm_signaled)
1686 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1687 /* protect listing [/path]/httpd_conf or IP deny */
1688 #if ENABLE_FEATURE_HTTPD_CGI
1689 FORBIDDEN: /* protect listing /cgi-bin */
1691 sendHeaders(HTTP_FORBIDDEN);
1695 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1696 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1697 sendHeaders(HTTP_UNAUTHORIZED);
1702 if (config->found_moved_temporarily) {
1703 sendHeaders(HTTP_MOVED_TEMPORARILY);
1704 /* clear unforked memory flag */
1705 config->found_moved_temporarily = NULL;
1709 test = url + 1; /* skip first '/' */
1711 #if ENABLE_FEATURE_HTTPD_CGI
1712 if (strncmp(test, "cgi-bin", 7) == 0) {
1713 if (test[7] == '/' && test[8] == 0)
1714 goto FORBIDDEN; /* protect listing cgi-bin/ */
1715 sendCgi(url, prequest, length, cookie, content_type);
1718 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1720 char *suffix = strrchr(test, '.');
1723 for (cur = config->script_i; cur; cur = cur->next) {
1724 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1725 sendCgi(url, prequest, length, cookie, content_type);
1732 if (prequest != request_GET) {
1733 sendHeaders(HTTP_NOT_IMPLEMENTED);
1736 #endif /* FEATURE_HTTPD_CGI */
1737 if (purl[-1] == '/')
1738 strcpy(purl, "index.html");
1739 if (stat(test, &sb) == 0) {
1740 /* It's a dir URL and there is index.html */
1741 config->ContentLength = sb.st_size;
1742 config->last_mod = sb.st_mtime;
1744 #if ENABLE_FEATURE_HTTPD_CGI
1745 else if (purl[-1] == '/') {
1746 /* It's a dir URL and there is no index.html
1747 * Try cgi-bin/index.cgi */
1748 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1750 config->query = url;
1751 sendCgi("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1755 #endif /* FEATURE_HTTPD_CGI */
1757 config->ContentLength = -1;
1760 #if ENABLE_FEATURE_HTTPD_CGI
1765 fprintf(stderr, "closing socket\n\n");
1766 #if ENABLE_FEATURE_HTTPD_CGI
1769 free(config->referer);
1770 config->referer = NULL;
1771 # if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1772 free(config->remoteuser);
1773 config->remoteuser = NULL;
1776 shutdown(config->accepted_socket, SHUT_WR);
1778 /* Properly wait for remote to closed */
1780 FD_SET(config->accepted_socket, &s_fd);
1785 retval = select(config->accepted_socket + 1, &s_fd, NULL, NULL, &tv);
1786 } while (retval > 0 && read(config->accepted_socket, buf, sizeof(config->buf) > 0));
1788 shutdown(config->accepted_socket, SHUT_RD);
1789 /* In inetd case, we close fd 1 (stdout) here. We will exit soon anyway */
1790 close(config->accepted_socket);
1793 /****************************************************************************
1795 > $Function: miniHttpd()
1797 * $Description: The main http server function.
1799 * Given an open socket fildes, listen for new connections and farm out
1800 * the processing as a forked process.
1803 * (int) server. . . The server socket fildes.
1805 * $Return: (int) . . . . Always 0.
1807 ****************************************************************************/
1808 static int miniHttpd(int server)
1810 fd_set readfd, portfd;
1813 FD_SET(server, &portfd);
1815 /* copy the ports we are watching to the readfd set */
1820 struct sockaddr_in sin;
1821 USE_FEATURE_IPV6(struct sockaddr_in6 sin6;)
1823 socklen_t fromAddrLen = sizeof(fromAddr);
1825 /* Now wait INDEFINITELY on the set of sockets! */
1827 if (select(server + 1, &readfd, 0, 0, 0) <= 0)
1829 if (!FD_ISSET(server, &readfd))
1831 s = accept(server, &fromAddr.sa, &fromAddrLen);
1834 config->accepted_socket = s;
1837 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1838 free(config->rmt_ip_str);
1839 config->rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddrLen);
1841 bb_error_msg("connection from '%s'", config->rmt_ip_str);
1843 #endif /* FEATURE_HTTPD_CGI */
1844 if (fromAddr.sa.sa_family == AF_INET) {
1845 config->rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1846 config->port = ntohs(fromAddr.sin.sin_port);
1848 #if ENABLE_FEATURE_IPV6
1849 if (fromAddr.sa.sa_family == AF_INET6) {
1850 //config->rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1851 config->port = ntohs(fromAddr.sin6.sin6_port);
1855 /* set the KEEPALIVE option to cull dead connections */
1856 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1858 if (DEBUG || fork() == 0) {
1860 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1861 /* protect reload config, may be confuse checking */
1862 signal(SIGHUP, SIG_IGN);
1874 static int miniHttpd_inetd(void)
1878 struct sockaddr_in sin;
1879 USE_FEATURE_IPV6(struct sockaddr_in6 sin6;)
1881 socklen_t fromAddrLen = sizeof(fromAddr);
1883 getpeername(0, &fromAddr.sa, &fromAddrLen);
1886 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1887 free(config->rmt_ip_str);
1888 config->rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddrLen);
1890 if (fromAddr.sa.sa_family == AF_INET) {
1891 config->rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1892 config->port = ntohs(fromAddr.sin.sin_port);
1894 #if ENABLE_FEATURE_IPV6
1895 if (fromAddr.sa.sa_family == AF_INET6) {
1896 //config->rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1897 config->port = ntohs(fromAddr.sin6.sin6_port);
1904 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1905 static void sighup_handler(int sig)
1908 struct sigaction sa;
1910 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1911 sa.sa_handler = sighup_handler;
1912 sigemptyset(&sa.sa_mask);
1913 sa.sa_flags = SA_RESTART;
1914 sigaction(SIGHUP, &sa, NULL);
1919 c_opt_config_file = 0,
1922 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1923 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1924 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1925 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1929 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1930 OPT_DECODE_URL = 1 << d_opt_decode_url,
1931 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1932 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1933 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1934 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1935 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1936 OPT_PORT = 1 << p_opt_port,
1937 OPT_INETD = 1 << p_opt_inetd,
1938 OPT_FOREGROUND = 1 << p_opt_foreground,
1941 static const char httpd_opts[] = "c:d:h:"
1942 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1943 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1944 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1945 USE_FEATURE_HTTPD_SETUID("u:")
1949 int httpd_main(int argc, char *argv[]);
1950 int httpd_main(int argc, char *argv[])
1953 const char *home_httpd = home;
1954 char *url_for_decode;
1955 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1957 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1958 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1959 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1961 #if ENABLE_LOCALE_SUPPORT
1962 /* Undo busybox.c: we want to speak English in http (dates etc) */
1963 setlocale(LC_TIME, "C");
1966 config = xzalloc(sizeof(*config));
1967 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1968 config->realm = "Web Server Authentication";
1971 config->ContentLength = -1;
1973 opt = getopt32(argc, argv, httpd_opts,
1974 &(config->configFile), &url_for_decode, &home_httpd
1975 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1976 USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
1977 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1978 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1981 if (opt & OPT_DECODE_URL) {
1982 printf("%s", decodeString(url_for_decode, 1));
1985 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1986 if (opt & OPT_ENCODE_URL) {
1987 printf("%s", encodeString(url_for_encode));
1991 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1992 if (opt & OPT_MD5) {
1993 puts(pw_encrypt(pass, "$1$"));
1998 config->port = xatou16(s_port);
2000 #if ENABLE_FEATURE_HTTPD_SETUID
2001 if (opt & OPT_SETUID) {
2002 if (!get_uidgid(&ugid, s_ugid, 1))
2003 bb_error_msg_and_die("unrecognized user[:group] "
2004 "name '%s'", s_ugid);
2009 if (!(opt & OPT_INETD)) {
2010 signal(SIGCHLD, SIG_IGN);
2011 config->server_socket = openServer();
2012 #if ENABLE_FEATURE_HTTPD_SETUID
2013 /* drop privileges */
2014 if (opt & OPT_SETUID) {
2015 if (ugid.gid != (gid_t)-1) {
2016 if (setgroups(1, &ugid.gid) == -1)
2017 bb_perror_msg_and_die("setgroups");
2025 #if ENABLE_FEATURE_HTTPD_CGI
2027 char *p = getenv("PATH");
2028 p = xstrdup(p); /* if gets NULL, returns NULL */
2032 if (!(opt & OPT_INETD))
2033 setenv_long("SERVER_PORT", config->port);
2037 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2040 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2043 if (opt & OPT_INETD)
2044 return miniHttpd_inetd();
2046 if (!(opt & OPT_FOREGROUND))
2047 xdaemon(1, 0); /* don't change current directory */
2048 return miniHttpd(config->server_socket);