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.
27 * The server can also be invoked as a url arg decoder and html text encoder
29 * foo=`httpd -d $foo` # decode "Hello%20World" as "Hello World"
30 * bar=`httpd -e "<Hello World>"` # encode as "<Hello World>"
31 * Note that url encoding for arguments is not the same as html encoding for
32 * presentation. -d decodes a url-encoded argument while -e encodes in html
35 * httpd.conf has the following format:
37 * A:172.20. # Allow address from 172.20.0.0/16
38 * A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
39 * A:10.0.0.0/255.255.255.128 # Allow any address that previous set
40 * A:127.0.0.1 # Allow local loopback connections
41 * D:* # Deny from other IP connections
42 * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
43 * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
44 * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
45 * .au:audio/basic # additional mime type for audio.au files
46 * *.php:/path/php # running cgi.php scripts through an interpreter
48 * A/D may be as a/d or allow/deny - first char case insensitive
49 * Deny IP rules take precedence over allow rules.
52 * The Deny/Allow IP logic:
54 * - Default is to allow all. No addresses are denied unless
55 * denied with a D: rule.
56 * - Order of Deny/Allow rules is significant
57 * - Deny rules take precedence over allow rules.
58 * - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
60 * - Specification of Allow all (A:*) is a no-op
63 * 1. Allow only specified addresses
64 * A:172.20 # Allow any address that begins with 172.20.
65 * A:10.10. # Allow any address that begins with 10.10.
66 * A:127.0.0.1 # Allow local loopback connections
67 * D:* # Deny from other IP connections
69 * 2. Only deny specified addresses
70 * D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
71 * D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
72 * A:* # (optional line added for clarity)
74 * If a sub directory contains a config file it is parsed and merged with
75 * any existing settings as if it was appended to the original configuration.
77 * subdir paths are relative to the containing subdir and thus cannot
78 * affect the parent rules.
80 * Note that since the sub dir is parsed in the forked thread servicing the
81 * subdir http request, any merge is discarded when the process exits. As a
82 * result, the subdir settings only have a lifetime of a single request.
85 * If -c is not set, an attempt will be made to open the default
86 * root configuration file. If -c is set and the file is not found, the
87 * server exits with an error.
95 static const char httpdVersion[] = "busybox httpd/1.35 6-Oct-2004";
96 static const char default_path_httpd_conf[] = "/etc";
97 static const char httpd_conf[] = "httpd.conf";
98 static const char home[] = "./";
102 // Note: busybox xfuncs are not used because we want the server to keep running
103 // if something bad happens due to a malformed user request.
104 // As a result, all memory allocation after daemonize
105 // is checked rigorously
113 #define MAX_MEMORY_BUFF 8192 /* IO buffer */
115 typedef struct HT_ACCESS {
117 struct HT_ACCESS *next;
118 char before_colon[1]; /* really bigger, must last */
121 typedef struct HT_ACCESS_IP {
125 struct HT_ACCESS_IP *next;
129 char buf[MAX_MEMORY_BUFF];
131 USE_FEATURE_HTTPD_BASIC_AUTH(const char *realm;)
132 USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
136 USE_FEATURE_HTTPD_CGI(char *referer;)
138 const char *configFile;
141 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
142 char rmt_ip_str[16]; /* for set env REMOTE_ADDR */
144 unsigned port; /* server initial port and for
145 set env REMOTE_PORT */
146 const char *found_mime_type;
147 const char *found_moved_temporarily;
149 off_t ContentLength; /* -1 - unknown */
152 Htaccess_IP *ip_a_d; /* config allow/deny lines */
154 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
155 Htaccess *auth; /* config user:password lines */
157 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
158 Htaccess *mime_a; /* config mime types */
163 volatile int alarm_signaled;
165 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
166 Htaccess *script_i; /* config script interpreters */
170 static HttpdConfig *config;
172 static const char request_GET[] = "GET"; /* size algorithmic optimize */
174 static const char* const suffixTable [] = {
175 /* Warning: shorted equivalent suffix in one line must be first */
176 ".htm.html", "text/html",
177 ".jpg.jpeg", "image/jpeg",
180 ".txt.h.c.cc.cpp", "text/plain",
183 ".avi", "video/x-msvideo",
184 ".qt.mov", "video/quicktime",
185 ".mpe.mpeg", "video/mpeg",
186 ".mid.midi", "audio/midi",
187 ".mp3", "audio/mpeg",
188 #if 0 /* unpopular */
189 ".au", "audio/basic",
190 ".pac", "application/x-ns-proxy-autoconfig",
191 ".vrml.wrl", "model/vrml",
193 0, "application/octet-stream" /* default */
198 HTTP_MOVED_TEMPORARILY = 302,
199 HTTP_BAD_REQUEST = 400, /* malformed syntax */
200 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
201 HTTP_NOT_FOUND = 404,
202 HTTP_FORBIDDEN = 403,
203 HTTP_REQUEST_TIMEOUT = 408,
204 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
205 HTTP_INTERNAL_SERVER_ERROR = 500,
206 #if 0 /* future use */
208 HTTP_SWITCHING_PROTOCOLS = 101,
211 HTTP_NON_AUTHORITATIVE_INFO = 203,
212 HTTP_NO_CONTENT = 204,
213 HTTP_MULTIPLE_CHOICES = 300,
214 HTTP_MOVED_PERMANENTLY = 301,
215 HTTP_NOT_MODIFIED = 304,
216 HTTP_PAYMENT_REQUIRED = 402,
217 HTTP_BAD_GATEWAY = 502,
218 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
219 HTTP_RESPONSE_SETSIZE = 0xffffffff
224 HttpResponseNum type;
229 static const HttpEnumString httpResponseNames[] = {
230 { HTTP_OK, "OK", NULL },
231 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
232 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
233 "No request appeared within a reasonable time period." },
234 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
235 "The requested method is not recognized by this server." },
236 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
237 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
239 { HTTP_NOT_FOUND, "Not Found",
240 "The requested URL was not found on this server." },
241 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
242 { HTTP_FORBIDDEN, "Forbidden", "" },
243 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
244 "Internal Server Error" },
245 #if 0 /* not implemented */
246 { HTTP_CREATED, "Created" },
247 { HTTP_ACCEPTED, "Accepted" },
248 { HTTP_NO_CONTENT, "No Content" },
249 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
250 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
251 { HTTP_NOT_MODIFIED, "Not Modified" },
252 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
253 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
258 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
261 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
264 static int scan_ip(const char **ep, unsigned int *ip, unsigned char endc)
271 for (j = 0; j < 4; j++) {
274 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
277 while (*p >= '0' && *p <= '9') {
286 if (*p != '/' && *p != 0)
288 *ip = ((*ip) << 8) | octet;
301 static int scan_ip_mask(const char *ipm, unsigned int *ip, unsigned int *mask)
306 i = scan_ip(&ipm, ip, '/');
314 if (*p < '0' || *p > '9') {
316 i = scan_ip(&ipm, mask, 0);
338 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
339 static void free_config_lines(Htaccess **pprev)
341 Htaccess *prev = *pprev;
344 Htaccess *cur = prev;
354 #define FIRST_PARSE 0
355 #define SUBDIR_PARSE 1
356 #define SIGNALED_PARSE 2
357 #define FIND_FROM_HTTPD_ROOT 3
358 /****************************************************************************
360 > $Function: parse_conf()
362 * $Description: parse configuration file into in-memory linked list.
364 * The first non-white character is examined to determine if the config line
365 * is one of the following:
366 * .ext:mime/type # new mime type not compiled into httpd
367 * [adAD]:from # ip address allow/deny, * for wildcard
368 * /path:user:pass # username/password
370 * Any previous IP rules are discarded.
371 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
372 * are also discarded. That is, previous settings are retained if flag is
376 * (const char *) path . . null for ip address checks, path for password
378 * (int) flag . . . . . . the source of the parse request.
382 ****************************************************************************/
383 static void parse_conf(const char *path, int flag)
386 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
387 Htaccess *prev, *cur;
388 #elif ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
392 const char *cf = config->configFile;
397 /* free previous ip setup if present */
398 Htaccess_IP *pip = config->ip_a_d;
401 Htaccess_IP *cur_ipl = pip;
406 config->ip_a_d = NULL;
408 config->flg_deny_all = 0;
410 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
411 /* retain previous auth and mime config only for subdir parse */
412 if (flag != SUBDIR_PARSE) {
413 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
414 free_config_lines(&config->auth);
416 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
417 free_config_lines(&config->mime_a);
419 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
420 free_config_lines(&config->script_i);
425 if (flag == SUBDIR_PARSE || cf == NULL) {
426 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
428 if (flag == FIRST_PARSE)
429 bb_error_msg_and_die(bb_msg_memory_exhausted);
432 sprintf((char *)cf, "%s/%s", path, httpd_conf);
435 while ((f = fopen(cf, "r")) == NULL) {
436 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
437 /* config file not found, no changes to config */
440 if (config->configFile && flag == FIRST_PARSE) /* if -c option given */
441 bb_perror_msg_and_die("%s", cf);
442 flag = FIND_FROM_HTTPD_ROOT;
446 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
449 /* This could stand some work */
450 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
452 for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
455 if (*p0 == ':' && c == NULL)
461 /* test for empty or strange line */
462 if (c == NULL || *c == 0)
469 /* memorize deny all */
470 config->flg_deny_all++;
472 /* skip default other "word:*" config lines */
478 else if (*p0 != 'D' && *p0 != 'A'
479 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
482 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
485 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
490 if (*p0 == 'A' || *p0 == 'D') {
491 /* storing current config IP line */
492 pip = calloc(1, sizeof(Htaccess_IP));
494 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
495 /* syntax IP{/mask} error detected, protect all */
499 pip->allow_deny = *p0;
501 /* Deny:form_IP move top */
502 pip->next = config->ip_a_d;
503 config->ip_a_d = pip;
505 /* add to bottom A:form_IP config line */
506 Htaccess_IP *prev_IP = config->ip_a_d;
508 if (prev_IP == NULL) {
509 config->ip_a_d = pip;
511 while (prev_IP->next)
512 prev_IP = prev_IP->next;
519 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
521 /* make full path from httpd root / curent_path / config_line_path */
522 cf = flag == SUBDIR_PARSE ? path : "";
523 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
527 sprintf(p0, "/%s%s", cf, buf);
529 /* another call bb_simplify_path */
534 if (*cf == '/') { /* skip duplicate (or initial) slash */
536 } else if (*cf == '.') {
537 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
539 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
542 while (*--p != '/') /* omit previous dir */;
551 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
552 ++p; /* so keep last character */
555 sprintf(p0, "%s:%s", p0, c);
559 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
560 /* storing current config line */
561 cur = calloc(1, sizeof(Htaccess) + strlen(p0));
563 cf = strcpy(cur->before_colon, p0);
566 cur->after_colon = c;
567 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
569 /* config .mime line move top for overwrite previous */
570 cur->next = config->mime_a;
571 config->mime_a = cur;
575 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
576 if (*cf == '*' && cf[1] == '.') {
577 /* config script interpreter line move top for overwrite previous */
578 cur->next = config->script_i;
579 config->script_i = cur;
583 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
587 config->auth = prev = cur;
589 /* sort path, if current lenght eq or bigger then move up */
590 Htaccess *prev_hti = config->auth;
591 size_t l = strlen(cf);
594 for (hti = prev_hti; hti; hti = hti->next) {
595 if (l >= strlen(hti->before_colon)) {
596 /* insert before hti */
598 if (prev_hti != hti) {
599 prev_hti->next = cur;
607 prev_hti = prev_hti->next;
609 if (!hti) { /* not inserted, add to bottom */
621 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
622 /****************************************************************************
624 > $Function: encodeString()
626 * $Description: Given a string, html encode special characters.
627 * This is used for the -e command line option to provide an easy way
628 * for scripts to encode result data without confusing browsers. The
629 * returned string pointer is memory allocated by malloc().
632 * (const char *) string . . The first string to encode.
634 * $Return: (char *) . . . .. . . A pointer to the encoded string.
636 * $Errors: Returns a null string ("") if memory is not available.
638 ****************************************************************************/
639 static char *encodeString(const char *string)
641 /* take the simple route and encode everything */
642 /* could possibly scan once to get length. */
643 int len = strlen(string);
644 char *out = malloc(len * 6 + 1);
649 while ((ch = *string++)) {
650 // very simple check for what to encode
651 if (isalnum(ch)) *p++ = ch;
652 else p += sprintf(p, "&#%d;", (unsigned char) ch);
657 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
659 /****************************************************************************
661 > $Function: decodeString()
663 * $Description: Given a URL encoded string, convert it to plain ascii.
664 * Since decoding always makes strings smaller, the decode is done in-place.
665 * Thus, callers should strdup() the argument if they do not want the
666 * argument modified. The return is the original pointer, allowing this
667 * function to be easily used as arguments to other functions.
670 * (char *) string . . . The first string to decode.
671 * (int) flag . . . 1 if require decode '+' as ' ' for CGI
673 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
677 ****************************************************************************/
678 static char *decodeString(char *orig, int flag_plus_to_space)
680 /* note that decoded string is always shorter than original */
685 if (*ptr == '+' && flag_plus_to_space) { *string++ = ' '; ptr++; }
686 else if (*ptr != '%') *string++ = *ptr++;
688 unsigned int value1, value2;
691 if (sscanf(ptr, "%1X", &value1) != 1 ||
692 sscanf(ptr+1, "%1X", &value2) != 1) {
693 if (!flag_plus_to_space)
697 value1 = value1 * 16 + value2;
698 if (value1 == '/' || value1 == 0)
710 #if ENABLE_FEATURE_HTTPD_CGI
711 /****************************************************************************
713 ****************************************************************************/
714 static void setenv1(const char *name, const char *value)
718 setenv(name, value, 1);
720 static void setenv_long(const char *name, long value)
722 char buf[sizeof(value)*3 + 1];
723 sprintf(buf, "%ld", value);
724 setenv(name, buf, 1);
728 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
729 /****************************************************************************
731 > $Function: decodeBase64()
733 > $Description: Decode a base 64 data stream as per rfc1521.
734 * Note that the rfc states that none base64 chars are to be ignored.
735 * Since the decode always results in a shorter size than the input, it is
736 * OK to pass the input arg as an output arg.
739 * (char *) Data . . . . A pointer to a base64 encoded string.
740 * Where to place the decoded data.
746 ****************************************************************************/
747 static void decodeBase64(char *Data)
750 const unsigned char *in = (const unsigned char *)Data;
751 // The decoded size will be at most 3/4 the size of the encoded
752 unsigned long ch = 0;
758 if (t >= '0' && t <= '9')
760 else if (t >= 'A' && t <= 'Z')
762 else if (t >= 'a' && t <= 'z')
776 *Data++ = (char) (ch >> 16);
777 *Data++ = (char) (ch >> 8);
787 /****************************************************************************
789 > $Function: openServer()
791 * $Description: create a listen server socket on the designated port.
793 * $Return: (int) . . . A connection socket. -1 for errors.
797 ****************************************************************************/
798 static int openServer(void)
800 struct sockaddr_in lsocket;
804 /* create the socket right now */
805 /* inet_addr() returns a value that is already in network order */
806 memset(&lsocket, 0, sizeof(lsocket));
807 lsocket.sin_family = AF_INET;
808 lsocket.sin_addr.s_addr = INADDR_ANY;
809 lsocket.sin_port = htons(config->port);
810 fd = xsocket(AF_INET, SOCK_STREAM, 0);
811 /* tell the OS it's OK to reuse a previous address even though */
812 /* it may still be in a close down state. Allows bind to succeed. */
814 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on));
816 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
818 xbind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket));
820 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
824 /****************************************************************************
826 > $Function: sendHeaders()
828 * $Description: Create and send HTTP response headers.
829 * The arguments are combined and sent as one write operation. Note that
830 * IE will puke big-time if the headers are not sent in one packet and the
831 * second packet is delayed for any reason.
834 * (HttpResponseNum) responseNum . . . The result code to send.
836 * $Return: (int) . . . . writing errors
838 ****************************************************************************/
839 static int sendHeaders(HttpResponseNum responseNum)
841 char *buf = config->buf;
842 const char *responseString = "";
843 const char *infoString = 0;
844 const char *mime_type;
846 time_t timer = time(0);
851 i < (sizeof(httpResponseNames)/sizeof(httpResponseNames[0])); i++) {
852 if (httpResponseNames[i].type == responseNum) {
853 responseString = httpResponseNames[i].name;
854 infoString = httpResponseNames[i].info;
858 /* error message is HTML */
859 mime_type = responseNum == HTTP_OK ?
860 config->found_mime_type : "text/html";
862 /* emit the current date */
863 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
865 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
866 "Date: %s\r\nConnection: close\r\n",
867 responseNum, responseString, mime_type, timeStr);
869 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
870 if (responseNum == HTTP_UNAUTHORIZED) {
871 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
875 if (responseNum == HTTP_MOVED_TEMPORARILY) {
876 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
877 config->found_moved_temporarily,
878 (config->query ? "?" : ""),
879 (config->query ? config->query : ""));
882 if (config->ContentLength != -1) { /* file */
883 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
884 len += sprintf(buf+len, "Last-Modified: %s\r\n%s %"OFF_FMT"\r\n",
885 timeStr, "Content-length:", (off_t) config->ContentLength);
890 len += sprintf(buf+len,
891 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
892 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
893 responseNum, responseString,
894 responseNum, responseString, infoString);
897 fprintf(stderr, "headers: '%s'\n", buf);
899 return full_write(config->accepted_socket, buf, len);
902 /****************************************************************************
904 > $Function: getLine()
906 * $Description: Read from the socket until an end of line char found.
908 * Characters are read one at a time until an eol sequence is found.
910 * $Return: (int) . . . . number of characters read. -1 if error.
912 ****************************************************************************/
913 static int getLine(void)
916 char *buf = config->buf;
918 while (read(config->accepted_socket, buf + count, 1) == 1) {
919 if (buf[count] == '\r') continue;
920 if (buf[count] == '\n') {
924 if (count < (MAX_MEMORY_BUFF-1)) /* check overflow */
927 if (count) return count;
931 #if ENABLE_FEATURE_HTTPD_CGI
932 /****************************************************************************
934 > $Function: sendCgi()
936 * $Description: Execute a CGI script and send it's stdout back
938 * Environment variables are set up and the script is invoked with pipes
939 * for stdin/stdout. If a post is being done the script is fed the POST
940 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
943 * (const char *) url . . . . . . The requested URL (with leading /).
944 * (int bodyLen) . . . . . . . . Length of the post body.
945 * (const char *cookie) . . . . . For set HTTP_COOKIE.
946 * (const char *content_type) . . For set CONTENT_TYPE.
949 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
953 ****************************************************************************/
954 static int sendCgi(const char *url,
955 const char *request, int bodyLen, const char *cookie,
956 const char *content_type)
958 int fromCgi[2]; /* pipe for reading data from CGI */
959 int toCgi[2]; /* pipe for sending data to CGI */
961 static char * argp[] = { 0, 0 };
967 if (pipe(fromCgi) != 0)
969 if (pipe(toCgi) != 0)
979 char *purl = strdup(url);
980 char realpath_buff[MAXPATHLEN];
988 dup2(inFd, 0); // replace stdin with the pipe
989 dup2(outFd, 1); // replace stdout with the pipe
991 dup2(outFd, 2); // replace stderr with the pipe
998 close(config->accepted_socket);
999 close(config->server_socket);
1005 while ((script = strchr(script + 1, '/')) != NULL) {
1006 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1010 if (is_directory(purl + 1, 1, &sb) == 0) {
1011 /* not directory, found script.cgi/PATH_INFO */
1015 *script = '/'; /* is directory, find next '/' */
1017 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1018 /* setenv1("PATH", getenv("PATH")); redundant */
1019 setenv1("REQUEST_METHOD", request);
1020 if (config->query) {
1021 char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
1023 sprintf(uri, "%s?%s", purl, config->query);
1024 setenv1("REQUEST_URI", uri);
1026 setenv1("REQUEST_URI", purl);
1029 *script = '\0'; /* reduce /PATH_INFO */
1030 /* SCRIPT_FILENAME required by PHP in CGI mode */
1031 if (!realpath(purl + 1, realpath_buff))
1032 goto error_execing_cgi;
1033 setenv1("SCRIPT_FILENAME", realpath_buff);
1034 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1035 setenv1("SCRIPT_NAME", purl);
1036 setenv1("QUERY_STRING", config->query);
1037 setenv1("SERVER_SOFTWARE", httpdVersion);
1038 putenv("SERVER_PROTOCOL=HTTP/1.0");
1039 putenv("GATEWAY_INTERFACE=CGI/1.1");
1040 setenv1("REMOTE_ADDR", config->rmt_ip_str);
1041 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1042 setenv_long("REMOTE_PORT", config->port);
1045 setenv_long("CONTENT_LENGTH", bodyLen);
1047 setenv1("HTTP_COOKIE", cookie);
1049 setenv1("CONTENT_TYPE", content_type);
1050 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1051 if (config->remoteuser) {
1052 setenv1("REMOTE_USER", config->remoteuser);
1053 putenv("AUTH_TYPE=Basic");
1056 if (config->referer)
1057 setenv1("HTTP_REFERER", config->referer);
1059 /* set execve argp[0] without path */
1060 argp[0] = strrchr(purl, '/') + 1;
1061 /* but script argp[0] must have absolute path and chdiring to this */
1062 script = strrchr(realpath_buff, '/');
1064 goto error_execing_cgi;
1066 if (chdir(realpath_buff) == 0) {
1067 // now run the program. If it fails,
1068 // use _exit() so no destructors
1069 // get called and make a mess.
1070 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1071 char *interpr = NULL;
1072 char *suffix = strrchr(purl, '.');
1076 for (cur = config->script_i; cur; cur = cur->next) {
1077 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1078 interpr = cur->after_colon;
1085 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1087 execv(interpr, argp);
1090 execv(realpath_buff, argp);
1093 /* send to stdout (even if we are not from inetd) */
1094 config->accepted_socket = 1;
1095 sendHeaders(HTTP_NOT_FOUND);
1102 /* parent process */
1104 size_t post_readed_size = 0, post_readed_idx = 0;
1110 signal(SIGPIPE, SIG_IGN);
1121 FD_SET(inFd, &readSet);
1122 if (bodyLen > 0 || post_readed_size > 0) {
1123 FD_SET(outFd, &writeSet);
1124 nfound = outFd > inFd ? outFd : inFd;
1125 if (post_readed_size == 0) {
1126 FD_SET(config->accepted_socket, &readSet);
1127 if (nfound < config->accepted_socket)
1128 nfound = config->accepted_socket;
1130 /* Now wait on the set of sockets! */
1131 nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
1137 nfound = select(inFd + 1, &readSet, 0, 0, NULL);
1141 if (waitpid(pid, &status, WNOHANG) > 0) {
1143 if (DEBUG && WIFEXITED(status))
1144 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1145 if (DEBUG && WIFSIGNALED(status))
1146 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1149 } else if (post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1150 count = full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1152 post_readed_size -= count;
1153 post_readed_idx += count;
1154 if (post_readed_size == 0)
1155 post_readed_idx = 0;
1157 post_readed_size = post_readed_idx = bodyLen = 0; /* broken pipe to CGI */
1159 } else if (bodyLen > 0 && post_readed_size == 0 && FD_ISSET(config->accepted_socket, &readSet)) {
1160 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1161 count = safe_read(config->accepted_socket, wbuf, count);
1163 post_readed_size += count;
1166 bodyLen = 0; /* closed */
1169 if (FD_ISSET(inFd, &readSet)) {
1170 int s = config->accepted_socket;
1171 char *rbuf = config->buf;
1174 # define PIPESIZE 4096 /* amount of buffering in a pipe */
1176 # define PIPESIZE PIPE_BUF
1178 #if PIPESIZE >= MAX_MEMORY_BUFF
1179 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1182 // There is something to read
1183 count = safe_read(inFd, rbuf, PIPESIZE);
1189 /* check to see if the user script added headers */
1190 if (strncmp(rbuf, "HTTP/1.0 200 OK\r\n", 4) != 0) {
1191 full_write(s, "HTTP/1.0 200 OK\r\n", 17);
1193 if (strstr(rbuf, "ontent-") == 0) {
1194 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1198 if (full_write(s, rbuf, count) != count)
1202 fprintf(stderr, "cgi read %d bytes\n", count);
1209 #endif /* FEATURE_HTTPD_CGI */
1211 /****************************************************************************
1213 > $Function: sendFile()
1215 * $Description: Send a file response to a HTTP request
1218 * (const char *) url . . The URL requested.
1220 * $Return: (int) . . . . . . Always 0.
1222 ****************************************************************************/
1223 static int sendFile(const char *url)
1227 const char * const * table;
1228 const char * try_suffix;
1230 suffix = strrchr(url, '.');
1232 for (table = suffixTable; *table; table += 2)
1233 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1234 try_suffix += strlen(suffix);
1235 if (*try_suffix == 0 || *try_suffix == '.')
1238 /* also, if not found, set default as "application/octet-stream"; */
1239 config->found_mime_type = table[1];
1240 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1244 for (cur = config->mime_a; cur; cur = cur->next) {
1245 if (strcmp(cur->before_colon, suffix) == 0) {
1246 config->found_mime_type = cur->after_colon;
1251 #endif /* FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1254 fprintf(stderr, "sending file '%s' content-type: %s\n",
1255 url, config->found_mime_type);
1257 f = open(url, O_RDONLY);
1260 char *buf = config->buf;
1262 sendHeaders(HTTP_OK);
1263 /* TODO: sendfile() */
1264 while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1265 if (full_write(config->accepted_socket, buf, count) != count)
1271 bb_perror_msg("cannot open '%s'", url);
1272 sendHeaders(HTTP_NOT_FOUND);
1278 static int checkPermIP(void)
1282 /* This could stand some work */
1283 for (cur = config->ip_a_d; cur; cur = cur->next) {
1285 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1287 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1288 (unsigned char)(cur->ip >> 24),
1289 (unsigned char)(cur->ip >> 16),
1290 (unsigned char)(cur->ip >> 8),
1292 (unsigned char)(cur->mask >> 24),
1293 (unsigned char)(cur->mask >> 16),
1294 (unsigned char)(cur->mask >> 8),
1296 if ((config->rmt_ip & cur->mask) == cur->ip)
1297 return cur->allow_deny == 'A'; /* Allow/Deny */
1300 /* if unconfigured, return 1 - access from all */
1301 return !config->flg_deny_all;
1304 /****************************************************************************
1306 > $Function: checkPerm()
1308 * $Description: Check the permission file for access password protected.
1310 * If config file isn't present, everything is allowed.
1311 * Entries are of the form you can see example from header source
1314 * (const char *) path . . . . The file path.
1315 * (const char *) request . . . User information to validate.
1317 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1319 ****************************************************************************/
1321 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1322 static int checkPerm(const char *path, const char *request)
1328 const char *prev = NULL;
1330 /* This could stand some work */
1331 for (cur = config->auth; cur; cur = cur->next) {
1334 p0 = cur->before_colon;
1335 if (prev != NULL && strcmp(prev, p0) != 0)
1336 continue; /* find next identical */
1337 p = cur->after_colon;
1339 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1342 if (strncmp(p0, path, l) == 0
1343 && (l == 1 || path[l] == '/' || path[l] == '\0')
1346 /* path match found. Check request */
1347 /* for check next /path:user:password */
1349 u = strchr(request, ':');
1351 /* bad request, ':' required */
1355 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1359 if (strncmp(p, request, u-request) != 0) {
1360 /* user uncompared */
1363 pp = strchr(p, ':');
1364 if (pp && pp[1] == '$' && pp[2] == '1' &&
1365 pp[3] == '$' && pp[4]) {
1367 cipher = pw_encrypt(u+1, pp);
1368 if (strcmp(cipher, pp) == 0)
1369 goto set_remoteuser_var; /* Ok */
1375 if (strcmp(p, request) == 0) {
1377 config->remoteuser = strdup(request);
1378 if (config->remoteuser)
1379 config->remoteuser[(u - request)] = 0;
1386 return prev == NULL;
1389 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1391 /****************************************************************************
1393 > $Function: handle_sigalrm()
1395 * $Description: Handle timeouts
1397 ****************************************************************************/
1399 static void handle_sigalrm(int sig)
1401 sendHeaders(HTTP_REQUEST_TIMEOUT);
1402 config->alarm_signaled = sig;
1405 /****************************************************************************
1407 > $Function: handleIncoming()
1409 * $Description: Handle an incoming http request.
1411 ****************************************************************************/
1412 static void handleIncoming(void)
1414 char *buf = config->buf;
1421 #if ENABLE_FEATURE_HTTPD_CGI
1422 const char *prequest = request_GET;
1423 unsigned long length = 0;
1425 char *content_type = 0;
1430 struct sigaction sa;
1432 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1433 int credentials = -1; /* if not required this is Ok */
1436 sa.sa_handler = handle_sigalrm;
1437 sigemptyset(&sa.sa_mask);
1438 sa.sa_flags = 0; /* no SA_RESTART */
1439 sigaction(SIGALRM, &sa, NULL);
1444 (void) alarm(TIMEOUT);
1448 purl = strpbrk(buf, " \t");
1451 sendHeaders(HTTP_BAD_REQUEST);
1455 #if ENABLE_FEATURE_HTTPD_CGI
1456 if (strcasecmp(buf, prequest) != 0) {
1458 if (strcasecmp(buf, prequest) != 0) {
1459 sendHeaders(HTTP_NOT_IMPLEMENTED);
1464 if (strcasecmp(buf, request_GET) != 0) {
1465 sendHeaders(HTTP_NOT_IMPLEMENTED);
1470 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1472 if (count < 1 || buf[0] != '/') {
1473 /* Garbled request/URL */
1476 url = alloca(strlen(buf) + sizeof("/index.html"));
1478 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1482 /* extract url args if present */
1483 test = strchr(url, '?');
1486 config->query = test;
1489 test = decodeString(url, 0);
1492 /* FIXME: bug? should be "url+1"? */
1493 if (test == (buf+1)) {
1494 sendHeaders(HTTP_NOT_FOUND);
1498 /* algorithm stolen from libbb bb_simplify_path(),
1499 but don't strdup and reducing trailing slash and protect out root */
1503 /* skip duplicate (or initial) slash */
1508 /* skip extra '.' */
1509 if (test[1] == '/' || test[1] == 0) {
1512 /* '..': be careful */
1513 if (test[1] == '.' && (test[2] == '/' || test[2] == 0)) {
1516 /* protect out root */
1519 while (*--purl != '/') /* omit previous dir */;
1526 *++purl = '\0'; /* so keep last character */
1527 test = purl; /* end ptr */
1529 /* If URL is directory, adding '/' */
1530 if (test[-1] != '/') {
1531 if (is_directory(url + 1, 1, &sb)) {
1532 config->found_moved_temporarily = url;
1536 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1539 ip_allowed = checkPermIP();
1540 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1541 /* have path1/path2 */
1543 if (is_directory(url + 1, 1, &sb)) {
1544 /* may be having subdir config */
1545 parse_conf(url + 1, SUBDIR_PARSE);
1546 ip_allowed = checkPermIP();
1551 // read until blank line for HTTP version specified, else parse immediate
1559 fprintf(stderr, "header: '%s'\n", buf);
1561 #if ENABLE_FEATURE_HTTPD_CGI
1562 /* try and do our best to parse more lines */
1563 if ((STRNCASECMP(buf, "Content-length:") == 0)) {
1564 /* extra read only for POST */
1565 if (prequest != request_GET) {
1566 test = buf + sizeof("Content-length:")-1;
1567 if (!test[0]) goto bail_out;
1569 /* not using strtoul: it ignores leading munis! */
1570 length = strtol(test, &test, 10);
1571 /* length is "ulong", but we need to pass it to int later */
1572 /* so we check for negative or too large values in one go: */
1573 /* (long -> ulong conv will cause negatives to be seen as > INT_MAX) */
1574 if (test[0] || errno || length > INT_MAX)
1577 } else if ((STRNCASECMP(buf, "Cookie:") == 0)) {
1578 cookie = strdup(skip_whitespace(buf + sizeof("Cookie:")-1));
1579 } else if ((STRNCASECMP(buf, "Content-Type:") == 0)) {
1580 content_type = strdup(skip_whitespace(buf + sizeof("Content-Type:")-1));
1581 } else if ((STRNCASECMP(buf, "Referer:") == 0)) {
1582 config->referer = strdup(skip_whitespace(buf + sizeof("Referer:")-1));
1586 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1587 if (STRNCASECMP(buf, "Authorization:") == 0) {
1588 /* We only allow Basic credentials.
1589 * It shows up as "Authorization: Basic <userid:password>" where
1590 * the userid:password is base64 encoded.
1592 test = skip_whitespace(buf + sizeof("Authorization:")-1);
1593 if (STRNCASECMP(test, "Basic") != 0)
1595 test += sizeof("Basic")-1;
1596 /* decodeBase64() skips whitespace itself */
1598 credentials = checkPerm(url, test);
1600 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1602 } /* while extra header reading */
1605 if (config->alarm_signaled)
1608 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1609 /* protect listing [/path]/httpd_conf or IP deny */
1610 #if ENABLE_FEATURE_HTTPD_CGI
1611 FORBIDDEN: /* protect listing /cgi-bin */
1613 sendHeaders(HTTP_FORBIDDEN);
1617 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1618 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1619 sendHeaders(HTTP_UNAUTHORIZED);
1624 if (config->found_moved_temporarily) {
1625 sendHeaders(HTTP_MOVED_TEMPORARILY);
1626 /* clear unforked memory flag */
1627 config->found_moved_temporarily = NULL;
1631 test = url + 1; /* skip first '/' */
1633 #if ENABLE_FEATURE_HTTPD_CGI
1634 if (strncmp(test, "cgi-bin", 7) == 0) {
1635 if (test[7] == '/' && test[8] == 0)
1636 goto FORBIDDEN; // protect listing cgi-bin/
1637 sendCgi(url, prequest, length, cookie, content_type);
1639 if (prequest != request_GET)
1640 sendHeaders(HTTP_NOT_IMPLEMENTED);
1642 #endif /* FEATURE_HTTPD_CGI */
1643 if (purl[-1] == '/')
1644 strcpy(purl, "index.html");
1645 if (stat(test, &sb) == 0) {
1646 config->ContentLength = sb.st_size;
1647 config->last_mod = sb.st_mtime;
1650 config->ContentLength = -1;
1651 #if ENABLE_FEATURE_HTTPD_CGI
1660 fprintf(stderr, "closing socket\n\n");
1661 #if ENABLE_FEATURE_HTTPD_CGI
1664 free(config->referer);
1665 config->referer = NULL;
1666 # if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1667 free(config->remoteuser);
1668 config->remoteuser = NULL;
1671 shutdown(config->accepted_socket, SHUT_WR);
1673 /* Properly wait for remote to closed */
1675 FD_SET(config->accepted_socket, &s_fd);
1680 retval = select(config->accepted_socket + 1, &s_fd, NULL, NULL, &tv);
1681 } while (retval > 0 && read(config->accepted_socket, buf, sizeof(config->buf) > 0));
1683 shutdown(config->accepted_socket, SHUT_RD);
1684 /* In inetd case, we close fd 1 (stdout) here. We will exit soon anyway */
1685 close(config->accepted_socket);
1688 /****************************************************************************
1690 > $Function: miniHttpd()
1692 * $Description: The main http server function.
1694 * Given an open socket fildes, listen for new connections and farm out
1695 * the processing as a forked process.
1698 * (int) server. . . The server socket fildes.
1700 * $Return: (int) . . . . Always 0.
1702 ****************************************************************************/
1703 static int miniHttpd(int server)
1705 fd_set readfd, portfd;
1708 FD_SET(server, &portfd);
1710 /* copy the ports we are watching to the readfd set */
1713 socklen_t fromAddrLen;
1714 struct sockaddr_in fromAddr;
1716 /* Now wait INDEFINITELY on the set of sockets! */
1718 if (select(server + 1, &readfd, 0, 0, 0) <= 0)
1720 if (!FD_ISSET(server, &readfd))
1722 fromAddrLen = sizeof(fromAddr);
1723 s = accept(server, (struct sockaddr *)&fromAddr, &fromAddrLen);
1726 config->accepted_socket = s;
1727 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1728 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1729 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1730 (unsigned char)(config->rmt_ip >> 24),
1731 (unsigned char)(config->rmt_ip >> 16),
1732 (unsigned char)(config->rmt_ip >> 8),
1733 config->rmt_ip & 0xff);
1734 config->port = ntohs(fromAddr.sin_port);
1736 bb_error_msg("connection from IP=%s, port %u",
1737 config->rmt_ip_str, config->port);
1739 #endif /* FEATURE_HTTPD_CGI */
1741 /* set the KEEPALIVE option to cull dead connections */
1743 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
1748 /* This is the spawned thread */
1749 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1750 /* protect reload config, may be confuse checking */
1751 signal(SIGHUP, SIG_IGN);
1764 static int miniHttpd_inetd(void)
1766 struct sockaddr_in fromAddrLen;
1767 socklen_t sinlen = sizeof(struct sockaddr_in);
1769 getpeername(0, (struct sockaddr *)&fromAddrLen, &sinlen);
1770 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1771 #if ENABLE_FEATURE_HTTPD_CGI
1772 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1773 (unsigned char)(config->rmt_ip >> 24),
1774 (unsigned char)(config->rmt_ip >> 16),
1775 (unsigned char)(config->rmt_ip >> 8),
1776 config->rmt_ip & 0xff);
1778 config->port = ntohs(fromAddrLen.sin_port);
1783 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1784 static void sighup_handler(int sig)
1787 struct sigaction sa;
1789 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1790 sa.sa_handler = sighup_handler;
1791 sigemptyset(&sa.sa_mask);
1792 sa.sa_flags = SA_RESTART;
1793 sigaction(SIGHUP, &sa, NULL);
1798 c_opt_config_file = 0,
1801 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1802 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1803 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1804 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1808 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1809 OPT_DECODE_URL = 1 << d_opt_decode_url,
1810 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1811 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1812 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1813 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1814 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1815 OPT_PORT = 1 << p_opt_port,
1816 OPT_INETD = 1 << p_opt_inetd,
1817 OPT_FOREGROUND = 1 << p_opt_foreground,
1820 static const char httpd_opts[] = "c:d:h:"
1821 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1822 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1823 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1824 USE_FEATURE_HTTPD_SETUID("u:")
1828 int httpd_main(int argc, char *argv[])
1831 const char *home_httpd = home;
1832 char *url_for_decode;
1833 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1835 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1836 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1837 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1839 config = xzalloc(sizeof(*config));
1840 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1841 config->realm = "Web Server Authentication";
1844 config->ContentLength = -1;
1846 opt = getopt32(argc, argv, httpd_opts,
1847 &(config->configFile), &url_for_decode, &home_httpd
1848 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1849 USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
1850 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1851 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1854 if (opt & OPT_DECODE_URL) {
1855 printf("%s", decodeString(url_for_decode, 1));
1858 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1859 if (opt & OPT_ENCODE_URL) {
1860 printf("%s", encodeString(url_for_encode));
1864 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1865 if (opt & OPT_MD5) {
1866 puts(pw_encrypt(pass, "$1$"));
1871 config->port = xatou16(s_port);
1873 #if ENABLE_FEATURE_HTTPD_SETUID
1874 if (opt & OPT_SETUID) {
1876 // FIXME: what the default group should be?
1878 ugid.uid = strtoul(s_ugid, &e, 0);
1881 ugid.gid = strtoul(e, &e, 0);
1885 if (!uidgid_get(&ugid, s_ugid))
1886 bb_error_msg_and_die("unrecognized user[:group] "
1887 "name '%s'", s_ugid);
1893 if (!(opt & OPT_INETD)) {
1894 config->server_socket = openServer();
1895 #if ENABLE_FEATURE_HTTPD_SETUID
1896 /* drop privileges */
1897 if (opt & OPT_SETUID) {
1898 if (ugid.gid != (gid_t)-1) {
1899 if (setgroups(1, &ugid.gid) == -1)
1900 bb_perror_msg_and_die("setgroups");
1908 #if ENABLE_FEATURE_HTTPD_CGI
1910 char *p = getenv("PATH");
1917 if (!(opt & OPT_INETD))
1918 setenv_long("SERVER_PORT", config->port);
1922 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1925 parse_conf(default_path_httpd_conf, FIRST_PARSE);
1928 if (opt & OPT_INETD)
1929 return miniHttpd_inetd();
1931 if (!(opt & OPT_FOREGROUND))
1932 xdaemon(1, 0); /* don't change current directory */
1933 return miniHttpd(config->server_socket);