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";
259 static const char Content_length[] = "Content-length:";
262 static int scan_ip(const char **ep, unsigned int *ip, unsigned char endc)
269 for (j = 0; j < 4; j++) {
272 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
275 while (*p >= '0' && *p <= '9') {
284 if (*p != '/' && *p != 0)
286 *ip = ((*ip) << 8) | octet;
299 static int scan_ip_mask(const char *ipm, unsigned int *ip, unsigned int *mask)
304 i = scan_ip(&ipm, ip, '/');
312 if (*p < '0' || *p > '9') {
314 i = scan_ip(&ipm, mask, 0);
336 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
337 static void free_config_lines(Htaccess **pprev)
339 Htaccess *prev = *pprev;
342 Htaccess *cur = prev;
352 #define FIRST_PARSE 0
353 #define SUBDIR_PARSE 1
354 #define SIGNALED_PARSE 2
355 #define FIND_FROM_HTTPD_ROOT 3
356 /****************************************************************************
358 > $Function: parse_conf()
360 * $Description: parse configuration file into in-memory linked list.
362 * The first non-white character is examined to determine if the config line
363 * is one of the following:
364 * .ext:mime/type # new mime type not compiled into httpd
365 * [adAD]:from # ip address allow/deny, * for wildcard
366 * /path:user:pass # username/password
368 * Any previous IP rules are discarded.
369 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
370 * are also discarded. That is, previous settings are retained if flag is
374 * (const char *) path . . null for ip address checks, path for password
376 * (int) flag . . . . . . the source of the parse request.
380 ****************************************************************************/
381 static void parse_conf(const char *path, int flag)
384 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
385 Htaccess *prev, *cur;
386 #elif ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
390 const char *cf = config->configFile;
395 /* free previous ip setup if present */
396 Htaccess_IP *pip = config->ip_a_d;
399 Htaccess_IP *cur_ipl = pip;
404 config->ip_a_d = NULL;
406 config->flg_deny_all = 0;
408 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
409 /* retain previous auth and mime config only for subdir parse */
410 if (flag != SUBDIR_PARSE) {
411 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
412 free_config_lines(&config->auth);
414 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
415 free_config_lines(&config->mime_a);
417 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
418 free_config_lines(&config->script_i);
423 if (flag == SUBDIR_PARSE || cf == NULL) {
424 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
426 if (flag == FIRST_PARSE)
427 bb_error_msg_and_die(bb_msg_memory_exhausted);
430 sprintf((char *)cf, "%s/%s", path, httpd_conf);
433 while ((f = fopen(cf, "r")) == NULL) {
434 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
435 /* config file not found, no changes to config */
438 if (config->configFile && flag == FIRST_PARSE) /* if -c option given */
439 bb_perror_msg_and_die("%s", cf);
440 flag = FIND_FROM_HTTPD_ROOT;
444 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
447 /* This could stand some work */
448 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
450 for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
453 if (*p0 == ':' && c == NULL)
459 /* test for empty or strange line */
460 if (c == NULL || *c == 0)
467 /* memorize deny all */
468 config->flg_deny_all++;
470 /* skip default other "word:*" config lines */
476 else if (*p0 != 'D' && *p0 != 'A'
477 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
480 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
483 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
488 if (*p0 == 'A' || *p0 == 'D') {
489 /* storing current config IP line */
490 pip = calloc(1, sizeof(Htaccess_IP));
492 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
493 /* syntax IP{/mask} error detected, protect all */
497 pip->allow_deny = *p0;
499 /* Deny:form_IP move top */
500 pip->next = config->ip_a_d;
501 config->ip_a_d = pip;
503 /* add to bottom A:form_IP config line */
504 Htaccess_IP *prev_IP = config->ip_a_d;
506 if (prev_IP == NULL) {
507 config->ip_a_d = pip;
509 while (prev_IP->next)
510 prev_IP = prev_IP->next;
517 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
519 /* make full path from httpd root / curent_path / config_line_path */
520 cf = flag == SUBDIR_PARSE ? path : "";
521 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
525 sprintf(p0, "/%s%s", cf, buf);
527 /* another call bb_simplify_path */
532 if (*cf == '/') { /* skip duplicate (or initial) slash */
534 } else if (*cf == '.') {
535 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
537 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
540 while (*--p != '/') /* omit previous dir */;
549 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
550 ++p; /* so keep last character */
553 sprintf(p0, "%s:%s", p0, c);
557 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
558 /* storing current config line */
559 cur = calloc(1, sizeof(Htaccess) + strlen(p0));
561 cf = strcpy(cur->before_colon, p0);
564 cur->after_colon = c;
565 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
567 /* config .mime line move top for overwrite previous */
568 cur->next = config->mime_a;
569 config->mime_a = cur;
573 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
574 if (*cf == '*' && cf[1] == '.') {
575 /* config script interpreter line move top for overwrite previous */
576 cur->next = config->script_i;
577 config->script_i = cur;
581 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
585 config->auth = prev = cur;
587 /* sort path, if current lenght eq or bigger then move up */
588 Htaccess *prev_hti = config->auth;
589 size_t l = strlen(cf);
592 for (hti = prev_hti; hti; hti = hti->next) {
593 if (l >= strlen(hti->before_colon)) {
594 /* insert before hti */
596 if (prev_hti != hti) {
597 prev_hti->next = cur;
605 prev_hti = prev_hti->next;
607 if (!hti) { /* not inserted, add to bottom */
619 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
620 /****************************************************************************
622 > $Function: encodeString()
624 * $Description: Given a string, html encode special characters.
625 * This is used for the -e command line option to provide an easy way
626 * for scripts to encode result data without confusing browsers. The
627 * returned string pointer is memory allocated by malloc().
630 * (const char *) string . . The first string to encode.
632 * $Return: (char *) . . . .. . . A pointer to the encoded string.
634 * $Errors: Returns a null string ("") if memory is not available.
636 ****************************************************************************/
637 static char *encodeString(const char *string)
639 /* take the simple route and encode everything */
640 /* could possibly scan once to get length. */
641 int len = strlen(string);
642 char *out = malloc(len * 6 + 1);
647 while ((ch = *string++)) {
648 // very simple check for what to encode
649 if (isalnum(ch)) *p++ = ch;
650 else p += sprintf(p, "&#%d;", (unsigned char) ch);
655 #endif /* CONFIG_FEATURE_HTTPD_ENCODE_URL_STR */
657 /****************************************************************************
659 > $Function: decodeString()
661 * $Description: Given a URL encoded string, convert it to plain ascii.
662 * Since decoding always makes strings smaller, the decode is done in-place.
663 * Thus, callers should strdup() the argument if they do not want the
664 * argument modified. The return is the original pointer, allowing this
665 * function to be easily used as arguments to other functions.
668 * (char *) string . . . The first string to decode.
669 * (int) flag . . . 1 if require decode '+' as ' ' for CGI
671 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
675 ****************************************************************************/
676 static char *decodeString(char *orig, int flag_plus_to_space)
678 /* note that decoded string is always shorter than original */
683 if (*ptr == '+' && flag_plus_to_space) { *string++ = ' '; ptr++; }
684 else if (*ptr != '%') *string++ = *ptr++;
686 unsigned int value1, value2;
689 if (sscanf(ptr, "%1X", &value1) != 1 ||
690 sscanf(ptr+1, "%1X", &value2) != 1) {
691 if (!flag_plus_to_space)
695 value1 = value1 * 16 + value2;
696 if (value1 == '/' || value1 == 0)
708 #if ENABLE_FEATURE_HTTPD_CGI
709 /****************************************************************************
711 ****************************************************************************/
712 static void setenv1(const char *name, const char *value)
716 setenv(name, value, 1);
718 static void setenv_long(const char *name, long value)
720 char buf[sizeof(value)*3 + 1];
721 sprintf(buf, "%ld", value);
722 setenv(name, buf, 1);
726 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
727 /****************************************************************************
729 > $Function: decodeBase64()
731 > $Description: Decode a base 64 data stream as per rfc1521.
732 * Note that the rfc states that none base64 chars are to be ignored.
733 * Since the decode always results in a shorter size than the input, it is
734 * OK to pass the input arg as an output arg.
737 * (char *) Data . . . . A pointer to a base64 encoded string.
738 * Where to place the decoded data.
744 ****************************************************************************/
745 static void decodeBase64(char *Data)
748 const unsigned char *in = (const unsigned char *)Data;
749 // The decoded size will be at most 3/4 the size of the encoded
750 unsigned long ch = 0;
756 if (t >= '0' && t <= '9')
758 else if (t >= 'A' && t <= 'Z')
760 else if (t >= 'a' && t <= 'z')
774 *Data++ = (char) (ch >> 16);
775 *Data++ = (char) (ch >> 8);
785 /****************************************************************************
787 > $Function: openServer()
789 * $Description: create a listen server socket on the designated port.
791 * $Return: (int) . . . A connection socket. -1 for errors.
795 ****************************************************************************/
796 static int openServer(void)
798 struct sockaddr_in lsocket;
802 /* create the socket right now */
803 /* inet_addr() returns a value that is already in network order */
804 memset(&lsocket, 0, sizeof(lsocket));
805 lsocket.sin_family = AF_INET;
806 lsocket.sin_addr.s_addr = INADDR_ANY;
807 lsocket.sin_port = htons(config->port);
808 fd = xsocket(AF_INET, SOCK_STREAM, 0);
809 /* tell the OS it's OK to reuse a previous address even though */
810 /* it may still be in a close down state. Allows bind to succeed. */
812 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on));
814 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
816 xbind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket));
818 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
822 /****************************************************************************
824 > $Function: sendHeaders()
826 * $Description: Create and send HTTP response headers.
827 * The arguments are combined and sent as one write operation. Note that
828 * IE will puke big-time if the headers are not sent in one packet and the
829 * second packet is delayed for any reason.
832 * (HttpResponseNum) responseNum . . . The result code to send.
834 * $Return: (int) . . . . writing errors
836 ****************************************************************************/
837 static int sendHeaders(HttpResponseNum responseNum)
839 char *buf = config->buf;
840 const char *responseString = "";
841 const char *infoString = 0;
842 const char *mime_type;
844 time_t timer = time(0);
849 i < (sizeof(httpResponseNames)/sizeof(httpResponseNames[0])); i++) {
850 if (httpResponseNames[i].type == responseNum) {
851 responseString = httpResponseNames[i].name;
852 infoString = httpResponseNames[i].info;
856 /* error message is HTML */
857 mime_type = responseNum == HTTP_OK ?
858 config->found_mime_type : "text/html";
860 /* emit the current date */
861 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
863 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
864 "Date: %s\r\nConnection: close\r\n",
865 responseNum, responseString, mime_type, timeStr);
867 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
868 if (responseNum == HTTP_UNAUTHORIZED) {
869 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
873 if (responseNum == HTTP_MOVED_TEMPORARILY) {
874 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
875 config->found_moved_temporarily,
876 (config->query ? "?" : ""),
877 (config->query ? config->query : ""));
880 if (config->ContentLength != -1) { /* file */
881 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
882 len += sprintf(buf+len, "Last-Modified: %s\r\n%s %"OFF_FMT"\r\n",
883 timeStr, Content_length, (off_t) config->ContentLength);
888 len += sprintf(buf+len,
889 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
890 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
891 responseNum, responseString,
892 responseNum, responseString, infoString);
895 fprintf(stderr, "headers: '%s'\n", buf);
897 return full_write(config->accepted_socket, buf, len);
900 /****************************************************************************
902 > $Function: getLine()
904 * $Description: Read from the socket until an end of line char found.
906 * Characters are read one at a time until an eol sequence is found.
908 * $Return: (int) . . . . number of characters read. -1 if error.
910 ****************************************************************************/
911 static int getLine(void)
914 char *buf = config->buf;
916 while (read(config->accepted_socket, buf + count, 1) == 1) {
917 if (buf[count] == '\r') continue;
918 if (buf[count] == '\n') {
922 if (count < (MAX_MEMORY_BUFF-1)) /* check overflow */
925 if (count) return count;
929 #if ENABLE_FEATURE_HTTPD_CGI
930 /****************************************************************************
932 > $Function: sendCgi()
934 * $Description: Execute a CGI script and send it's stdout back
936 * Environment variables are set up and the script is invoked with pipes
937 * for stdin/stdout. If a post is being done the script is fed the POST
938 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
941 * (const char *) url . . . . . . The requested URL (with leading /).
942 * (int bodyLen) . . . . . . . . Length of the post body.
943 * (const char *cookie) . . . . . For set HTTP_COOKIE.
944 * (const char *content_type) . . For set CONTENT_TYPE.
947 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
951 ****************************************************************************/
952 static int sendCgi(const char *url,
953 const char *request, int bodyLen, const char *cookie,
954 const char *content_type)
956 int fromCgi[2]; /* pipe for reading data from CGI */
957 int toCgi[2]; /* pipe for sending data to CGI */
959 static char * argp[] = { 0, 0 };
966 if (pipe(fromCgi) != 0) {
969 if (pipe(toCgi) != 0) {
982 char *purl = strdup(url);
983 char realpath_buff[MAXPATHLEN];
991 dup2(inFd, 0); // replace stdin with the pipe
992 dup2(outFd, 1); // replace stdout with the pipe
994 dup2(outFd, 2); // replace stderr with the pipe
1001 close(config->accepted_socket);
1002 close(config->server_socket);
1008 while ((script = strchr(script + 1, '/')) != NULL) {
1009 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1013 if (is_directory(purl + 1, 1, &sb) == 0) {
1014 /* not directory, found script.cgi/PATH_INFO */
1018 *script = '/'; /* is directory, find next '/' */
1020 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1021 setenv1("PATH", getenv("PATH")); /* Huh?? */
1022 setenv1("REQUEST_METHOD", request);
1023 if (config->query) {
1024 char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
1026 sprintf(uri, "%s?%s", purl, config->query);
1027 setenv1("REQUEST_URI", uri);
1029 setenv1("REQUEST_URI", purl);
1032 *script = '\0'; /* reduce /PATH_INFO */
1033 /* SCRIPT_FILENAME required by PHP in CGI mode */
1034 if (realpath(purl + 1, realpath_buff))
1035 setenv1("SCRIPT_FILENAME", realpath_buff);
1037 *realpath_buff = '\0';
1038 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1039 setenv1("SCRIPT_NAME", purl);
1040 setenv1("QUERY_STRING", config->query);
1041 setenv1("SERVER_SOFTWARE", httpdVersion);
1042 putenv("SERVER_PROTOCOL=HTTP/1.0");
1043 putenv("GATEWAY_INTERFACE=CGI/1.1");
1044 setenv1("REMOTE_ADDR", config->rmt_ip_str);
1045 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1046 setenv_long("REMOTE_PORT", config->port);
1049 setenv_long("CONTENT_LENGTH", bodyLen);
1052 setenv1("HTTP_COOKIE", cookie);
1054 setenv1("CONTENT_TYPE", content_type);
1055 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1056 if (config->remoteuser) {
1057 setenv1("REMOTE_USER", config->remoteuser);
1058 putenv("AUTH_TYPE=Basic");
1061 if (config->referer)
1062 setenv1("HTTP_REFERER", config->referer);
1064 /* set execve argp[0] without path */
1065 argp[0] = strrchr(purl, '/') + 1;
1066 /* but script argp[0] must have absolute path and chdiring to this */
1067 if (*realpath_buff) {
1068 script = strrchr(realpath_buff, '/');
1071 if (chdir(realpath_buff) == 0) {
1072 // now run the program. If it fails,
1073 // use _exit() so no destructors
1074 // get called and make a mess.
1075 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1076 char *interpr = NULL;
1077 char *suffix = strrchr(purl, '.');
1081 for (cur = config->script_i; cur; cur = cur->next)
1082 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1083 interpr = cur->after_colon;
1089 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1091 execv(interpr, argp);
1094 execv(realpath_buff, argp);
1098 /* send to stdout (even if we are not from inetd) */
1099 config->accepted_socket = 1;
1100 sendHeaders(HTTP_NOT_FOUND);
1107 /* parent process */
1109 size_t post_readed_size = 0, post_readed_idx = 0;
1115 signal(SIGPIPE, SIG_IGN);
1126 FD_SET(inFd, &readSet);
1127 if (bodyLen > 0 || post_readed_size > 0) {
1128 FD_SET(outFd, &writeSet);
1129 nfound = outFd > inFd ? outFd : inFd;
1130 if (post_readed_size == 0) {
1131 FD_SET(config->accepted_socket, &readSet);
1132 if (nfound < config->accepted_socket)
1133 nfound = config->accepted_socket;
1135 /* Now wait on the set of sockets! */
1136 nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
1142 nfound = select(inFd + 1, &readSet, 0, 0, NULL);
1146 if (waitpid(pid, &status, WNOHANG) > 0) {
1149 if (WIFEXITED(status))
1150 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1151 if (WIFSIGNALED(status))
1152 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1156 } else if (post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1157 count = full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1159 post_readed_size -= count;
1160 post_readed_idx += count;
1161 if (post_readed_size == 0)
1162 post_readed_idx = 0;
1164 post_readed_size = post_readed_idx = bodyLen = 0; /* broken pipe to CGI */
1166 } else if (bodyLen > 0 && post_readed_size == 0 && FD_ISSET(config->accepted_socket, &readSet)) {
1167 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1168 count = safe_read(config->accepted_socket, wbuf, count);
1170 post_readed_size += count;
1173 bodyLen = 0; /* closed */
1176 if (FD_ISSET(inFd, &readSet)) {
1177 int s = config->accepted_socket;
1178 char *rbuf = config->buf;
1181 # define PIPESIZE 4096 /* amount of buffering in a pipe */
1183 # define PIPESIZE PIPE_BUF
1185 #if PIPESIZE >= MAX_MEMORY_BUFF
1186 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1189 // There is something to read
1190 count = safe_read(inFd, rbuf, PIPESIZE);
1196 /* check to see if the user script added headers */
1197 if (strncmp(rbuf, "HTTP/1.0 200 OK\r\n", 4) != 0) {
1198 full_write(s, "HTTP/1.0 200 OK\r\n", 17);
1200 if (strstr(rbuf, "ontent-") == 0) {
1201 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1205 if (full_write(s, rbuf, count) != count)
1209 fprintf(stderr, "cgi read %d bytes\n", count);
1217 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1219 /****************************************************************************
1221 > $Function: sendFile()
1223 * $Description: Send a file response to a HTTP request
1226 * (const char *) url . . The URL requested.
1228 * $Return: (int) . . . . . . Always 0.
1230 ****************************************************************************/
1231 static int sendFile(const char *url)
1235 const char * const * table;
1236 const char * try_suffix;
1238 suffix = strrchr(url, '.');
1240 for (table = suffixTable; *table; table += 2)
1241 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1242 try_suffix += strlen(suffix);
1243 if (*try_suffix == 0 || *try_suffix == '.')
1246 /* also, if not found, set default as "application/octet-stream"; */
1247 config->found_mime_type = table[1];
1248 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1252 for (cur = config->mime_a; cur; cur = cur->next) {
1253 if (strcmp(cur->before_colon, suffix) == 0) {
1254 config->found_mime_type = cur->after_colon;
1259 #endif /* CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1262 fprintf(stderr, "sending file '%s' content-type: %s\n",
1263 url, config->found_mime_type);
1266 f = open(url, O_RDONLY);
1269 char *buf = config->buf;
1271 sendHeaders(HTTP_OK);
1272 while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1273 if (full_write(config->accepted_socket, buf, count) != count)
1279 bb_perror_msg("cannot open '%s'", url);
1281 sendHeaders(HTTP_NOT_FOUND);
1287 static int checkPermIP(void)
1291 /* This could stand some work */
1292 for (cur = config->ip_a_d; cur; cur = cur->next) {
1294 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1295 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1296 (unsigned char)(cur->ip >> 24),
1297 (unsigned char)(cur->ip >> 16),
1298 (unsigned char)(cur->ip >> 8),
1300 (unsigned char)(cur->mask >> 24),
1301 (unsigned char)(cur->mask >> 16),
1302 (unsigned char)(cur->mask >> 8),
1305 if ((config->rmt_ip & cur->mask) == cur->ip)
1306 return cur->allow_deny == 'A'; /* Allow/Deny */
1309 /* if unconfigured, return 1 - access from all */
1310 return !config->flg_deny_all;
1313 /****************************************************************************
1315 > $Function: checkPerm()
1317 * $Description: Check the permission file for access password protected.
1319 * If config file isn't present, everything is allowed.
1320 * Entries are of the form you can see example from header source
1323 * (const char *) path . . . . The file path.
1324 * (const char *) request . . . User information to validate.
1326 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1328 ****************************************************************************/
1330 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1331 static int checkPerm(const char *path, const char *request)
1337 const char *prev = NULL;
1339 /* This could stand some work */
1340 for (cur = config->auth; cur; cur = cur->next) {
1341 p0 = cur->before_colon;
1342 if (prev != NULL && strcmp(prev, p0) != 0)
1343 continue; /* find next identical */
1344 p = cur->after_colon;
1346 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1349 size_t l = strlen(p0);
1351 if (strncmp(p0, path, l) == 0 &&
1352 (l == 1 || path[l] == '/' || path[l] == 0)) {
1354 /* path match found. Check request */
1355 /* for check next /path:user:password */
1357 u = strchr(request, ':');
1359 /* bad request, ':' required */
1363 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1368 if (strncmp(p, request, u-request) != 0) {
1369 /* user uncompared */
1372 pp = strchr(p, ':');
1373 if (pp && pp[1] == '$' && pp[2] == '1' &&
1374 pp[3] == '$' && pp[4]) {
1376 cipher = pw_encrypt(u+1, pp);
1377 if (strcmp(cipher, pp) == 0)
1378 goto set_remoteuser_var; /* Ok */
1384 if (strcmp(p, request) == 0) {
1385 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1388 config->remoteuser = strdup(request);
1389 if (config->remoteuser)
1390 config->remoteuser[(u - request)] = 0;
1398 return prev == NULL;
1401 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1403 /****************************************************************************
1405 > $Function: handle_sigalrm()
1407 * $Description: Handle timeouts
1409 ****************************************************************************/
1411 static void handle_sigalrm(int sig)
1413 sendHeaders(HTTP_REQUEST_TIMEOUT);
1414 config->alarm_signaled = sig;
1417 /****************************************************************************
1419 > $Function: handleIncoming()
1421 * $Description: Handle an incoming http request.
1423 ****************************************************************************/
1424 static void handleIncoming(void)
1426 char *buf = config->buf;
1433 #if ENABLE_FEATURE_HTTPD_CGI
1434 const char *prequest = request_GET;
1437 char *content_type = 0;
1442 struct sigaction sa;
1444 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1445 int credentials = -1; /* if not required this is Ok */
1448 sa.sa_handler = handle_sigalrm;
1449 sigemptyset(&sa.sa_mask);
1450 sa.sa_flags = 0; /* no SA_RESTART */
1451 sigaction(SIGALRM, &sa, NULL);
1456 (void) alarm(TIMEOUT);
1460 purl = strpbrk(buf, " \t");
1463 sendHeaders(HTTP_BAD_REQUEST);
1467 #if ENABLE_FEATURE_HTTPD_CGI
1468 if (strcasecmp(buf, prequest) != 0) {
1470 if (strcasecmp(buf, prequest) != 0) {
1471 sendHeaders(HTTP_NOT_IMPLEMENTED);
1476 if (strcasecmp(buf, request_GET) != 0) {
1477 sendHeaders(HTTP_NOT_IMPLEMENTED);
1482 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1484 if (count < 1 || buf[0] != '/') {
1485 /* Garbled request/URL */
1488 url = alloca(strlen(buf) + sizeof("/index.html"));
1490 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1494 /* extract url args if present */
1495 test = strchr(url, '?');
1498 config->query = test;
1501 test = decodeString(url, 0);
1504 if (test == (buf+1)) {
1505 sendHeaders(HTTP_NOT_FOUND);
1508 /* algorithm stolen from libbb bb_simplify_path(),
1509 but don't strdup and reducing trailing slash and protect out root */
1514 if (*test == '/') { /* skip duplicate (or initial) slash */
1516 } else if (*test == '.') {
1517 if (test[1] == '/' || test[1] == 0) { /* skip extra '.' */
1519 } else if ((test[1] == '.') && (test[2] == '/' || test[2] == 0)) {
1522 /* protect out root */
1525 while (*--purl != '/') /* omit previous dir */;
1533 *++purl = 0; /* so keep last character */
1534 test = purl; /* end ptr */
1536 /* If URL is directory, adding '/' */
1537 if (test[-1] != '/') {
1538 if (is_directory(url + 1, 1, &sb)) {
1539 config->found_moved_temporarily = url;
1543 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1547 ip_allowed = checkPermIP();
1548 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1549 /* have path1/path2 */
1551 if (is_directory(url + 1, 1, &sb)) {
1552 /* may be having subdir config */
1553 parse_conf(url + 1, SUBDIR_PARSE);
1554 ip_allowed = checkPermIP();
1559 // read until blank line for HTTP version specified, else parse immediate
1567 fprintf(stderr, "Header: '%s'\n", buf);
1570 #if ENABLE_FEATURE_HTTPD_CGI
1571 /* try and do our best to parse more lines */
1572 if ((strncasecmp(buf, Content_length, 15) == 0)) {
1573 if (prequest != request_GET)
1574 length = strtol(buf + 15, 0, 0); // extra read only for POST
1575 } else if ((strncasecmp(buf, "Cookie:", 7) == 0)) {
1576 for (test = buf + 7; isspace(*test); test++)
1578 cookie = strdup(test);
1579 } else if ((strncasecmp(buf, "Content-Type:", 13) == 0)) {
1580 for (test = buf + 13; isspace(*test); test++)
1582 content_type = strdup(test);
1583 } else if ((strncasecmp(buf, "Referer:", 8) == 0)) {
1584 for (test = buf + 8; isspace(*test); test++)
1586 config->referer = strdup(test);
1590 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1591 if (strncasecmp(buf, "Authorization:", 14) == 0) {
1592 /* We only allow Basic credentials.
1593 * It shows up as "Authorization: Basic <userid:password>" where
1594 * the userid:password is base64 encoded.
1596 for (test = buf + 14; isspace(*test); test++)
1598 if (strncasecmp(test, "Basic", 5) != 0)
1601 test += 5; /* decodeBase64() skiping space self */
1603 credentials = checkPerm(url, test);
1605 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1607 } /* while extra header reading */
1610 if (config->alarm_signaled)
1613 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1614 /* protect listing [/path]/httpd_conf or IP deny */
1615 #if ENABLE_FEATURE_HTTPD_CGI
1616 FORBIDDEN: /* protect listing /cgi-bin */
1618 sendHeaders(HTTP_FORBIDDEN);
1622 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1623 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1624 sendHeaders(HTTP_UNAUTHORIZED);
1629 if (config->found_moved_temporarily) {
1630 sendHeaders(HTTP_MOVED_TEMPORARILY);
1631 /* clear unforked memory flag */
1632 config->found_moved_temporarily = NULL;
1636 test = url + 1; /* skip first '/' */
1638 #if ENABLE_FEATURE_HTTPD_CGI
1639 /* if strange Content-Length */
1643 if (strncmp(test, "cgi-bin", 7) == 0) {
1644 if (test[7] == '/' && test[8] == 0)
1645 goto FORBIDDEN; // protect listing cgi-bin/
1646 sendCgi(url, prequest, length, cookie, content_type);
1648 if (prequest != request_GET)
1649 sendHeaders(HTTP_NOT_IMPLEMENTED);
1651 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1652 if (purl[-1] == '/')
1653 strcpy(purl, "index.html");
1654 if (stat(test, &sb) == 0) {
1655 config->ContentLength = sb.st_size;
1656 config->last_mod = sb.st_mtime;
1659 config->ContentLength = -1;
1660 #if ENABLE_FEATURE_HTTPD_CGI
1667 fprintf(stderr, "closing socket\n\n");
1669 # if ENABLE_FEATURE_HTTPD_CGI
1672 free(config->referer); config->referer = NULL;
1673 # if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1674 free(config->remoteuser); config->remoteuser = NULL;
1677 shutdown(config->accepted_socket, SHUT_WR);
1679 /* Properly wait for remote to closed */
1681 FD_SET(config->accepted_socket, &s_fd);
1686 retval = select(config->accepted_socket + 1, &s_fd, NULL, NULL, &tv);
1687 } while (retval > 0 && read(config->accepted_socket, buf, sizeof(config->buf) > 0));
1689 shutdown(config->accepted_socket, SHUT_RD);
1690 /* In inetd case, we close fd 1 (stdout) here. We will exit soon anyway */
1691 close(config->accepted_socket);
1694 /****************************************************************************
1696 > $Function: miniHttpd()
1698 * $Description: The main http server function.
1700 * Given an open socket fildes, listen for new connections and farm out
1701 * the processing as a forked process.
1704 * (int) server. . . The server socket fildes.
1706 * $Return: (int) . . . . Always 0.
1708 ****************************************************************************/
1709 static int miniHttpd(int server)
1711 fd_set readfd, portfd;
1714 FD_SET(server, &portfd);
1716 /* copy the ports we are watching to the readfd set */
1719 socklen_t fromAddrLen;
1720 struct sockaddr_in fromAddr;
1722 /* Now wait INDEFINITELY on the set of sockets! */
1724 if (select(server + 1, &readfd, 0, 0, 0) <= 0)
1726 if (!FD_ISSET(server, &readfd))
1728 fromAddrLen = sizeof(fromAddr);
1729 s = accept(server, (struct sockaddr *)&fromAddr, &fromAddrLen);
1732 config->accepted_socket = s;
1733 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1734 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1735 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1736 (unsigned char)(config->rmt_ip >> 24),
1737 (unsigned char)(config->rmt_ip >> 16),
1738 (unsigned char)(config->rmt_ip >> 8),
1739 config->rmt_ip & 0xff);
1740 config->port = ntohs(fromAddr.sin_port);
1742 bb_error_msg("connection from IP=%s, port %u",
1743 config->rmt_ip_str, config->port);
1745 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1747 /* set the KEEPALIVE option to cull dead connections */
1749 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
1754 /* This is the spawned thread */
1755 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1756 /* protect reload config, may be confuse checking */
1757 signal(SIGHUP, SIG_IGN);
1770 static int miniHttpd_inetd(void)
1772 struct sockaddr_in fromAddrLen;
1773 socklen_t sinlen = sizeof(struct sockaddr_in);
1775 getpeername(0, (struct sockaddr *)&fromAddrLen, &sinlen);
1776 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1777 #if ENABLE_FEATURE_HTTPD_CGI
1778 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1779 (unsigned char)(config->rmt_ip >> 24),
1780 (unsigned char)(config->rmt_ip >> 16),
1781 (unsigned char)(config->rmt_ip >> 8),
1782 config->rmt_ip & 0xff);
1784 config->port = ntohs(fromAddrLen.sin_port);
1789 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1790 static void sighup_handler(int sig)
1793 struct sigaction sa;
1795 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1796 sa.sa_handler = sighup_handler;
1797 sigemptyset(&sa.sa_mask);
1798 sa.sa_flags = SA_RESTART;
1799 sigaction(SIGHUP, &sa, NULL);
1804 c_opt_config_file = 0,
1807 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1808 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1809 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1810 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1814 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1815 OPT_DECODE_URL = 1 << d_opt_decode_url,
1816 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1817 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1818 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1819 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1820 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1821 OPT_PORT = 1 << p_opt_port,
1822 OPT_INETD = 1 << p_opt_inetd,
1823 OPT_FOREGROUND = 1 << p_opt_foreground,
1826 static const char httpd_opts[] = "c:d:h:"
1827 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1828 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1829 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1830 USE_FEATURE_HTTPD_SETUID("u:")
1834 int httpd_main(int argc, char *argv[])
1837 const char *home_httpd = home;
1838 char *url_for_decode;
1839 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1841 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1842 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1843 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1845 config = xzalloc(sizeof(*config));
1846 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1847 config->realm = "Web Server Authentication";
1850 config->ContentLength = -1;
1852 opt = getopt32(argc, argv, httpd_opts,
1853 &(config->configFile), &url_for_decode, &home_httpd
1854 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1855 USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
1856 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1857 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1860 if (opt & OPT_DECODE_URL) {
1861 printf("%s", decodeString(url_for_decode, 1));
1864 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1865 if (opt & OPT_ENCODE_URL) {
1866 printf("%s", encodeString(url_for_encode));
1870 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1871 if (opt & OPT_MD5) {
1872 puts(pw_encrypt(pass, "$1$"));
1877 config->port = xatou16(s_port);
1879 #if ENABLE_FEATURE_HTTPD_SETUID
1880 if (opt & OPT_SETUID) {
1882 // FIXME: what the default group should be?
1884 ugid.uid = strtoul(s_ugid, &e, 0);
1887 ugid.gid = strtoul(e, &e, 0);
1891 if (!uidgid_get(&ugid, s_ugid))
1892 bb_error_msg_and_die("unrecognized user[:group] "
1893 "name '%s'", s_ugid);
1899 if (!(opt & OPT_INETD)) {
1900 config->server_socket = openServer();
1901 #if ENABLE_FEATURE_HTTPD_SETUID
1902 /* drop privileges */
1903 if (opt & OPT_SETUID) {
1904 if (ugid.gid != (gid_t)-1) {
1905 if (setgroups(1, &ugid.gid) == -1)
1906 bb_perror_msg_and_die("setgroups");
1914 #if ENABLE_FEATURE_HTTPD_CGI
1916 char *p = getenv("PATH");
1923 if (!(opt & OPT_INETD))
1924 setenv_long("SERVER_PORT", config->port);
1928 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1931 parse_conf(default_path_httpd_conf, FIRST_PARSE);
1934 if (opt & OPT_INETD)
1935 return miniHttpd_inetd();
1937 if (!(opt & OPT_FOREGROUND))
1938 xdaemon(1, 0); /* don't change current directory */
1939 return miniHttpd(config->server_socket);