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 static const char httpdVersion[] = "busybox httpd/1.35 6-Oct-2004";
97 static const char default_path_httpd_conf[] = "/etc";
98 static const char httpd_conf[] = "httpd.conf";
99 static const char home[] = "./";
103 // Note: busybox xfuncs are not used because we want the server to keep running
104 // if something bad happens due to a malformed user request.
105 // As a result, all memory allocation after daemonize
106 // 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;
130 char buf[MAX_MEMORY_BUFF];
132 USE_FEATURE_HTTPD_BASIC_AUTH(const char *realm;)
133 USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
137 USE_FEATURE_HTTPD_CGI(char *referer;)
139 const char *configFile;
142 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
143 char rmt_ip_str[16]; /* for set env REMOTE_ADDR */
145 unsigned port; /* server initial port and for
146 set env REMOTE_PORT */
147 const char *found_mime_type;
148 const char *found_moved_temporarily;
150 off_t ContentLength; /* -1 - unknown */
153 Htaccess_IP *ip_a_d; /* config allow/deny lines */
155 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
156 Htaccess *auth; /* config user:password lines */
158 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
159 Htaccess *mime_a; /* config mime types */
164 volatile int alarm_signaled;
166 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
167 Htaccess *script_i; /* config script interpreters */
171 static HttpdConfig *config;
173 static const char request_GET[] = "GET"; /* size algorithmic optimize */
175 static const char* const suffixTable [] = {
176 /* Warning: shorted equivalent suffix in one line must be first */
177 ".htm.html", "text/html",
178 ".jpg.jpeg", "image/jpeg",
181 ".txt.h.c.cc.cpp", "text/plain",
184 ".avi", "video/x-msvideo",
185 ".qt.mov", "video/quicktime",
186 ".mpe.mpeg", "video/mpeg",
187 ".mid.midi", "audio/midi",
188 ".mp3", "audio/mpeg",
189 #if 0 /* unpopular */
190 ".au", "audio/basic",
191 ".pac", "application/x-ns-proxy-autoconfig",
192 ".vrml.wrl", "model/vrml",
194 0, "application/octet-stream" /* default */
199 HTTP_MOVED_TEMPORARILY = 302,
200 HTTP_BAD_REQUEST = 400, /* malformed syntax */
201 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
202 HTTP_NOT_FOUND = 404,
203 HTTP_FORBIDDEN = 403,
204 HTTP_REQUEST_TIMEOUT = 408,
205 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
206 HTTP_INTERNAL_SERVER_ERROR = 500,
207 #if 0 /* future use */
209 HTTP_SWITCHING_PROTOCOLS = 101,
212 HTTP_NON_AUTHORITATIVE_INFO = 203,
213 HTTP_NO_CONTENT = 204,
214 HTTP_MULTIPLE_CHOICES = 300,
215 HTTP_MOVED_PERMANENTLY = 301,
216 HTTP_NOT_MODIFIED = 304,
217 HTTP_PAYMENT_REQUIRED = 402,
218 HTTP_BAD_GATEWAY = 502,
219 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
220 HTTP_RESPONSE_SETSIZE = 0xffffffff
225 HttpResponseNum type;
230 static const HttpEnumString httpResponseNames[] = {
231 { HTTP_OK, "OK", NULL },
232 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
233 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
234 "No request appeared within a reasonable time period." },
235 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
236 "The requested method is not recognized by this server." },
237 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
238 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
240 { HTTP_NOT_FOUND, "Not Found",
241 "The requested URL was not found on this server." },
242 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
243 { HTTP_FORBIDDEN, "Forbidden", "" },
244 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
245 "Internal Server Error" },
246 #if 0 /* not implemented */
247 { HTTP_CREATED, "Created" },
248 { HTTP_ACCEPTED, "Accepted" },
249 { HTTP_NO_CONTENT, "No Content" },
250 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
251 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
252 { HTTP_NOT_MODIFIED, "Not Modified" },
253 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
254 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
259 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
262 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
265 static int scan_ip(const char **ep, unsigned int *ip, unsigned char endc)
272 for (j = 0; j < 4; j++) {
275 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
278 while (*p >= '0' && *p <= '9') {
287 if (*p != '/' && *p != 0)
289 *ip = ((*ip) << 8) | octet;
302 static int scan_ip_mask(const char *ipm, unsigned int *ip, unsigned int *mask)
307 i = scan_ip(&ipm, ip, '/');
315 if (*p < '0' || *p > '9') {
317 i = scan_ip(&ipm, mask, 0);
339 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
340 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
341 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
342 static void free_config_lines(Htaccess **pprev)
344 Htaccess *prev = *pprev;
347 Htaccess *cur = prev;
357 #define FIRST_PARSE 0
358 #define SUBDIR_PARSE 1
359 #define SIGNALED_PARSE 2
360 #define FIND_FROM_HTTPD_ROOT 3
361 /****************************************************************************
363 > $Function: parse_conf()
365 * $Description: parse configuration file into in-memory linked list.
367 * The first non-white character is examined to determine if the config line
368 * is one of the following:
369 * .ext:mime/type # new mime type not compiled into httpd
370 * [adAD]:from # ip address allow/deny, * for wildcard
371 * /path:user:pass # username/password
373 * Any previous IP rules are discarded.
374 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
375 * are also discarded. That is, previous settings are retained if flag is
379 * (const char *) path . . null for ip address checks, path for password
381 * (int) flag . . . . . . the source of the parse request.
385 ****************************************************************************/
386 static void parse_conf(const char *path, int flag)
389 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
392 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
393 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
394 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
398 const char *cf = config->configFile;
403 /* free previous ip setup if present */
404 Htaccess_IP *pip = config->ip_a_d;
407 Htaccess_IP *cur_ipl = pip;
412 config->ip_a_d = NULL;
414 config->flg_deny_all = 0;
416 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
417 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
418 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
419 /* retain previous auth and mime config only for subdir parse */
420 if (flag != SUBDIR_PARSE) {
421 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
422 free_config_lines(&config->auth);
424 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
425 free_config_lines(&config->mime_a);
427 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
428 free_config_lines(&config->script_i);
433 if (flag == SUBDIR_PARSE || cf == NULL) {
434 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
436 if (flag == FIRST_PARSE)
437 bb_error_msg_and_die(bb_msg_memory_exhausted);
440 sprintf((char *)cf, "%s/%s", path, httpd_conf);
443 while ((f = fopen(cf, "r")) == NULL) {
444 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
445 /* config file not found, no changes to config */
448 if (config->configFile && flag == FIRST_PARSE) /* if -c option given */
449 bb_perror_msg_and_die("%s", cf);
450 flag = FIND_FROM_HTTPD_ROOT;
454 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
457 /* This could stand some work */
458 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
460 for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
463 if (*p0 == ':' && c == NULL)
469 /* test for empty or strange line */
470 if (c == NULL || *c == 0)
477 /* memorize deny all */
478 config->flg_deny_all++;
480 /* skip default other "word:*" config lines */
486 else if (*p0 != 'D' && *p0 != 'A'
487 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
490 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
493 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
498 if (*p0 == 'A' || *p0 == 'D') {
499 /* storing current config IP line */
500 pip = xzalloc(sizeof(Htaccess_IP));
502 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
503 /* syntax IP{/mask} error detected, protect all */
507 pip->allow_deny = *p0;
509 /* Deny:form_IP move top */
510 pip->next = config->ip_a_d;
511 config->ip_a_d = pip;
513 /* add to bottom A:form_IP config line */
514 Htaccess_IP *prev_IP = config->ip_a_d;
516 if (prev_IP == NULL) {
517 config->ip_a_d = pip;
519 while (prev_IP->next)
520 prev_IP = prev_IP->next;
527 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
529 /* make full path from httpd root / curent_path / config_line_path */
530 cf = flag == SUBDIR_PARSE ? path : "";
531 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
535 sprintf(p0, "/%s%s", cf, buf);
537 /* another call bb_simplify_path */
542 if (*cf == '/') { /* skip duplicate (or initial) slash */
544 } else if (*cf == '.') {
545 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
547 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
550 while (*--p != '/') /* omit previous dir */;
559 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
560 ++p; /* so keep last character */
563 sprintf(p0, "%s:%s", p0, c);
567 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
568 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
569 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
570 /* storing current config line */
571 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
573 cf = strcpy(cur->before_colon, p0);
576 cur->after_colon = c;
577 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
579 /* config .mime line move top for overwrite previous */
580 cur->next = config->mime_a;
581 config->mime_a = cur;
585 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
586 if (*cf == '*' && cf[1] == '.') {
587 /* config script interpreter line move top for overwrite previous */
588 cur->next = config->script_i;
589 config->script_i = cur;
593 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
597 config->auth = prev = cur;
599 /* sort path, if current lenght eq or bigger then move up */
600 Htaccess *prev_hti = config->auth;
601 size_t l = strlen(cf);
604 for (hti = prev_hti; hti; hti = hti->next) {
605 if (l >= strlen(hti->before_colon)) {
606 /* insert before hti */
608 if (prev_hti != hti) {
609 prev_hti->next = cur;
617 prev_hti = prev_hti->next;
619 if (!hti) { /* not inserted, add to bottom */
631 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
632 /****************************************************************************
634 > $Function: encodeString()
636 * $Description: Given a string, html encode special characters.
637 * This is used for the -e command line option to provide an easy way
638 * for scripts to encode result data without confusing browsers. The
639 * returned string pointer is memory allocated by malloc().
642 * (const char *) string . . The first string to encode.
644 * $Return: (char *) . . . .. . . A pointer to the encoded string.
646 * $Errors: Returns a null string ("") if memory is not available.
648 ****************************************************************************/
649 static char *encodeString(const char *string)
651 /* take the simple route and encode everything */
652 /* could possibly scan once to get length. */
653 int len = strlen(string);
654 char *out = malloc(len * 6 + 1);
659 while ((ch = *string++)) {
660 // very simple check for what to encode
661 if (isalnum(ch)) *p++ = ch;
662 else p += sprintf(p, "&#%d;", (unsigned char) ch);
667 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
669 /****************************************************************************
671 > $Function: decodeString()
673 * $Description: Given a URL encoded string, convert it to plain ascii.
674 * Since decoding always makes strings smaller, the decode is done in-place.
675 * Thus, callers should strdup() the argument if they do not want the
676 * argument modified. The return is the original pointer, allowing this
677 * function to be easily used as arguments to other functions.
680 * (char *) string . . . The first string to decode.
681 * (int) option_d . . 1 if called for httpd -d
683 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
687 ****************************************************************************/
688 static char *decodeString(char *orig, int option_d)
690 /* note that decoded string is always shorter than original */
695 while ((c = *ptr++) != '\0') {
696 unsigned value1, value2;
698 if (option_d && c == '+') {
706 if (sscanf(ptr, "%1X", &value1) != 1
707 || sscanf(ptr+1, "%1X", &value2) != 1
714 value1 = value1 * 16 + value2;
715 if (!option_d && (value1 == '/' || value1 == '\0')) {
716 /* caller takes it as indication of invalid
717 * (dangerous wrt exploits) chars */
728 #if ENABLE_FEATURE_HTTPD_CGI
729 /****************************************************************************
731 ****************************************************************************/
732 static void setenv1(const char *name, const char *value)
736 setenv(name, value, 1);
738 static void setenv_long(const char *name, long value)
740 char buf[sizeof(value)*3 + 1];
741 sprintf(buf, "%ld", value);
742 setenv(name, buf, 1);
746 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
747 /****************************************************************************
749 > $Function: decodeBase64()
751 > $Description: Decode a base 64 data stream as per rfc1521.
752 * Note that the rfc states that none base64 chars are to be ignored.
753 * Since the decode always results in a shorter size than the input, it is
754 * OK to pass the input arg as an output arg.
757 * (char *) Data . . . . A pointer to a base64 encoded string.
758 * Where to place the decoded data.
764 ****************************************************************************/
765 static void decodeBase64(char *Data)
768 const unsigned char *in = (const unsigned char *)Data;
769 // The decoded size will be at most 3/4 the size of the encoded
770 unsigned long ch = 0;
776 if (t >= '0' && t <= '9')
778 else if (t >= 'A' && t <= 'Z')
780 else if (t >= 'a' && t <= 'z')
794 *Data++ = (char) (ch >> 16);
795 *Data++ = (char) (ch >> 8);
805 /****************************************************************************
807 > $Function: openServer()
809 * $Description: create a listen server socket on the designated port.
811 * $Return: (int) . . . A connection socket. -1 for errors.
815 ****************************************************************************/
816 static int openServer(void)
818 struct sockaddr_in lsocket;
821 /* create the socket right now */
822 /* inet_addr() returns a value that is already in network order */
823 memset(&lsocket, 0, sizeof(lsocket));
824 lsocket.sin_family = AF_INET;
825 lsocket.sin_addr.s_addr = INADDR_ANY;
826 lsocket.sin_port = htons(config->port);
827 fd = xsocket(AF_INET, SOCK_STREAM, 0);
828 /* tell the OS it's OK to reuse a previous address even though */
829 /* it may still be in a close down state. Allows bind to succeed. */
832 static const int on = 1;
833 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT,
834 (void *)&on, sizeof(on));
837 setsockopt_reuseaddr(fd);
839 xbind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket));
841 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
845 /****************************************************************************
847 > $Function: sendHeaders()
849 * $Description: Create and send HTTP response headers.
850 * The arguments are combined and sent as one write operation. Note that
851 * IE will puke big-time if the headers are not sent in one packet and the
852 * second packet is delayed for any reason.
855 * (HttpResponseNum) responseNum . . . The result code to send.
857 * $Return: (int) . . . . writing errors
859 ****************************************************************************/
860 static int sendHeaders(HttpResponseNum responseNum)
862 char *buf = config->buf;
863 const char *responseString = "";
864 const char *infoString = 0;
865 const char *mime_type;
867 time_t timer = time(0);
871 numNames = sizeof(httpResponseNames) / sizeof(httpResponseNames[0])
874 for (i = 0; i < numNames; i++) {
875 if (httpResponseNames[i].type == responseNum) {
876 responseString = httpResponseNames[i].name;
877 infoString = httpResponseNames[i].info;
881 /* error message is HTML */
882 mime_type = responseNum == HTTP_OK ?
883 config->found_mime_type : "text/html";
885 /* emit the current date */
886 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
888 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
889 "Date: %s\r\nConnection: close\r\n",
890 responseNum, responseString, mime_type, timeStr);
892 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
893 if (responseNum == HTTP_UNAUTHORIZED) {
894 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
898 if (responseNum == HTTP_MOVED_TEMPORARILY) {
899 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
900 config->found_moved_temporarily,
901 (config->query ? "?" : ""),
902 (config->query ? config->query : ""));
905 if (config->ContentLength != -1) { /* file */
906 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
907 len += sprintf(buf+len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
908 timeStr, "Content-length:", config->ContentLength);
913 len += sprintf(buf+len,
914 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
915 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
916 responseNum, responseString,
917 responseNum, responseString, infoString);
920 fprintf(stderr, "headers: '%s'\n", buf);
921 return full_write(config->accepted_socket, buf, len);
924 /****************************************************************************
926 > $Function: getLine()
928 * $Description: Read from the socket until an end of line char found.
930 * Characters are read one at a time until an eol sequence is found.
932 * $Return: (int) . . . . number of characters read. -1 if error.
934 ****************************************************************************/
935 static int getLine(void)
938 char *buf = config->buf;
940 while (read(config->accepted_socket, buf + count, 1) == 1) {
941 if (buf[count] == '\r') continue;
942 if (buf[count] == '\n') {
946 if (count < (MAX_MEMORY_BUFF-1)) /* check overflow */
949 if (count) return count;
953 #if ENABLE_FEATURE_HTTPD_CGI
954 /****************************************************************************
956 > $Function: sendCgi()
958 * $Description: Execute a CGI script and send it's stdout back
960 * Environment variables are set up and the script is invoked with pipes
961 * for stdin/stdout. If a post is being done the script is fed the POST
962 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
965 * (const char *) url . . . . . . The requested URL (with leading /).
966 * (int bodyLen) . . . . . . . . Length of the post body.
967 * (const char *cookie) . . . . . For set HTTP_COOKIE.
968 * (const char *content_type) . . For set CONTENT_TYPE.
971 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
975 ****************************************************************************/
976 static int sendCgi(const char *url,
977 const char *request, int bodyLen, const char *cookie,
978 const char *content_type)
980 int fromCgi[2]; /* pipe for reading data from CGI */
981 int toCgi[2]; /* pipe for sending data to CGI */
983 static char * argp[] = { 0, 0 };
989 size_t post_readed_size, post_readed_idx;
991 if (pipe(fromCgi) != 0)
993 if (pipe(toCgi) != 0)
1003 char *purl = strdup(url);
1004 char realpath_buff[MAXPATHLEN];
1012 dup2(inFd, 0); // replace stdin with the pipe
1013 dup2(outFd, 1); // replace stdout with the pipe
1015 dup2(outFd, 2); // replace stderr with the pipe
1022 close(config->accepted_socket);
1023 close(config->server_socket);
1029 while ((script = strchr(script + 1, '/')) != NULL) {
1030 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1034 if (is_directory(purl + 1, 1, &sb) == 0) {
1035 /* not directory, found script.cgi/PATH_INFO */
1039 *script = '/'; /* is directory, find next '/' */
1041 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1042 /* setenv1("PATH", getenv("PATH")); redundant */
1043 setenv1("REQUEST_METHOD", request);
1044 if (config->query) {
1045 char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
1047 sprintf(uri, "%s?%s", purl, config->query);
1048 setenv1("REQUEST_URI", uri);
1050 setenv1("REQUEST_URI", purl);
1053 *script = '\0'; /* cut off /PATH_INFO */
1054 /* SCRIPT_FILENAME required by PHP in CGI mode */
1055 if (!realpath(purl + 1, realpath_buff))
1056 goto error_execing_cgi;
1057 setenv1("SCRIPT_FILENAME", realpath_buff);
1058 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1059 setenv1("SCRIPT_NAME", purl);
1060 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1061 * QUERY_STRING: The information which follows the ? in the URL
1062 * which referenced this script. This is the query information.
1063 * It should not be decoded in any fashion. This variable
1064 * should always be set when there is query information,
1065 * regardless of command line decoding. */
1066 /* (Older versions of bbox seem to do some decoding) */
1067 setenv1("QUERY_STRING", config->query);
1068 setenv1("SERVER_SOFTWARE", httpdVersion);
1069 putenv("SERVER_PROTOCOL=HTTP/1.0");
1070 putenv("GATEWAY_INTERFACE=CGI/1.1");
1071 setenv1("REMOTE_ADDR", config->rmt_ip_str);
1072 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1073 setenv_long("REMOTE_PORT", config->port);
1076 setenv_long("CONTENT_LENGTH", bodyLen);
1078 setenv1("HTTP_COOKIE", cookie);
1080 setenv1("CONTENT_TYPE", content_type);
1081 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1082 if (config->remoteuser) {
1083 setenv1("REMOTE_USER", config->remoteuser);
1084 putenv("AUTH_TYPE=Basic");
1087 if (config->referer)
1088 setenv1("HTTP_REFERER", config->referer);
1090 /* set execve argp[0] without path */
1091 argp[0] = strrchr(purl, '/') + 1;
1092 /* but script argp[0] must have absolute path and chdiring to this */
1093 script = strrchr(realpath_buff, '/');
1095 goto error_execing_cgi;
1097 if (chdir(realpath_buff) == 0) {
1098 // Now run the program. If it fails,
1099 // use _exit() so no destructors
1100 // get called and make a mess.
1101 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1102 char *interpr = NULL;
1103 char *suffix = strrchr(purl, '.');
1107 for (cur = config->script_i; cur; cur = cur->next) {
1108 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1109 interpr = cur->after_colon;
1116 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1118 execv(interpr, argp);
1121 execv(realpath_buff, argp);
1124 /* send to stdout (even if we are not from inetd) */
1125 config->accepted_socket = 1;
1126 sendHeaders(HTTP_NOT_FOUND);
1130 /* parent process */
1132 post_readed_size = 0;
1133 post_readed_idx = 0;
1138 signal(SIGPIPE, SIG_IGN);
1149 FD_SET(inFd, &readSet);
1150 if (bodyLen > 0 || post_readed_size > 0) {
1151 FD_SET(outFd, &writeSet);
1152 nfound = outFd > inFd ? outFd : inFd;
1153 if (post_readed_size == 0) {
1154 FD_SET(config->accepted_socket, &readSet);
1155 if (nfound < config->accepted_socket)
1156 nfound = config->accepted_socket;
1158 /* Now wait on the set of sockets! */
1159 nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
1165 nfound = select(inFd + 1, &readSet, 0, 0, NULL);
1169 if (waitpid(pid, &status, WNOHANG) > 0) {
1171 if (DEBUG && WIFEXITED(status))
1172 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1173 if (DEBUG && WIFSIGNALED(status))
1174 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1177 } else if (post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1178 count = full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1180 post_readed_size -= count;
1181 post_readed_idx += count;
1182 if (post_readed_size == 0)
1183 post_readed_idx = 0;
1185 post_readed_size = post_readed_idx = bodyLen = 0; /* broken pipe to CGI */
1187 } else if (bodyLen > 0 && post_readed_size == 0 && FD_ISSET(config->accepted_socket, &readSet)) {
1188 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1189 count = safe_read(config->accepted_socket, wbuf, count);
1191 post_readed_size += count;
1194 bodyLen = 0; /* closed */
1197 if (FD_ISSET(inFd, &readSet)) {
1198 int s = config->accepted_socket;
1199 char *rbuf = config->buf;
1202 # define PIPESIZE 4096 /* amount of buffering in a pipe */
1204 # define PIPESIZE PIPE_BUF
1206 #if PIPESIZE >= MAX_MEMORY_BUFF
1207 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1210 /* There is something to read */
1211 /* NB: was safe_read. If it *has to be* safe_read, */
1212 /* please explain why in this comment... */
1213 count = full_read(inFd, rbuf, PIPESIZE);
1218 /* full_read (above) avoids
1219 * "chopped up into small chunks" syndrome here */
1221 /* check to see if the user script added headers */
1222 if (strncmp(rbuf, "HTTP/1.0 200 OK\r\n", 4) != 0) {
1223 /* there is no "HTTP", do it ourself */
1224 full_write(s, "HTTP/1.0 200 OK\r\n", 17);
1225 } /* hmm, maybe 'else if'? */
1226 if (!strstr(rbuf, "ontent-")) {
1227 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1231 if (full_write(s, rbuf, count) != count)
1235 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1241 #endif /* FEATURE_HTTPD_CGI */
1243 /****************************************************************************
1245 > $Function: sendFile()
1247 * $Description: Send a file response to a HTTP request
1250 * (const char *) url . . The URL requested.
1252 * $Return: (int) . . . . . . Always 0.
1254 ****************************************************************************/
1255 static int sendFile(const char *url)
1259 const char * const * table;
1260 const char * try_suffix;
1262 suffix = strrchr(url, '.');
1264 for (table = suffixTable; *table; table += 2)
1265 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1266 try_suffix += strlen(suffix);
1267 if (*try_suffix == 0 || *try_suffix == '.')
1270 /* also, if not found, set default as "application/octet-stream"; */
1271 config->found_mime_type = table[1];
1272 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1276 for (cur = config->mime_a; cur; cur = cur->next) {
1277 if (strcmp(cur->before_colon, suffix) == 0) {
1278 config->found_mime_type = cur->after_colon;
1283 #endif /* FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1286 fprintf(stderr, "sending file '%s' content-type: %s\n",
1287 url, config->found_mime_type);
1289 f = open(url, O_RDONLY);
1292 char *buf = config->buf;
1294 sendHeaders(HTTP_OK);
1295 /* TODO: sendfile() */
1296 while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1297 if (full_write(config->accepted_socket, buf, count) != count)
1303 bb_perror_msg("cannot open '%s'", url);
1304 sendHeaders(HTTP_NOT_FOUND);
1310 static int checkPermIP(void)
1314 /* This could stand some work */
1315 for (cur = config->ip_a_d; cur; cur = cur->next) {
1317 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1320 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1321 (unsigned char)(cur->ip >> 24),
1322 (unsigned char)(cur->ip >> 16),
1323 (unsigned char)(cur->ip >> 8),
1325 (unsigned char)(cur->mask >> 24),
1326 (unsigned char)(cur->mask >> 16),
1327 (unsigned char)(cur->mask >> 8),
1329 if ((config->rmt_ip & cur->mask) == cur->ip)
1330 return cur->allow_deny == 'A'; /* Allow/Deny */
1333 /* if unconfigured, return 1 - access from all */
1334 return !config->flg_deny_all;
1337 /****************************************************************************
1339 > $Function: checkPerm()
1341 * $Description: Check the permission file for access password protected.
1343 * If config file isn't present, everything is allowed.
1344 * Entries are of the form you can see example from header source
1347 * (const char *) path . . . . The file path.
1348 * (const char *) request . . . User information to validate.
1350 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1352 ****************************************************************************/
1354 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1355 static int checkPerm(const char *path, const char *request)
1361 const char *prev = NULL;
1363 /* This could stand some work */
1364 for (cur = config->auth; cur; cur = cur->next) {
1367 p0 = cur->before_colon;
1368 if (prev != NULL && strcmp(prev, p0) != 0)
1369 continue; /* find next identical */
1370 p = cur->after_colon;
1372 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1375 if (strncmp(p0, path, l) == 0
1376 && (l == 1 || path[l] == '/' || path[l] == '\0')
1379 /* path match found. Check request */
1380 /* for check next /path:user:password */
1382 u = strchr(request, ':');
1384 /* bad request, ':' required */
1388 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1392 if (strncmp(p, request, u-request) != 0) {
1393 /* user uncompared */
1396 pp = strchr(p, ':');
1397 if (pp && pp[1] == '$' && pp[2] == '1' &&
1398 pp[3] == '$' && pp[4]) {
1400 cipher = pw_encrypt(u+1, pp);
1401 if (strcmp(cipher, pp) == 0)
1402 goto set_remoteuser_var; /* Ok */
1408 if (strcmp(p, request) == 0) {
1410 config->remoteuser = strdup(request);
1411 if (config->remoteuser)
1412 config->remoteuser[(u - request)] = 0;
1419 return prev == NULL;
1422 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1424 /****************************************************************************
1426 > $Function: handle_sigalrm()
1428 * $Description: Handle timeouts
1430 ****************************************************************************/
1432 static void handle_sigalrm(int sig)
1434 sendHeaders(HTTP_REQUEST_TIMEOUT);
1435 config->alarm_signaled = sig;
1438 /****************************************************************************
1440 > $Function: handleIncoming()
1442 * $Description: Handle an incoming http request.
1444 ****************************************************************************/
1445 static void handleIncoming(void)
1447 char *buf = config->buf;
1454 #if ENABLE_FEATURE_HTTPD_CGI
1455 const char *prequest = request_GET;
1456 unsigned long length = 0;
1458 char *content_type = 0;
1463 struct sigaction sa;
1465 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1466 int credentials = -1; /* if not required this is Ok */
1469 sa.sa_handler = handle_sigalrm;
1470 sigemptyset(&sa.sa_mask);
1471 sa.sa_flags = 0; /* no SA_RESTART */
1472 sigaction(SIGALRM, &sa, NULL);
1477 (void) alarm(TIMEOUT);
1481 purl = strpbrk(buf, " \t");
1484 sendHeaders(HTTP_BAD_REQUEST);
1488 #if ENABLE_FEATURE_HTTPD_CGI
1489 if (strcasecmp(buf, prequest) != 0) {
1491 if (strcasecmp(buf, prequest) != 0) {
1492 sendHeaders(HTTP_NOT_IMPLEMENTED);
1497 if (strcasecmp(buf, request_GET) != 0) {
1498 sendHeaders(HTTP_NOT_IMPLEMENTED);
1503 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1505 if (count < 1 || buf[0] != '/') {
1506 /* Garbled request/URL */
1509 url = alloca(strlen(buf) + sizeof("/index.html"));
1511 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1515 /* extract url args if present */
1516 test = strchr(url, '?');
1517 config->query = NULL;
1520 config->query = test;
1523 test = decodeString(url, 0);
1526 if (test == url+1) {
1527 /* '/' or NUL is encoded */
1528 sendHeaders(HTTP_NOT_FOUND);
1532 /* algorithm stolen from libbb bb_simplify_path(),
1533 but don't strdup and reducing trailing slash and protect out root */
1537 /* skip duplicate (or initial) slash */
1542 /* skip extra '.' */
1543 if (test[1] == '/' || test[1] == 0) {
1546 /* '..': be careful */
1547 if (test[1] == '.' && (test[2] == '/' || test[2] == 0)) {
1550 /* protect out root */
1553 while (*--purl != '/') /* omit previous dir */;
1560 *++purl = '\0'; /* so keep last character */
1561 test = purl; /* end ptr */
1563 /* If URL is directory, adding '/' */
1564 if (test[-1] != '/') {
1565 if (is_directory(url + 1, 1, &sb)) {
1566 config->found_moved_temporarily = url;
1570 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1573 ip_allowed = checkPermIP();
1574 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1575 /* have path1/path2 */
1577 if (is_directory(url + 1, 1, &sb)) {
1578 /* may be having subdir config */
1579 parse_conf(url + 1, SUBDIR_PARSE);
1580 ip_allowed = checkPermIP();
1585 /* read until blank line for HTTP version specified, else parse immediate */
1593 fprintf(stderr, "header: '%s'\n", buf);
1595 #if ENABLE_FEATURE_HTTPD_CGI
1596 /* try and do our best to parse more lines */
1597 if ((STRNCASECMP(buf, "Content-length:") == 0)) {
1598 /* extra read only for POST */
1599 if (prequest != request_GET) {
1600 test = buf + sizeof("Content-length:")-1;
1604 /* not using strtoul: it ignores leading munis! */
1605 length = strtol(test, &test, 10);
1606 /* length is "ulong", but we need to pass it to int later */
1607 /* so we check for negative or too large values in one go: */
1608 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1609 if (test[0] || errno || length > INT_MAX)
1612 } else if ((STRNCASECMP(buf, "Cookie:") == 0)) {
1613 cookie = strdup(skip_whitespace(buf + sizeof("Cookie:")-1));
1614 } else if ((STRNCASECMP(buf, "Content-Type:") == 0)) {
1615 content_type = strdup(skip_whitespace(buf + sizeof("Content-Type:")-1));
1616 } else if ((STRNCASECMP(buf, "Referer:") == 0)) {
1617 config->referer = strdup(skip_whitespace(buf + sizeof("Referer:")-1));
1621 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1622 if (STRNCASECMP(buf, "Authorization:") == 0) {
1623 /* We only allow Basic credentials.
1624 * It shows up as "Authorization: Basic <userid:password>" where
1625 * the userid:password is base64 encoded.
1627 test = skip_whitespace(buf + sizeof("Authorization:")-1);
1628 if (STRNCASECMP(test, "Basic") != 0)
1630 test += sizeof("Basic")-1;
1631 /* decodeBase64() skips whitespace itself */
1633 credentials = checkPerm(url, test);
1635 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1637 } /* while extra header reading */
1640 if (config->alarm_signaled)
1643 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1644 /* protect listing [/path]/httpd_conf or IP deny */
1645 #if ENABLE_FEATURE_HTTPD_CGI
1646 FORBIDDEN: /* protect listing /cgi-bin */
1648 sendHeaders(HTTP_FORBIDDEN);
1652 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1653 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1654 sendHeaders(HTTP_UNAUTHORIZED);
1659 if (config->found_moved_temporarily) {
1660 sendHeaders(HTTP_MOVED_TEMPORARILY);
1661 /* clear unforked memory flag */
1662 config->found_moved_temporarily = NULL;
1666 test = url + 1; /* skip first '/' */
1668 #if ENABLE_FEATURE_HTTPD_CGI
1669 if (strncmp(test, "cgi-bin", 7) == 0) {
1670 if (test[7] == '/' && test[8] == 0)
1671 goto FORBIDDEN; /* protect listing cgi-bin/ */
1672 sendCgi(url, prequest, length, cookie, content_type);
1675 if (prequest != request_GET) {
1676 sendHeaders(HTTP_NOT_IMPLEMENTED);
1679 #endif /* FEATURE_HTTPD_CGI */
1680 if (purl[-1] == '/')
1681 strcpy(purl, "index.html");
1682 if (stat(test, &sb) == 0) {
1683 /* It's a dir URL and there is index.html */
1684 config->ContentLength = sb.st_size;
1685 config->last_mod = sb.st_mtime;
1687 #if ENABLE_FEATURE_HTTPD_CGI
1688 else if (purl[-1] == '/') {
1689 /* It's a dir URL and there is no index.html
1690 * Try cgi-bin/index.cgi */
1691 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1693 config->query = url;
1694 sendCgi("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1698 #endif /* FEATURE_HTTPD_CGI */
1700 config->ContentLength = -1;
1703 #if ENABLE_FEATURE_HTTPD_CGI
1708 fprintf(stderr, "closing socket\n\n");
1709 #if ENABLE_FEATURE_HTTPD_CGI
1712 free(config->referer);
1713 config->referer = NULL;
1714 # if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1715 free(config->remoteuser);
1716 config->remoteuser = NULL;
1719 shutdown(config->accepted_socket, SHUT_WR);
1721 /* Properly wait for remote to closed */
1723 FD_SET(config->accepted_socket, &s_fd);
1728 retval = select(config->accepted_socket + 1, &s_fd, NULL, NULL, &tv);
1729 } while (retval > 0 && read(config->accepted_socket, buf, sizeof(config->buf) > 0));
1731 shutdown(config->accepted_socket, SHUT_RD);
1732 /* In inetd case, we close fd 1 (stdout) here. We will exit soon anyway */
1733 close(config->accepted_socket);
1736 /****************************************************************************
1738 > $Function: miniHttpd()
1740 * $Description: The main http server function.
1742 * Given an open socket fildes, listen for new connections and farm out
1743 * the processing as a forked process.
1746 * (int) server. . . The server socket fildes.
1748 * $Return: (int) . . . . Always 0.
1750 ****************************************************************************/
1751 static int miniHttpd(int server)
1753 fd_set readfd, portfd;
1756 FD_SET(server, &portfd);
1758 /* copy the ports we are watching to the readfd set */
1761 socklen_t fromAddrLen;
1762 struct sockaddr_in fromAddr;
1764 /* Now wait INDEFINITELY on the set of sockets! */
1766 if (select(server + 1, &readfd, 0, 0, 0) <= 0)
1768 if (!FD_ISSET(server, &readfd))
1770 fromAddrLen = sizeof(fromAddr);
1771 s = accept(server, (struct sockaddr *)&fromAddr, &fromAddrLen);
1774 config->accepted_socket = s;
1775 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1776 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1777 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1778 (unsigned char)(config->rmt_ip >> 24),
1779 (unsigned char)(config->rmt_ip >> 16),
1780 (unsigned char)(config->rmt_ip >> 8),
1781 config->rmt_ip & 0xff);
1782 config->port = ntohs(fromAddr.sin_port);
1784 bb_error_msg("connection from IP=%s, port %u",
1785 config->rmt_ip_str, config->port);
1787 #endif /* FEATURE_HTTPD_CGI */
1789 /* set the KEEPALIVE option to cull dead connections */
1791 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
1793 if (DEBUG || fork() == 0) {
1795 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1796 /* protect reload config, may be confuse checking */
1797 signal(SIGHUP, SIG_IGN);
1809 static int miniHttpd_inetd(void)
1811 struct sockaddr_in fromAddrLen;
1812 socklen_t sinlen = sizeof(struct sockaddr_in);
1814 getpeername(0, (struct sockaddr *)&fromAddrLen, &sinlen);
1815 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1816 #if ENABLE_FEATURE_HTTPD_CGI
1817 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1818 (unsigned char)(config->rmt_ip >> 24),
1819 (unsigned char)(config->rmt_ip >> 16),
1820 (unsigned char)(config->rmt_ip >> 8),
1821 config->rmt_ip & 0xff);
1823 config->port = ntohs(fromAddrLen.sin_port);
1828 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1829 static void sighup_handler(int sig)
1832 struct sigaction sa;
1834 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1835 sa.sa_handler = sighup_handler;
1836 sigemptyset(&sa.sa_mask);
1837 sa.sa_flags = SA_RESTART;
1838 sigaction(SIGHUP, &sa, NULL);
1843 c_opt_config_file = 0,
1846 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1847 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1848 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1849 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1853 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1854 OPT_DECODE_URL = 1 << d_opt_decode_url,
1855 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1856 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1857 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1858 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1859 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1860 OPT_PORT = 1 << p_opt_port,
1861 OPT_INETD = 1 << p_opt_inetd,
1862 OPT_FOREGROUND = 1 << p_opt_foreground,
1865 static const char httpd_opts[] = "c:d:h:"
1866 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1867 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1868 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1869 USE_FEATURE_HTTPD_SETUID("u:")
1873 int httpd_main(int argc, char *argv[])
1876 const char *home_httpd = home;
1877 char *url_for_decode;
1878 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1880 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1881 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1882 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1884 #if ENABLE_LOCALE_SUPPORT
1885 /* Undo busybox.c: we want to speak English in http (dates etc) */
1886 setlocale(LC_TIME, "C");
1889 config = xzalloc(sizeof(*config));
1890 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1891 config->realm = "Web Server Authentication";
1894 config->ContentLength = -1;
1896 opt = getopt32(argc, argv, httpd_opts,
1897 &(config->configFile), &url_for_decode, &home_httpd
1898 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1899 USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
1900 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1901 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1904 if (opt & OPT_DECODE_URL) {
1905 printf("%s", decodeString(url_for_decode, 1));
1908 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1909 if (opt & OPT_ENCODE_URL) {
1910 printf("%s", encodeString(url_for_encode));
1914 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1915 if (opt & OPT_MD5) {
1916 puts(pw_encrypt(pass, "$1$"));
1921 config->port = xatou16(s_port);
1923 #if ENABLE_FEATURE_HTTPD_SETUID
1924 if (opt & OPT_SETUID) {
1925 if (!get_uidgid(&ugid, s_ugid, 1))
1926 bb_error_msg_and_die("unrecognized user[:group] "
1927 "name '%s'", s_ugid);
1932 if (!(opt & OPT_INETD)) {
1933 config->server_socket = openServer();
1934 #if ENABLE_FEATURE_HTTPD_SETUID
1935 /* drop privileges */
1936 if (opt & OPT_SETUID) {
1937 if (ugid.gid != (gid_t)-1) {
1938 if (setgroups(1, &ugid.gid) == -1)
1939 bb_perror_msg_and_die("setgroups");
1947 #if ENABLE_FEATURE_HTTPD_CGI
1949 char *p = getenv("PATH");
1950 p = xstrdup(p); /* if gets NULL, returns NULL */
1954 if (!(opt & OPT_INETD))
1955 setenv_long("SERVER_PORT", config->port);
1959 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1962 parse_conf(default_path_httpd_conf, FIRST_PARSE);
1965 if (opt & OPT_INETD)
1966 return miniHttpd_inetd();
1968 if (!(opt & OPT_FOREGROUND))
1969 xdaemon(1, 0); /* don't change current directory */
1970 return miniHttpd(config->server_socket);