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.
98 static const char httpdVersion[] = "busybox httpd/1.35 6-Oct-2004";
99 static const char default_path_httpd_conf[] = "/etc";
100 static const char httpd_conf[] = "httpd.conf";
101 static const char home[] = "./";
105 // Note: busybox xfuncs are not used because we want the server to keep running
106 // if something bad happens due to a malformed user request.
107 // As a result, all memory allocation after daemonize
108 // 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[16]; /* 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 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
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
390 Htaccess *prev, *cur;
391 #elif ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
395 const char *cf = config->configFile;
400 /* free previous ip setup if present */
401 Htaccess_IP *pip = config->ip_a_d;
404 Htaccess_IP *cur_ipl = pip;
409 config->ip_a_d = NULL;
411 config->flg_deny_all = 0;
413 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
414 /* retain previous auth and mime config only for subdir parse */
415 if (flag != SUBDIR_PARSE) {
416 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
417 free_config_lines(&config->auth);
419 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
420 free_config_lines(&config->mime_a);
422 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
423 free_config_lines(&config->script_i);
428 if (flag == SUBDIR_PARSE || cf == NULL) {
429 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
431 if (flag == FIRST_PARSE)
432 bb_error_msg_and_die(bb_msg_memory_exhausted);
435 sprintf((char *)cf, "%s/%s", path, httpd_conf);
438 while ((f = fopen(cf, "r")) == NULL) {
439 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
440 /* config file not found, no changes to config */
443 if (config->configFile && flag == FIRST_PARSE) /* if -c option given */
444 bb_perror_msg_and_die("%s", cf);
445 flag = FIND_FROM_HTTPD_ROOT;
449 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
452 /* This could stand some work */
453 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
455 for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
458 if (*p0 == ':' && c == NULL)
464 /* test for empty or strange line */
465 if (c == NULL || *c == 0)
472 /* memorize deny all */
473 config->flg_deny_all++;
475 /* skip default other "word:*" config lines */
481 else if (*p0 != 'D' && *p0 != 'A'
482 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
485 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
488 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
493 if (*p0 == 'A' || *p0 == 'D') {
494 /* storing current config IP line */
495 pip = calloc(1, sizeof(Htaccess_IP));
497 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
498 /* syntax IP{/mask} error detected, protect all */
502 pip->allow_deny = *p0;
504 /* Deny:form_IP move top */
505 pip->next = config->ip_a_d;
506 config->ip_a_d = pip;
508 /* add to bottom A:form_IP config line */
509 Htaccess_IP *prev_IP = config->ip_a_d;
511 if (prev_IP == NULL) {
512 config->ip_a_d = pip;
514 while (prev_IP->next)
515 prev_IP = prev_IP->next;
522 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
524 /* make full path from httpd root / curent_path / config_line_path */
525 cf = flag == SUBDIR_PARSE ? path : "";
526 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
530 sprintf(p0, "/%s%s", cf, buf);
532 /* another call bb_simplify_path */
537 if (*cf == '/') { /* skip duplicate (or initial) slash */
539 } else if (*cf == '.') {
540 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
542 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
545 while (*--p != '/') /* omit previous dir */;
554 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
555 ++p; /* so keep last character */
558 sprintf(p0, "%s:%s", p0, c);
562 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
563 /* storing current config line */
564 cur = calloc(1, sizeof(Htaccess) + strlen(p0));
566 cf = strcpy(cur->before_colon, p0);
569 cur->after_colon = c;
570 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
572 /* config .mime line move top for overwrite previous */
573 cur->next = config->mime_a;
574 config->mime_a = cur;
578 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
579 if (*cf == '*' && cf[1] == '.') {
580 /* config script interpreter line move top for overwrite previous */
581 cur->next = config->script_i;
582 config->script_i = cur;
586 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
590 config->auth = prev = cur;
592 /* sort path, if current lenght eq or bigger then move up */
593 Htaccess *prev_hti = config->auth;
594 size_t l = strlen(cf);
597 for (hti = prev_hti; hti; hti = hti->next) {
598 if (l >= strlen(hti->before_colon)) {
599 /* insert before hti */
601 if (prev_hti != hti) {
602 prev_hti->next = cur;
610 prev_hti = prev_hti->next;
612 if (!hti) { /* not inserted, add to bottom */
624 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
625 /****************************************************************************
627 > $Function: encodeString()
629 * $Description: Given a string, html encode special characters.
630 * This is used for the -e command line option to provide an easy way
631 * for scripts to encode result data without confusing browsers. The
632 * returned string pointer is memory allocated by malloc().
635 * (const char *) string . . The first string to encode.
637 * $Return: (char *) . . . .. . . A pointer to the encoded string.
639 * $Errors: Returns a null string ("") if memory is not available.
641 ****************************************************************************/
642 static char *encodeString(const char *string)
644 /* take the simple route and encode everything */
645 /* could possibly scan once to get length. */
646 int len = strlen(string);
647 char *out = malloc(len * 6 + 1);
652 while ((ch = *string++)) {
653 // very simple check for what to encode
654 if (isalnum(ch)) *p++ = ch;
655 else p += sprintf(p, "&#%d;", (unsigned char) ch);
660 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
662 /****************************************************************************
664 > $Function: decodeString()
666 * $Description: Given a URL encoded string, convert it to plain ascii.
667 * Since decoding always makes strings smaller, the decode is done in-place.
668 * Thus, callers should strdup() the argument if they do not want the
669 * argument modified. The return is the original pointer, allowing this
670 * function to be easily used as arguments to other functions.
673 * (char *) string . . . The first string to decode.
674 * (int) option_d . . 1 if called for httpd -d
676 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
680 ****************************************************************************/
681 static char *decodeString(char *orig, int option_d)
683 /* note that decoded string is always shorter than original */
688 while ((c = *ptr++) != '\0') {
689 unsigned value1, value2;
691 if (option_d && c == '+') {
699 if (sscanf(ptr, "%1X", &value1) != 1
700 || sscanf(ptr+1, "%1X", &value2) != 1
707 value1 = value1 * 16 + value2;
708 if (!option_d && (value1 == '/' || value1 == '\0')) {
709 /* caller takes it as indication of invalid
710 * (dangerous wrt exploits) chars */
721 #if ENABLE_FEATURE_HTTPD_CGI
722 /****************************************************************************
724 ****************************************************************************/
725 static void setenv1(const char *name, const char *value)
729 setenv(name, value, 1);
731 static void setenv_long(const char *name, long value)
733 char buf[sizeof(value)*3 + 1];
734 sprintf(buf, "%ld", value);
735 setenv(name, buf, 1);
739 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
740 /****************************************************************************
742 > $Function: decodeBase64()
744 > $Description: Decode a base 64 data stream as per rfc1521.
745 * Note that the rfc states that none base64 chars are to be ignored.
746 * Since the decode always results in a shorter size than the input, it is
747 * OK to pass the input arg as an output arg.
750 * (char *) Data . . . . A pointer to a base64 encoded string.
751 * Where to place the decoded data.
757 ****************************************************************************/
758 static void decodeBase64(char *Data)
761 const unsigned char *in = (const unsigned char *)Data;
762 // The decoded size will be at most 3/4 the size of the encoded
763 unsigned long ch = 0;
769 if (t >= '0' && t <= '9')
771 else if (t >= 'A' && t <= 'Z')
773 else if (t >= 'a' && t <= 'z')
787 *Data++ = (char) (ch >> 16);
788 *Data++ = (char) (ch >> 8);
798 /****************************************************************************
800 > $Function: openServer()
802 * $Description: create a listen server socket on the designated port.
804 * $Return: (int) . . . A connection socket. -1 for errors.
808 ****************************************************************************/
809 static int openServer(void)
811 struct sockaddr_in lsocket;
814 /* create the socket right now */
815 /* inet_addr() returns a value that is already in network order */
816 memset(&lsocket, 0, sizeof(lsocket));
817 lsocket.sin_family = AF_INET;
818 lsocket.sin_addr.s_addr = INADDR_ANY;
819 lsocket.sin_port = htons(config->port);
820 fd = xsocket(AF_INET, SOCK_STREAM, 0);
821 /* tell the OS it's OK to reuse a previous address even though */
822 /* it may still be in a close down state. Allows bind to succeed. */
825 static const int on = 1;
826 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT,
827 (void *)&on, sizeof(on));
830 setsockopt_reuseaddr(fd);
832 xbind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket));
834 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
838 /****************************************************************************
840 > $Function: sendHeaders()
842 * $Description: Create and send HTTP response headers.
843 * The arguments are combined and sent as one write operation. Note that
844 * IE will puke big-time if the headers are not sent in one packet and the
845 * second packet is delayed for any reason.
848 * (HttpResponseNum) responseNum . . . The result code to send.
850 * $Return: (int) . . . . writing errors
852 ****************************************************************************/
853 static int sendHeaders(HttpResponseNum responseNum)
855 char *buf = config->buf;
856 const char *responseString = "";
857 const char *infoString = 0;
858 const char *mime_type;
860 time_t timer = time(0);
864 numNames = sizeof(httpResponseNames) / sizeof(httpResponseNames[0])
867 for (i = 0; i < numNames; i++) {
868 if (httpResponseNames[i].type == responseNum) {
869 responseString = httpResponseNames[i].name;
870 infoString = httpResponseNames[i].info;
874 /* error message is HTML */
875 mime_type = responseNum == HTTP_OK ?
876 config->found_mime_type : "text/html";
878 /* emit the current date */
879 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
881 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
882 "Date: %s\r\nConnection: close\r\n",
883 responseNum, responseString, mime_type, timeStr);
885 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
886 if (responseNum == HTTP_UNAUTHORIZED) {
887 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
891 if (responseNum == HTTP_MOVED_TEMPORARILY) {
892 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
893 config->found_moved_temporarily,
894 (config->query ? "?" : ""),
895 (config->query ? config->query : ""));
898 if (config->ContentLength != -1) { /* file */
899 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
900 len += sprintf(buf+len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
901 timeStr, "Content-length:", config->ContentLength);
906 len += sprintf(buf+len,
907 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
908 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
909 responseNum, responseString,
910 responseNum, responseString, infoString);
913 fprintf(stderr, "headers: '%s'\n", buf);
914 return full_write(config->accepted_socket, buf, len);
917 /****************************************************************************
919 > $Function: getLine()
921 * $Description: Read from the socket until an end of line char found.
923 * Characters are read one at a time until an eol sequence is found.
925 * $Return: (int) . . . . number of characters read. -1 if error.
927 ****************************************************************************/
928 static int getLine(void)
931 char *buf = config->buf;
933 while (read(config->accepted_socket, buf + count, 1) == 1) {
934 if (buf[count] == '\r') continue;
935 if (buf[count] == '\n') {
939 if (count < (MAX_MEMORY_BUFF-1)) /* check overflow */
942 if (count) return count;
946 #if ENABLE_FEATURE_HTTPD_CGI
947 /****************************************************************************
949 > $Function: sendCgi()
951 * $Description: Execute a CGI script and send it's stdout back
953 * Environment variables are set up and the script is invoked with pipes
954 * for stdin/stdout. If a post is being done the script is fed the POST
955 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
958 * (const char *) url . . . . . . The requested URL (with leading /).
959 * (int bodyLen) . . . . . . . . Length of the post body.
960 * (const char *cookie) . . . . . For set HTTP_COOKIE.
961 * (const char *content_type) . . For set CONTENT_TYPE.
964 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
968 ****************************************************************************/
969 static int sendCgi(const char *url,
970 const char *request, int bodyLen, const char *cookie,
971 const char *content_type)
973 int fromCgi[2]; /* pipe for reading data from CGI */
974 int toCgi[2]; /* pipe for sending data to CGI */
976 static char * argp[] = { 0, 0 };
982 size_t post_readed_size, post_readed_idx;
984 if (pipe(fromCgi) != 0)
986 if (pipe(toCgi) != 0)
996 char *purl = strdup(url);
997 char realpath_buff[MAXPATHLEN];
1005 dup2(inFd, 0); // replace stdin with the pipe
1006 dup2(outFd, 1); // replace stdout with the pipe
1008 dup2(outFd, 2); // replace stderr with the pipe
1015 close(config->accepted_socket);
1016 close(config->server_socket);
1022 while ((script = strchr(script + 1, '/')) != NULL) {
1023 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1027 if (is_directory(purl + 1, 1, &sb) == 0) {
1028 /* not directory, found script.cgi/PATH_INFO */
1032 *script = '/'; /* is directory, find next '/' */
1034 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1035 /* setenv1("PATH", getenv("PATH")); redundant */
1036 setenv1("REQUEST_METHOD", request);
1037 if (config->query) {
1038 char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
1040 sprintf(uri, "%s?%s", purl, config->query);
1041 setenv1("REQUEST_URI", uri);
1043 setenv1("REQUEST_URI", purl);
1046 *script = '\0'; /* cut off /PATH_INFO */
1047 /* SCRIPT_FILENAME required by PHP in CGI mode */
1048 if (!realpath(purl + 1, realpath_buff))
1049 goto error_execing_cgi;
1050 setenv1("SCRIPT_FILENAME", realpath_buff);
1051 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1052 setenv1("SCRIPT_NAME", purl);
1053 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1054 * QUERY_STRING: The information which follows the ? in the URL
1055 * which referenced this script. This is the query information.
1056 * It should not be decoded in any fashion. This variable
1057 * should always be set when there is query information,
1058 * regardless of command line decoding. */
1059 /* (Older versions of bbox seemed to do some decoding) */
1060 setenv1("QUERY_STRING", config->query);
1061 setenv1("SERVER_SOFTWARE", httpdVersion);
1062 putenv("SERVER_PROTOCOL=HTTP/1.0");
1063 putenv("GATEWAY_INTERFACE=CGI/1.1");
1064 setenv1("REMOTE_ADDR", config->rmt_ip_str);
1065 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1066 setenv_long("REMOTE_PORT", config->port);
1069 setenv_long("CONTENT_LENGTH", bodyLen);
1071 setenv1("HTTP_COOKIE", cookie);
1073 setenv1("CONTENT_TYPE", content_type);
1074 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1075 if (config->remoteuser) {
1076 setenv1("REMOTE_USER", config->remoteuser);
1077 putenv("AUTH_TYPE=Basic");
1080 if (config->referer)
1081 setenv1("HTTP_REFERER", config->referer);
1083 /* set execve argp[0] without path */
1084 argp[0] = strrchr(purl, '/') + 1;
1085 /* but script argp[0] must have absolute path and chdiring to this */
1086 script = strrchr(realpath_buff, '/');
1088 goto error_execing_cgi;
1090 if (chdir(realpath_buff) == 0) {
1091 // now run the program. If it fails,
1092 // use _exit() so no destructors
1093 // get called and make a mess.
1094 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1095 char *interpr = NULL;
1096 char *suffix = strrchr(purl, '.');
1100 for (cur = config->script_i; cur; cur = cur->next) {
1101 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1102 interpr = cur->after_colon;
1109 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1111 execv(interpr, argp);
1114 execv(realpath_buff, argp);
1117 /* send to stdout (even if we are not from inetd) */
1118 config->accepted_socket = 1;
1119 sendHeaders(HTTP_NOT_FOUND);
1123 /* parent process */
1125 post_readed_size = 0;
1126 post_readed_idx = 0;
1131 signal(SIGPIPE, SIG_IGN);
1142 FD_SET(inFd, &readSet);
1143 if (bodyLen > 0 || post_readed_size > 0) {
1144 FD_SET(outFd, &writeSet);
1145 nfound = outFd > inFd ? outFd : inFd;
1146 if (post_readed_size == 0) {
1147 FD_SET(config->accepted_socket, &readSet);
1148 if (nfound < config->accepted_socket)
1149 nfound = config->accepted_socket;
1151 /* Now wait on the set of sockets! */
1152 nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
1158 nfound = select(inFd + 1, &readSet, 0, 0, NULL);
1162 if (waitpid(pid, &status, WNOHANG) > 0) {
1164 if (DEBUG && WIFEXITED(status))
1165 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1166 if (DEBUG && WIFSIGNALED(status))
1167 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1170 } else if (post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1171 count = full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1173 post_readed_size -= count;
1174 post_readed_idx += count;
1175 if (post_readed_size == 0)
1176 post_readed_idx = 0;
1178 post_readed_size = post_readed_idx = bodyLen = 0; /* broken pipe to CGI */
1180 } else if (bodyLen > 0 && post_readed_size == 0 && FD_ISSET(config->accepted_socket, &readSet)) {
1181 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1182 count = safe_read(config->accepted_socket, wbuf, count);
1184 post_readed_size += count;
1187 bodyLen = 0; /* closed */
1190 if (FD_ISSET(inFd, &readSet)) {
1191 int s = config->accepted_socket;
1192 char *rbuf = config->buf;
1195 # define PIPESIZE 4096 /* amount of buffering in a pipe */
1197 # define PIPESIZE PIPE_BUF
1199 #if PIPESIZE >= MAX_MEMORY_BUFF
1200 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1203 /* There is something to read */
1204 count = safe_read(inFd, rbuf, PIPESIZE);
1210 /* check to see if the user script added headers */
1211 if (strncmp(rbuf, "HTTP/1.0 200 OK\r\n", 4) != 0) {
1212 full_write(s, "HTTP/1.0 200 OK\r\n", 17);
1214 /* Sometimes CGI is writing to pipe in small chunks
1215 * and we don't see Content-type (because the read
1216 * is too short) and we emit bogus "text/plain"!
1217 * Is it a bug or CGI *has to* write it in one piece? */
1218 if (strstr(rbuf, "ontent-") == 0) {
1219 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1223 if (full_write(s, rbuf, count) != count)
1227 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1233 #endif /* FEATURE_HTTPD_CGI */
1235 /****************************************************************************
1237 > $Function: sendFile()
1239 * $Description: Send a file response to a HTTP request
1242 * (const char *) url . . The URL requested.
1244 * $Return: (int) . . . . . . Always 0.
1246 ****************************************************************************/
1247 static int sendFile(const char *url)
1251 const char * const * table;
1252 const char * try_suffix;
1254 suffix = strrchr(url, '.');
1256 for (table = suffixTable; *table; table += 2)
1257 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1258 try_suffix += strlen(suffix);
1259 if (*try_suffix == 0 || *try_suffix == '.')
1262 /* also, if not found, set default as "application/octet-stream"; */
1263 config->found_mime_type = table[1];
1264 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1268 for (cur = config->mime_a; cur; cur = cur->next) {
1269 if (strcmp(cur->before_colon, suffix) == 0) {
1270 config->found_mime_type = cur->after_colon;
1275 #endif /* FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1278 fprintf(stderr, "sending file '%s' content-type: %s\n",
1279 url, config->found_mime_type);
1281 f = open(url, O_RDONLY);
1284 char *buf = config->buf;
1286 sendHeaders(HTTP_OK);
1287 /* TODO: sendfile() */
1288 while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1289 if (full_write(config->accepted_socket, buf, count) != count)
1295 bb_perror_msg("cannot open '%s'", url);
1296 sendHeaders(HTTP_NOT_FOUND);
1302 static int checkPermIP(void)
1306 /* This could stand some work */
1307 for (cur = config->ip_a_d; cur; cur = cur->next) {
1309 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1311 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1312 (unsigned char)(cur->ip >> 24),
1313 (unsigned char)(cur->ip >> 16),
1314 (unsigned char)(cur->ip >> 8),
1316 (unsigned char)(cur->mask >> 24),
1317 (unsigned char)(cur->mask >> 16),
1318 (unsigned char)(cur->mask >> 8),
1320 if ((config->rmt_ip & cur->mask) == cur->ip)
1321 return cur->allow_deny == 'A'; /* Allow/Deny */
1324 /* if unconfigured, return 1 - access from all */
1325 return !config->flg_deny_all;
1328 /****************************************************************************
1330 > $Function: checkPerm()
1332 * $Description: Check the permission file for access password protected.
1334 * If config file isn't present, everything is allowed.
1335 * Entries are of the form you can see example from header source
1338 * (const char *) path . . . . The file path.
1339 * (const char *) request . . . User information to validate.
1341 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1343 ****************************************************************************/
1345 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1346 static int checkPerm(const char *path, const char *request)
1352 const char *prev = NULL;
1354 /* This could stand some work */
1355 for (cur = config->auth; cur; cur = cur->next) {
1358 p0 = cur->before_colon;
1359 if (prev != NULL && strcmp(prev, p0) != 0)
1360 continue; /* find next identical */
1361 p = cur->after_colon;
1363 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1366 if (strncmp(p0, path, l) == 0
1367 && (l == 1 || path[l] == '/' || path[l] == '\0')
1370 /* path match found. Check request */
1371 /* for check next /path:user:password */
1373 u = strchr(request, ':');
1375 /* bad request, ':' required */
1379 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1383 if (strncmp(p, request, u-request) != 0) {
1384 /* user uncompared */
1387 pp = strchr(p, ':');
1388 if (pp && pp[1] == '$' && pp[2] == '1' &&
1389 pp[3] == '$' && pp[4]) {
1391 cipher = pw_encrypt(u+1, pp);
1392 if (strcmp(cipher, pp) == 0)
1393 goto set_remoteuser_var; /* Ok */
1399 if (strcmp(p, request) == 0) {
1401 config->remoteuser = strdup(request);
1402 if (config->remoteuser)
1403 config->remoteuser[(u - request)] = 0;
1410 return prev == NULL;
1413 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1415 /****************************************************************************
1417 > $Function: handle_sigalrm()
1419 * $Description: Handle timeouts
1421 ****************************************************************************/
1423 static void handle_sigalrm(int sig)
1425 sendHeaders(HTTP_REQUEST_TIMEOUT);
1426 config->alarm_signaled = sig;
1429 /****************************************************************************
1431 > $Function: handleIncoming()
1433 * $Description: Handle an incoming http request.
1435 ****************************************************************************/
1436 static void handleIncoming(void)
1438 char *buf = config->buf;
1445 #if ENABLE_FEATURE_HTTPD_CGI
1446 const char *prequest = request_GET;
1447 unsigned long length = 0;
1449 char *content_type = 0;
1454 struct sigaction sa;
1456 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1457 int credentials = -1; /* if not required this is Ok */
1460 sa.sa_handler = handle_sigalrm;
1461 sigemptyset(&sa.sa_mask);
1462 sa.sa_flags = 0; /* no SA_RESTART */
1463 sigaction(SIGALRM, &sa, NULL);
1468 (void) alarm(TIMEOUT);
1472 purl = strpbrk(buf, " \t");
1475 sendHeaders(HTTP_BAD_REQUEST);
1479 #if ENABLE_FEATURE_HTTPD_CGI
1480 if (strcasecmp(buf, prequest) != 0) {
1482 if (strcasecmp(buf, prequest) != 0) {
1483 sendHeaders(HTTP_NOT_IMPLEMENTED);
1488 if (strcasecmp(buf, request_GET) != 0) {
1489 sendHeaders(HTTP_NOT_IMPLEMENTED);
1494 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1496 if (count < 1 || buf[0] != '/') {
1497 /* Garbled request/URL */
1500 url = alloca(strlen(buf) + sizeof("/index.html"));
1502 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1506 /* extract url args if present */
1507 test = strchr(url, '?');
1508 config->query = NULL;
1511 config->query = test;
1514 test = decodeString(url, 0);
1517 if (test == url+1) {
1518 /* '/' or NUL is encoded */
1519 sendHeaders(HTTP_NOT_FOUND);
1523 /* algorithm stolen from libbb bb_simplify_path(),
1524 but don't strdup and reducing trailing slash and protect out root */
1528 /* skip duplicate (or initial) slash */
1533 /* skip extra '.' */
1534 if (test[1] == '/' || test[1] == 0) {
1537 /* '..': be careful */
1538 if (test[1] == '.' && (test[2] == '/' || test[2] == 0)) {
1541 /* protect out root */
1544 while (*--purl != '/') /* omit previous dir */;
1551 *++purl = '\0'; /* so keep last character */
1552 test = purl; /* end ptr */
1554 /* If URL is directory, adding '/' */
1555 if (test[-1] != '/') {
1556 if (is_directory(url + 1, 1, &sb)) {
1557 config->found_moved_temporarily = url;
1561 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1564 ip_allowed = checkPermIP();
1565 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1566 /* have path1/path2 */
1568 if (is_directory(url + 1, 1, &sb)) {
1569 /* may be having subdir config */
1570 parse_conf(url + 1, SUBDIR_PARSE);
1571 ip_allowed = checkPermIP();
1576 /* read until blank line for HTTP version specified, else parse immediate */
1584 fprintf(stderr, "header: '%s'\n", buf);
1586 #if ENABLE_FEATURE_HTTPD_CGI
1587 /* try and do our best to parse more lines */
1588 if ((STRNCASECMP(buf, "Content-length:") == 0)) {
1589 /* extra read only for POST */
1590 if (prequest != request_GET) {
1591 test = buf + sizeof("Content-length:")-1;
1592 if (!test[0]) goto bail_out;
1594 /* not using strtoul: it ignores leading munis! */
1595 length = strtol(test, &test, 10);
1596 /* length is "ulong", but we need to pass it to int later */
1597 /* so we check for negative or too large values in one go: */
1598 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1599 if (test[0] || errno || length > INT_MAX)
1602 } else if ((STRNCASECMP(buf, "Cookie:") == 0)) {
1603 cookie = strdup(skip_whitespace(buf + sizeof("Cookie:")-1));
1604 } else if ((STRNCASECMP(buf, "Content-Type:") == 0)) {
1605 content_type = strdup(skip_whitespace(buf + sizeof("Content-Type:")-1));
1606 } else if ((STRNCASECMP(buf, "Referer:") == 0)) {
1607 config->referer = strdup(skip_whitespace(buf + sizeof("Referer:")-1));
1611 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1612 if (STRNCASECMP(buf, "Authorization:") == 0) {
1613 /* We only allow Basic credentials.
1614 * It shows up as "Authorization: Basic <userid:password>" where
1615 * the userid:password is base64 encoded.
1617 test = skip_whitespace(buf + sizeof("Authorization:")-1);
1618 if (STRNCASECMP(test, "Basic") != 0)
1620 test += sizeof("Basic")-1;
1621 /* decodeBase64() skips whitespace itself */
1623 credentials = checkPerm(url, test);
1625 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1627 } /* while extra header reading */
1630 if (config->alarm_signaled)
1633 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1634 /* protect listing [/path]/httpd_conf or IP deny */
1635 #if ENABLE_FEATURE_HTTPD_CGI
1636 FORBIDDEN: /* protect listing /cgi-bin */
1638 sendHeaders(HTTP_FORBIDDEN);
1642 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1643 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1644 sendHeaders(HTTP_UNAUTHORIZED);
1649 if (config->found_moved_temporarily) {
1650 sendHeaders(HTTP_MOVED_TEMPORARILY);
1651 /* clear unforked memory flag */
1652 config->found_moved_temporarily = NULL;
1656 test = url + 1; /* skip first '/' */
1658 #if ENABLE_FEATURE_HTTPD_CGI
1659 if (strncmp(test, "cgi-bin", 7) == 0) {
1660 if (test[7] == '/' && test[8] == 0)
1661 goto FORBIDDEN; /* protect listing cgi-bin/ */
1662 sendCgi(url, prequest, length, cookie, content_type);
1665 if (prequest != request_GET) {
1666 sendHeaders(HTTP_NOT_IMPLEMENTED);
1669 #endif /* FEATURE_HTTPD_CGI */
1670 if (purl[-1] == '/')
1671 strcpy(purl, "index.html");
1672 if (stat(test, &sb) == 0) {
1673 /* It's a dir URL and there is index.html */
1674 config->ContentLength = sb.st_size;
1675 config->last_mod = sb.st_mtime;
1677 #if ENABLE_FEATURE_HTTPD_CGI
1678 else if (purl[-1] == '/') {
1679 /* It's a dir URL and there is no index.html
1680 * Try cgi-bin/index.cgi */
1681 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1683 config->query = url;
1684 sendCgi("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1688 #endif /* FEATURE_HTTPD_CGI */
1690 config->ContentLength = -1;
1696 fprintf(stderr, "closing socket\n\n");
1697 #if ENABLE_FEATURE_HTTPD_CGI
1700 free(config->referer);
1701 config->referer = NULL;
1702 # if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1703 free(config->remoteuser);
1704 config->remoteuser = NULL;
1707 shutdown(config->accepted_socket, SHUT_WR);
1709 /* Properly wait for remote to closed */
1711 FD_SET(config->accepted_socket, &s_fd);
1716 retval = select(config->accepted_socket + 1, &s_fd, NULL, NULL, &tv);
1717 } while (retval > 0 && read(config->accepted_socket, buf, sizeof(config->buf) > 0));
1719 shutdown(config->accepted_socket, SHUT_RD);
1720 /* In inetd case, we close fd 1 (stdout) here. We will exit soon anyway */
1721 close(config->accepted_socket);
1724 /****************************************************************************
1726 > $Function: miniHttpd()
1728 * $Description: The main http server function.
1730 * Given an open socket fildes, listen for new connections and farm out
1731 * the processing as a forked process.
1734 * (int) server. . . The server socket fildes.
1736 * $Return: (int) . . . . Always 0.
1738 ****************************************************************************/
1739 static int miniHttpd(int server)
1741 fd_set readfd, portfd;
1744 FD_SET(server, &portfd);
1746 /* copy the ports we are watching to the readfd set */
1749 socklen_t fromAddrLen;
1750 struct sockaddr_in fromAddr;
1752 /* Now wait INDEFINITELY on the set of sockets! */
1754 if (select(server + 1, &readfd, 0, 0, 0) <= 0)
1756 if (!FD_ISSET(server, &readfd))
1758 fromAddrLen = sizeof(fromAddr);
1759 s = accept(server, (struct sockaddr *)&fromAddr, &fromAddrLen);
1762 config->accepted_socket = s;
1763 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1764 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1765 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1766 (unsigned char)(config->rmt_ip >> 24),
1767 (unsigned char)(config->rmt_ip >> 16),
1768 (unsigned char)(config->rmt_ip >> 8),
1769 config->rmt_ip & 0xff);
1770 config->port = ntohs(fromAddr.sin_port);
1772 bb_error_msg("connection from IP=%s, port %u",
1773 config->rmt_ip_str, config->port);
1775 #endif /* FEATURE_HTTPD_CGI */
1777 /* set the KEEPALIVE option to cull dead connections */
1779 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
1781 if (DEBUG || fork() == 0) {
1783 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1784 /* protect reload config, may be confuse checking */
1785 signal(SIGHUP, SIG_IGN);
1797 static int miniHttpd_inetd(void)
1799 struct sockaddr_in fromAddrLen;
1800 socklen_t sinlen = sizeof(struct sockaddr_in);
1802 getpeername(0, (struct sockaddr *)&fromAddrLen, &sinlen);
1803 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1804 #if ENABLE_FEATURE_HTTPD_CGI
1805 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1806 (unsigned char)(config->rmt_ip >> 24),
1807 (unsigned char)(config->rmt_ip >> 16),
1808 (unsigned char)(config->rmt_ip >> 8),
1809 config->rmt_ip & 0xff);
1811 config->port = ntohs(fromAddrLen.sin_port);
1816 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1817 static void sighup_handler(int sig)
1820 struct sigaction sa;
1822 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1823 sa.sa_handler = sighup_handler;
1824 sigemptyset(&sa.sa_mask);
1825 sa.sa_flags = SA_RESTART;
1826 sigaction(SIGHUP, &sa, NULL);
1831 c_opt_config_file = 0,
1834 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1835 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1836 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1837 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1841 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1842 OPT_DECODE_URL = 1 << d_opt_decode_url,
1843 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1844 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1845 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1846 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1847 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1848 OPT_PORT = 1 << p_opt_port,
1849 OPT_INETD = 1 << p_opt_inetd,
1850 OPT_FOREGROUND = 1 << p_opt_foreground,
1853 static const char httpd_opts[] = "c:d:h:"
1854 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1855 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1856 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1857 USE_FEATURE_HTTPD_SETUID("u:")
1861 int httpd_main(int argc, char *argv[])
1864 const char *home_httpd = home;
1865 char *url_for_decode;
1866 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1868 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1869 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1870 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1872 #if ENABLE_LOCALE_SUPPORT
1873 /* Undo busybox.c: we want to speak English in http (dates etc) */
1874 setlocale(LC_TIME, "C");
1877 config = xzalloc(sizeof(*config));
1878 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1879 config->realm = "Web Server Authentication";
1882 config->ContentLength = -1;
1884 opt = getopt32(argc, argv, httpd_opts,
1885 &(config->configFile), &url_for_decode, &home_httpd
1886 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1887 USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
1888 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1889 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1892 if (opt & OPT_DECODE_URL) {
1893 printf("%s", decodeString(url_for_decode, 1));
1896 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1897 if (opt & OPT_ENCODE_URL) {
1898 printf("%s", encodeString(url_for_encode));
1902 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1903 if (opt & OPT_MD5) {
1904 puts(pw_encrypt(pass, "$1$"));
1909 config->port = xatou16(s_port);
1911 #if ENABLE_FEATURE_HTTPD_SETUID
1912 if (opt & OPT_SETUID) {
1914 // FIXME: what the default group should be?
1916 ugid.uid = bb_strtoul(s_ugid, &e, 0);
1919 ugid.gid = bb_strtoul(e, NULL, 0);
1923 if (!uidgid_get(&ugid, s_ugid))
1924 bb_error_msg_and_die("unrecognized user[:group] "
1925 "name '%s'", s_ugid);
1931 if (!(opt & OPT_INETD)) {
1932 config->server_socket = openServer();
1933 #if ENABLE_FEATURE_HTTPD_SETUID
1934 /* drop privileges */
1935 if (opt & OPT_SETUID) {
1936 if (ugid.gid != (gid_t)-1) {
1937 if (setgroups(1, &ugid.gid) == -1)
1938 bb_perror_msg_and_die("setgroups");
1946 #if ENABLE_FEATURE_HTTPD_CGI
1948 char *p = getenv("PATH");
1949 p = xstrdup(p); /* if gets NULL, returns NULL */
1953 if (!(opt & OPT_INETD))
1954 setenv_long("SERVER_PORT", config->port);
1958 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1961 parse_conf(default_path_httpd_conf, FIRST_PARSE);
1964 if (opt & OPT_INETD)
1965 return miniHttpd_inetd();
1967 if (!(opt & OPT_FOREGROUND))
1968 xdaemon(1, 0); /* don't change current directory */
1969 return miniHttpd(config->server_socket);