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 */
147 const char *found_mime_type;
148 const char *found_moved_temporarily;
151 off_t ContentLength; /* -1 - unknown */
154 Htaccess_IP *ip_a_d; /* config allow/deny lines */
156 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
157 Htaccess *auth; /* config user:password lines */
159 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
160 Htaccess *mime_a; /* config mime types */
163 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
165 # define a_c_r config->accepted_socket
166 # define a_c_w config->accepted_socket
171 volatile int alarm_signaled;
173 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
174 Htaccess *script_i; /* config script interpreters */
178 static HttpdConfig *config;
180 static const char request_GET[] = "GET"; /* size algorithmic optimize */
182 static const char* const suffixTable [] = {
183 /* Warning: shorted equivalent suffix in one line must be first */
184 ".htm.html", "text/html",
185 ".jpg.jpeg", "image/jpeg",
188 ".txt.h.c.cc.cpp", "text/plain",
191 ".avi", "video/x-msvideo",
192 ".qt.mov", "video/quicktime",
193 ".mpe.mpeg", "video/mpeg",
194 ".mid.midi", "audio/midi",
195 ".mp3", "audio/mpeg",
196 #if 0 /* unpopular */
197 ".au", "audio/basic",
198 ".pac", "application/x-ns-proxy-autoconfig",
199 ".vrml.wrl", "model/vrml",
201 0, "application/octet-stream" /* default */
206 HTTP_MOVED_TEMPORARILY = 302,
207 HTTP_BAD_REQUEST = 400, /* malformed syntax */
208 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
209 HTTP_NOT_FOUND = 404,
210 HTTP_FORBIDDEN = 403,
211 HTTP_REQUEST_TIMEOUT = 408,
212 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
213 HTTP_INTERNAL_SERVER_ERROR = 500,
214 #if 0 /* future use */
216 HTTP_SWITCHING_PROTOCOLS = 101,
219 HTTP_NON_AUTHORITATIVE_INFO = 203,
220 HTTP_NO_CONTENT = 204,
221 HTTP_MULTIPLE_CHOICES = 300,
222 HTTP_MOVED_PERMANENTLY = 301,
223 HTTP_NOT_MODIFIED = 304,
224 HTTP_PAYMENT_REQUIRED = 402,
225 HTTP_BAD_GATEWAY = 502,
226 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
227 HTTP_RESPONSE_SETSIZE = 0xffffffff
232 HttpResponseNum type;
237 static const HttpEnumString httpResponseNames[] = {
238 { HTTP_OK, "OK", NULL },
239 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
240 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
241 "No request appeared within a reasonable time period." },
242 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
243 "The requested method is not recognized by this server." },
244 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
245 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
247 { HTTP_NOT_FOUND, "Not Found",
248 "The requested URL was not found on this server." },
249 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
250 { HTTP_FORBIDDEN, "Forbidden", "" },
251 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
252 "Internal Server Error" },
253 #if 0 /* not implemented */
254 { HTTP_CREATED, "Created" },
255 { HTTP_ACCEPTED, "Accepted" },
256 { HTTP_NO_CONTENT, "No Content" },
257 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
258 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
259 { HTTP_NOT_MODIFIED, "Not Modified" },
260 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
261 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
266 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
267 static const char Content_length[] = "Content-length:";
270 static int scan_ip(const char **ep, unsigned int *ip, unsigned char endc)
277 for (j = 0; j < 4; j++) {
280 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
283 while (*p >= '0' && *p <= '9') {
292 if (*p != '/' && *p != 0)
294 *ip = ((*ip) << 8) | octet;
307 static int scan_ip_mask(const char *ipm, unsigned int *ip, unsigned int *mask)
312 i = scan_ip(&ipm, ip, '/');
320 if (*p < '0' || *p > '9') {
322 i = scan_ip(&ipm, mask, 0);
344 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
345 static void free_config_lines(Htaccess **pprev)
347 Htaccess *prev = *pprev;
350 Htaccess *cur = prev;
360 #define FIRST_PARSE 0
361 #define SUBDIR_PARSE 1
362 #define SIGNALED_PARSE 2
363 #define FIND_FROM_HTTPD_ROOT 3
364 /****************************************************************************
366 > $Function: parse_conf()
368 * $Description: parse configuration file into in-memory linked list.
370 * The first non-white character is examined to determine if the config line
371 * is one of the following:
372 * .ext:mime/type # new mime type not compiled into httpd
373 * [adAD]:from # ip address allow/deny, * for wildcard
374 * /path:user:pass # username/password
376 * Any previous IP rules are discarded.
377 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
378 * are also discarded. That is, previous settings are retained if flag is
382 * (const char *) path . . null for ip address checks, path for password
384 * (int) flag . . . . . . the source of the parse request.
388 ****************************************************************************/
389 static void parse_conf(const char *path, int flag)
392 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
393 Htaccess *prev, *cur;
394 #elif CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
398 const char *cf = config->configFile;
403 /* free previous ip setup if present */
404 Htaccess_IP *pip = config->ip_a_d;
407 Htaccess_IP *cur_ipl = pip;
412 config->ip_a_d = NULL;
414 config->flg_deny_all = 0;
416 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
417 /* retain previous auth and mime config only for subdir parse */
418 if (flag != SUBDIR_PARSE) {
419 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
420 free_config_lines(&config->auth);
422 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
423 free_config_lines(&config->mime_a);
425 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
426 free_config_lines(&config->script_i);
431 if (flag == SUBDIR_PARSE || cf == NULL) {
432 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
434 if (flag == FIRST_PARSE)
435 bb_error_msg_and_die(bb_msg_memory_exhausted);
438 sprintf((char *)cf, "%s/%s", path, httpd_conf);
441 while ((f = fopen(cf, "r")) == NULL) {
442 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
443 /* config file not found, no changes to config */
446 if (config->configFile && flag == FIRST_PARSE) /* if -c option given */
447 bb_perror_msg_and_die("%s", cf);
448 flag = FIND_FROM_HTTPD_ROOT;
452 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
455 /* This could stand some work */
456 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
458 for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
461 if (*p0 == ':' && c == NULL)
467 /* test for empty or strange line */
468 if (c == NULL || *c == 0)
475 /* memorize deny all */
476 config->flg_deny_all++;
478 /* skip default other "word:*" config lines */
484 else if (*p0 != 'D' && *p0 != 'A'
485 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
488 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
491 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
496 if (*p0 == 'A' || *p0 == 'D') {
497 /* storing current config IP line */
498 pip = calloc(1, sizeof(Htaccess_IP));
500 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
501 /* syntax IP{/mask} error detected, protect all */
505 pip->allow_deny = *p0;
507 /* Deny:form_IP move top */
508 pip->next = config->ip_a_d;
509 config->ip_a_d = pip;
511 /* add to bottom A:form_IP config line */
512 Htaccess_IP *prev_IP = config->ip_a_d;
514 if (prev_IP == NULL) {
515 config->ip_a_d = pip;
517 while (prev_IP->next)
518 prev_IP = prev_IP->next;
525 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
527 /* make full path from httpd root / curent_path / config_line_path */
528 cf = flag == SUBDIR_PARSE ? path : "";
529 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
533 sprintf(p0, "/%s%s", cf, buf);
535 /* another call bb_simplify_path */
540 if (*cf == '/') { /* skip duplicate (or initial) slash */
542 } else if (*cf == '.') {
543 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
545 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
548 while (*--p != '/') /* omit previous dir */;
557 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
558 ++p; /* so keep last character */
561 sprintf(p0, "%s:%s", p0, c);
565 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
566 /* storing current config line */
567 cur = calloc(1, sizeof(Htaccess) + strlen(p0));
569 cf = strcpy(cur->before_colon, p0);
572 cur->after_colon = c;
573 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
575 /* config .mime line move top for overwrite previous */
576 cur->next = config->mime_a;
577 config->mime_a = cur;
581 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
582 if (*cf == '*' && cf[1] == '.') {
583 /* config script interpreter line move top for overwrite previous */
584 cur->next = config->script_i;
585 config->script_i = cur;
589 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
593 config->auth = prev = cur;
595 /* sort path, if current lenght eq or bigger then move up */
596 Htaccess *prev_hti = config->auth;
597 size_t l = strlen(cf);
600 for (hti = prev_hti; hti; hti = hti->next) {
601 if (l >= strlen(hti->before_colon)) {
602 /* insert before hti */
604 if (prev_hti != hti) {
605 prev_hti->next = cur;
613 prev_hti = prev_hti->next;
615 if (!hti) { /* not inserted, add to bottom */
627 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
628 /****************************************************************************
630 > $Function: encodeString()
632 * $Description: Given a string, html encode special characters.
633 * This is used for the -e command line option to provide an easy way
634 * for scripts to encode result data without confusing browsers. The
635 * returned string pointer is memory allocated by malloc().
638 * (const char *) string . . The first string to encode.
640 * $Return: (char *) . . . .. . . A pointer to the encoded string.
642 * $Errors: Returns a null string ("") if memory is not available.
644 ****************************************************************************/
645 static char *encodeString(const char *string)
647 /* take the simple route and encode everything */
648 /* could possibly scan once to get length. */
649 int len = strlen(string);
650 char *out = malloc(len * 6 + 1);
655 while ((ch = *string++)) {
656 // very simple check for what to encode
657 if (isalnum(ch)) *p++ = ch;
658 else p += sprintf(p, "&#%d;", (unsigned char) ch);
663 #endif /* CONFIG_FEATURE_HTTPD_ENCODE_URL_STR */
665 /****************************************************************************
667 > $Function: decodeString()
669 * $Description: Given a URL encoded string, convert it to plain ascii.
670 * Since decoding always makes strings smaller, the decode is done in-place.
671 * Thus, callers should strdup() the argument if they do not want the
672 * argument modified. The return is the original pointer, allowing this
673 * function to be easily used as arguments to other functions.
676 * (char *) string . . . The first string to decode.
677 * (int) flag . . . 1 if require decode '+' as ' ' for CGI
679 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
683 ****************************************************************************/
684 static char *decodeString(char *orig, int flag_plus_to_space)
686 /* note that decoded string is always shorter than original */
691 if (*ptr == '+' && flag_plus_to_space) { *string++ = ' '; ptr++; }
692 else if (*ptr != '%') *string++ = *ptr++;
694 unsigned int value1, value2;
697 if (sscanf(ptr, "%1X", &value1) != 1 ||
698 sscanf(ptr+1, "%1X", &value2) != 1) {
699 if (!flag_plus_to_space)
703 value1 = value1 * 16 + value2;
704 if (value1 == '/' || value1 == 0)
716 #if ENABLE_FEATURE_HTTPD_CGI
717 /****************************************************************************
719 > $Function: addEnv()
721 * $Description: Add an environment variable setting to the global list.
722 * A NAME=VALUE string is allocated, filled, and added to the list of
723 * environment settings passed to the cgi execution script.
726 * (char *) name_before_underline - The first part environment variable name.
727 * (char *) name_after_underline - The second part environment variable name.
728 * (char *) value . . The value to which the env variable is set.
732 * $Errors: Silently returns if the env runs out of space to hold the new item
734 ****************************************************************************/
735 static void addEnv(const char *name_before_underline,
736 const char *name_after_underline, const char *value)
739 const char *underline;
743 underline = *name_after_underline ? "_" : "";
744 asprintf(&s, "%s%s%s=%s", name_before_underline, underline,
745 name_after_underline, value);
751 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV || ENABLE_FEATURE_HTTPD_WITHOUT_INETD
752 /* set environs SERVER_PORT and REMOTE_PORT */
753 static void addEnvPort(const char *port_name)
757 sprintf(buf, "%u", config->port);
758 addEnv(port_name, "PORT", buf);
761 #endif /* CONFIG_FEATURE_HTTPD_CGI */
764 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
765 /****************************************************************************
767 > $Function: decodeBase64()
769 > $Description: Decode a base 64 data stream as per rfc1521.
770 * Note that the rfc states that none base64 chars are to be ignored.
771 * Since the decode always results in a shorter size than the input, it is
772 * OK to pass the input arg as an output arg.
775 * (char *) Data . . . . A pointer to a base64 encoded string.
776 * Where to place the decoded data.
782 ****************************************************************************/
783 static void decodeBase64(char *Data)
786 const unsigned char *in = (const unsigned char *)Data;
787 // The decoded size will be at most 3/4 the size of the encoded
788 unsigned long ch = 0;
794 if (t >= '0' && t <= '9')
796 else if (t >= 'A' && t <= 'Z')
798 else if (t >= 'a' && t <= 'z')
812 *Data++ = (char) (ch >> 16);
813 *Data++ = (char) (ch >> 8);
823 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
824 /****************************************************************************
826 > $Function: openServer()
828 * $Description: create a listen server socket on the designated port.
830 * $Return: (int) . . . A connection socket. -1 for errors.
834 ****************************************************************************/
835 static int openServer(void)
837 struct sockaddr_in lsocket;
841 /* create the socket right now */
842 /* inet_addr() returns a value that is already in network order */
843 memset(&lsocket, 0, sizeof(lsocket));
844 lsocket.sin_family = AF_INET;
845 lsocket.sin_addr.s_addr = INADDR_ANY;
846 lsocket.sin_port = htons(config->port);
847 fd = xsocket(AF_INET, SOCK_STREAM, 0);
848 /* tell the OS it's OK to reuse a previous address even though */
849 /* it may still be in a close down state. Allows bind to succeed. */
851 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on));
853 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
855 xbind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket));
857 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
860 #endif /* CONFIG_FEATURE_HTTPD_WITHOUT_INETD */
862 /****************************************************************************
864 > $Function: sendHeaders()
866 * $Description: Create and send HTTP response headers.
867 * The arguments are combined and sent as one write operation. Note that
868 * IE will puke big-time if the headers are not sent in one packet and the
869 * second packet is delayed for any reason.
872 * (HttpResponseNum) responseNum . . . The result code to send.
874 * $Return: (int) . . . . writing errors
876 ****************************************************************************/
877 static int sendHeaders(HttpResponseNum responseNum)
879 char *buf = config->buf;
880 const char *responseString = "";
881 const char *infoString = 0;
882 const char *mime_type;
884 time_t timer = time(0);
889 i < (sizeof(httpResponseNames)/sizeof(httpResponseNames[0])); i++) {
890 if (httpResponseNames[i].type == responseNum) {
891 responseString = httpResponseNames[i].name;
892 infoString = httpResponseNames[i].info;
896 /* error message is HTML */
897 mime_type = responseNum == HTTP_OK ?
898 config->httpd_found.found_mime_type : "text/html";
900 /* emit the current date */
901 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
903 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
904 "Date: %s\r\nConnection: close\r\n",
905 responseNum, responseString, mime_type, timeStr);
907 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
908 if (responseNum == HTTP_UNAUTHORIZED) {
909 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
913 if (responseNum == HTTP_MOVED_TEMPORARILY) {
914 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
915 config->httpd_found.found_moved_temporarily,
916 (config->query ? "?" : ""),
917 (config->query ? config->query : ""));
920 if (config->ContentLength != -1) { /* file */
921 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
922 len += sprintf(buf+len, "Last-Modified: %s\r\n%s "OFF_FMT"\r\n",
923 timeStr, Content_length, (off_t) config->ContentLength);
928 len += sprintf(buf+len,
929 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
930 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
931 responseNum, responseString,
932 responseNum, responseString, infoString);
935 fprintf(stderr, "Headers: '%s'", buf);
937 return full_write(a_c_w, buf, len);
940 /****************************************************************************
942 > $Function: getLine()
944 * $Description: Read from the socket until an end of line char found.
946 * Characters are read one at a time until an eol sequence is found.
948 * $Return: (int) . . . . number of characters read. -1 if error.
950 ****************************************************************************/
951 static int getLine(void)
954 char *buf = config->buf;
956 while (read(a_c_r, buf + count, 1) == 1) {
957 if (buf[count] == '\r') continue;
958 if (buf[count] == '\n') {
962 if (count < (MAX_MEMORY_BUFF-1)) /* check owerflow */
965 if (count) return count;
969 #if ENABLE_FEATURE_HTTPD_CGI
970 /****************************************************************************
972 > $Function: sendCgi()
974 * $Description: Execute a CGI script and send it's stdout back
976 * Environment variables are set up and the script is invoked with pipes
977 * for stdin/stdout. If a post is being done the script is fed the POST
978 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
981 * (const char *) url . . . . . . The requested URL (with leading /).
982 * (int bodyLen) . . . . . . . . Length of the post body.
983 * (const char *cookie) . . . . . For set HTTP_COOKIE.
984 * (const char *content_type) . . For set CONTENT_TYPE.
987 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
991 ****************************************************************************/
992 static int sendCgi(const char *url,
993 const char *request, int bodyLen, const char *cookie,
994 const char *content_type)
996 int fromCgi[2]; /* pipe for reading data from CGI */
997 int toCgi[2]; /* pipe for sending data to CGI */
999 static char * argp[] = { 0, 0 };
1006 if (pipe(fromCgi) != 0) {
1009 if (pipe(toCgi) != 0) {
1022 char *purl = strdup(url);
1023 char realpath_buff[MAXPATHLEN];
1031 dup2(inFd, 0); // replace stdin with the pipe
1032 dup2(outFd, 1); // replace stdout with the pipe
1034 dup2(outFd, 2); // replace stderr with the pipe
1045 while ((script = strchr(script + 1, '/')) != NULL) {
1046 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1050 if (is_directory(purl + 1, 1, &sb) == 0) {
1051 /* not directory, found script.cgi/PATH_INFO */
1055 *script = '/'; /* is directory, find next '/' */
1057 addEnv("PATH", "INFO", script); /* set /PATH_INFO or NULL */
1058 addEnv("PATH", "", getenv("PATH"));
1059 addEnv("REQUEST", "METHOD", request);
1060 if (config->query) {
1061 char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
1063 sprintf(uri, "%s?%s", purl, config->query);
1064 addEnv("REQUEST", "URI", uri);
1066 addEnv("REQUEST", "URI", purl);
1069 *script = '\0'; /* reduce /PATH_INFO */
1070 /* SCRIPT_FILENAME required by PHP in CGI mode */
1071 if (realpath(purl + 1, realpath_buff))
1072 addEnv("SCRIPT", "FILENAME", realpath_buff);
1075 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1076 addEnv("SCRIPT_NAME", "", purl);
1077 addEnv("QUERY_STRING", "", config->query);
1078 addEnv("SERVER", "SOFTWARE", httpdVersion);
1079 addEnv("SERVER", "PROTOCOL", "HTTP/1.0");
1080 addEnv("GATEWAY_INTERFACE", "", "CGI/1.1");
1081 addEnv("REMOTE", "ADDR", config->rmt_ip_str);
1082 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1083 addEnvPort("REMOTE");
1088 sprintf(sbl, "%d", bodyLen);
1089 addEnv("CONTENT", "LENGTH", sbl);
1092 addEnv("HTTP", "COOKIE", cookie);
1094 addEnv("CONTENT", "TYPE", content_type);
1095 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1096 if (config->remoteuser) {
1097 addEnv("REMOTE", "USER", config->remoteuser);
1098 addEnv("AUTH_TYPE", "", "Basic");
1101 if (config->referer)
1102 addEnv("HTTP", "REFERER", config->referer);
1104 /* set execve argp[0] without path */
1105 argp[0] = strrchr(purl, '/') + 1;
1106 /* but script argp[0] must have absolute path and chdiring to this */
1107 if (*realpath_buff) {
1108 script = strrchr(realpath_buff, '/');
1111 if (chdir(realpath_buff) == 0) {
1112 // now run the program. If it fails,
1113 // use _exit() so no destructors
1114 // get called and make a mess.
1115 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1116 char *interpr = NULL;
1117 char *suffix = strrchr(purl, '.');
1121 for (cur = config->script_i; cur; cur = cur->next)
1122 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1123 interpr = cur->after_colon;
1129 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1131 execv(interpr, argp);
1134 execv(realpath_buff, argp);
1138 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
1139 config->accepted_socket = 1; /* send to stdout */
1141 sendHeaders(HTTP_NOT_FOUND);
1148 /* parent process */
1150 size_t post_readed_size = 0, post_readed_idx = 0;
1156 signal(SIGPIPE, SIG_IGN);
1167 FD_SET(inFd, &readSet);
1168 if (bodyLen > 0 || post_readed_size > 0) {
1169 FD_SET(outFd, &writeSet);
1170 nfound = outFd > inFd ? outFd : inFd;
1171 if (post_readed_size == 0) {
1172 FD_SET(a_c_r, &readSet);
1176 /* Now wait on the set of sockets! */
1177 nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
1183 nfound = select(inFd + 1, &readSet, 0, 0, NULL);
1187 if (waitpid(pid, &status, WNOHANG) > 0) {
1190 if (WIFEXITED(status))
1191 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1192 if (WIFSIGNALED(status))
1193 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1197 } else if (post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1198 count = full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1200 post_readed_size -= count;
1201 post_readed_idx += count;
1202 if (post_readed_size == 0)
1203 post_readed_idx = 0;
1205 post_readed_size = post_readed_idx = bodyLen = 0; /* broken pipe to CGI */
1207 } else if (bodyLen > 0 && post_readed_size == 0 && FD_ISSET(a_c_r, &readSet)) {
1208 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1209 count = safe_read(a_c_r, wbuf, count);
1211 post_readed_size += count;
1214 bodyLen = 0; /* closed */
1217 if (FD_ISSET(inFd, &readSet)) {
1219 char *rbuf = config->buf;
1222 # define PIPESIZE 4096 /* amount of buffering in a pipe */
1224 # define PIPESIZE PIPE_BUF
1226 #if PIPESIZE >= MAX_MEMORY_BUFF
1227 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1230 // There is something to read
1231 count = safe_read(inFd, rbuf, PIPESIZE);
1237 /* check to see if the user script added headers */
1238 if (strncmp(rbuf, "HTTP/1.0 200 OK\r\n", 4) != 0) {
1239 full_write(s, "HTTP/1.0 200 OK\r\n", 17);
1241 if (strstr(rbuf, "ontent-") == 0) {
1242 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1246 if (full_write(s, rbuf, count) != count)
1250 fprintf(stderr, "cgi read %d bytes\n", count);
1258 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1260 /****************************************************************************
1262 > $Function: sendFile()
1264 * $Description: Send a file response to an HTTP request
1267 * (const char *) url . . The URL requested.
1269 * $Return: (int) . . . . . . Always 0.
1271 ****************************************************************************/
1272 static int sendFile(const char *url)
1276 const char * const * table;
1277 const char * try_suffix;
1279 suffix = strrchr(url, '.');
1281 for (table = suffixTable; *table; table += 2)
1282 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1283 try_suffix += strlen(suffix);
1284 if (*try_suffix == 0 || *try_suffix == '.')
1287 /* also, if not found, set default as "application/octet-stream"; */
1288 config->httpd_found.found_mime_type = *(table+1);
1289 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1293 for (cur = config->mime_a; cur; cur = cur->next) {
1294 if (strcmp(cur->before_colon, suffix) == 0) {
1295 config->httpd_found.found_mime_type = cur->after_colon;
1300 #endif /* CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1303 fprintf(stderr, "Sending file '%s' Content-type: %s\n",
1304 url, config->httpd_found.found_mime_type);
1307 f = open(url, O_RDONLY);
1310 char *buf = config->buf;
1312 sendHeaders(HTTP_OK);
1313 while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1314 if (full_write(a_c_w, buf, count) != count)
1320 bb_perror_msg("unable to open '%s'", url);
1322 sendHeaders(HTTP_NOT_FOUND);
1328 static int checkPermIP(void)
1332 /* This could stand some work */
1333 for (cur = config->ip_a_d; cur; cur = cur->next) {
1335 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1336 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1337 (unsigned char)(cur->ip >> 24),
1338 (unsigned char)(cur->ip >> 16),
1339 (unsigned char)(cur->ip >> 8),
1341 (unsigned char)(cur->mask >> 24),
1342 (unsigned char)(cur->mask >> 16),
1343 (unsigned char)(cur->mask >> 8),
1346 if ((config->rmt_ip & cur->mask) == cur->ip)
1347 return cur->allow_deny == 'A'; /* Allow/Deny */
1350 /* if unconfigured, return 1 - access from all */
1351 return !config->flg_deny_all;
1354 /****************************************************************************
1356 > $Function: checkPerm()
1358 * $Description: Check the permission file for access password protected.
1360 * If config file isn't present, everything is allowed.
1361 * Entries are of the form you can see example from header source
1364 * (const char *) path . . . . The file path.
1365 * (const char *) request . . . User information to validate.
1367 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1369 ****************************************************************************/
1371 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1372 static int checkPerm(const char *path, const char *request)
1378 const char *prev = NULL;
1380 /* This could stand some work */
1381 for (cur = config->auth; cur; cur = cur->next) {
1382 p0 = cur->before_colon;
1383 if (prev != NULL && strcmp(prev, p0) != 0)
1384 continue; /* find next identical */
1385 p = cur->after_colon;
1387 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1390 size_t l = strlen(p0);
1392 if (strncmp(p0, path, l) == 0 &&
1393 (l == 1 || path[l] == '/' || path[l] == 0)) {
1395 /* path match found. Check request */
1396 /* for check next /path:user:password */
1398 u = strchr(request, ':');
1400 /* bad request, ':' required */
1404 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1409 if (strncmp(p, request, u-request) != 0) {
1410 /* user uncompared */
1413 pp = strchr(p, ':');
1414 if (pp && pp[1] == '$' && pp[2] == '1' &&
1415 pp[3] == '$' && pp[4]) {
1417 cipher = pw_encrypt(u+1, pp);
1418 if (strcmp(cipher, pp) == 0)
1419 goto set_remoteuser_var; /* Ok */
1425 if (strcmp(p, request) == 0) {
1426 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1429 config->remoteuser = strdup(request);
1430 if (config->remoteuser)
1431 config->remoteuser[(u - request)] = 0;
1439 return prev == NULL;
1442 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1444 /****************************************************************************
1446 > $Function: handle_sigalrm()
1448 * $Description: Handle timeouts
1450 ****************************************************************************/
1452 static void handle_sigalrm(int sig)
1454 sendHeaders(HTTP_REQUEST_TIMEOUT);
1455 config->alarm_signaled = sig;
1458 /****************************************************************************
1460 > $Function: handleIncoming()
1462 * $Description: Handle an incoming http request.
1464 ****************************************************************************/
1465 static void handleIncoming(void)
1467 char *buf = config->buf;
1474 #if ENABLE_FEATURE_HTTPD_CGI
1475 const char *prequest = request_GET;
1478 char *content_type = 0;
1483 struct sigaction sa;
1485 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1486 int credentials = -1; /* if not requred this is Ok */
1489 sa.sa_handler = handle_sigalrm;
1490 sigemptyset(&sa.sa_mask);
1491 sa.sa_flags = 0; /* no SA_RESTART */
1492 sigaction(SIGALRM, &sa, NULL);
1497 (void) alarm(TIMEOUT);
1501 purl = strpbrk(buf, " \t");
1504 sendHeaders(HTTP_BAD_REQUEST);
1508 #if ENABLE_FEATURE_HTTPD_CGI
1509 if (strcasecmp(buf, prequest) != 0) {
1511 if (strcasecmp(buf, prequest) != 0) {
1512 sendHeaders(HTTP_NOT_IMPLEMENTED);
1517 if (strcasecmp(buf, request_GET) != 0) {
1518 sendHeaders(HTTP_NOT_IMPLEMENTED);
1523 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1525 if (count < 1 || buf[0] != '/') {
1526 /* Garbled request/URL */
1529 url = alloca(strlen(buf) + 12); /* + sizeof("/index.html\0") */
1531 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1535 /* extract url args if present */
1536 test = strchr(url, '?');
1539 config->query = test;
1542 test = decodeString(url, 0);
1545 if (test == (buf+1)) {
1546 sendHeaders(HTTP_NOT_FOUND);
1549 /* algorithm stolen from libbb bb_simplify_path(),
1550 but don't strdup and reducing trailing slash and protect out root */
1555 if (*test == '/') { /* skip duplicate (or initial) slash */
1557 } else if (*test == '.') {
1558 if (test[1] == '/' || test[1] == 0) { /* skip extra '.' */
1560 } else if ((test[1] == '.') && (test[2] == '/' || test[2] == 0)) {
1563 /* protect out root */
1566 while (*--purl != '/') /* omit previous dir */;
1574 *++purl = 0; /* so keep last character */
1575 test = purl; /* end ptr */
1577 /* If URL is directory, adding '/' */
1578 if (test[-1] != '/') {
1579 if (is_directory(url + 1, 1, &sb)) {
1580 config->httpd_found.found_moved_temporarily = url;
1584 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1588 ip_allowed = checkPermIP();
1589 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1590 /* have path1/path2 */
1592 if (is_directory(url + 1, 1, &sb)) {
1593 /* may be having subdir config */
1594 parse_conf(url + 1, SUBDIR_PARSE);
1595 ip_allowed = checkPermIP();
1600 // read until blank line for HTTP version specified, else parse immediate
1608 fprintf(stderr, "Header: '%s'\n", buf);
1611 #if ENABLE_FEATURE_HTTPD_CGI
1612 /* try and do our best to parse more lines */
1613 if ((strncasecmp(buf, Content_length, 15) == 0)) {
1614 if (prequest != request_GET)
1615 length = strtol(buf + 15, 0, 0); // extra read only for POST
1616 } else if ((strncasecmp(buf, "Cookie:", 7) == 0)) {
1617 for (test = buf + 7; isspace(*test); test++)
1619 cookie = strdup(test);
1620 } else if ((strncasecmp(buf, "Content-Type:", 13) == 0)) {
1621 for (test = buf + 13; isspace(*test); test++)
1623 content_type = strdup(test);
1624 } else if ((strncasecmp(buf, "Referer:", 8) == 0)) {
1625 for (test = buf + 8; isspace(*test); test++)
1627 config->referer = strdup(test);
1631 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1632 if (strncasecmp(buf, "Authorization:", 14) == 0) {
1633 /* We only allow Basic credentials.
1634 * It shows up as "Authorization: Basic <userid:password>" where
1635 * the userid:password is base64 encoded.
1637 for (test = buf + 14; isspace(*test); test++)
1639 if (strncasecmp(test, "Basic", 5) != 0)
1642 test += 5; /* decodeBase64() skiping space self */
1644 credentials = checkPerm(url, test);
1646 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1648 } /* while extra header reading */
1651 if (config->alarm_signaled)
1654 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1655 /* protect listing [/path]/httpd_conf or IP deny */
1656 #if ENABLE_FEATURE_HTTPD_CGI
1657 FORBIDDEN: /* protect listing /cgi-bin */
1659 sendHeaders(HTTP_FORBIDDEN);
1663 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1664 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1665 sendHeaders(HTTP_UNAUTHORIZED);
1670 if (config->httpd_found.found_moved_temporarily) {
1671 sendHeaders(HTTP_MOVED_TEMPORARILY);
1673 /* clear unforked memory flag */
1674 config->httpd_found.found_moved_temporarily = NULL;
1679 test = url + 1; /* skip first '/' */
1681 #if ENABLE_FEATURE_HTTPD_CGI
1682 /* if strange Content-Length */
1686 if (strncmp(test, "cgi-bin", 7) == 0) {
1687 if (test[7] == '/' && test[8] == 0)
1688 goto FORBIDDEN; // protect listing cgi-bin/
1689 sendCgi(url, prequest, length, cookie, content_type);
1691 if (prequest != request_GET)
1692 sendHeaders(HTTP_NOT_IMPLEMENTED);
1694 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1695 if (purl[-1] == '/')
1696 strcpy(purl, "index.html");
1697 if (stat(test, &sb) == 0) {
1698 config->ContentLength = sb.st_size;
1699 config->last_mod = sb.st_mtime;
1702 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
1703 /* unset if non inetd looped */
1704 config->ContentLength = -1;
1707 #if ENABLE_FEATURE_HTTPD_CGI
1715 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
1716 /* from inetd don't looping: freeing, closing automatic from exit always */
1718 fprintf(stderr, "closing socket\n");
1720 # ifdef CONFIG_FEATURE_HTTPD_CGI
1723 free(config->referer);
1724 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1725 free(config->remoteuser);
1728 #endif /* CONFIG_FEATURE_HTTPD_WITHOUT_INETD */
1729 shutdown(a_c_w, SHUT_WR);
1731 /* Properly wait for remote to closed */
1733 FD_SET(a_c_r, &s_fd);
1738 retval = select(a_c_r + 1, &s_fd, NULL, NULL, &tv);
1739 } while (retval > 0 && read(a_c_r, buf, sizeof(config->buf) > 0));
1741 shutdown(a_c_r, SHUT_RD);
1742 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
1743 close(config->accepted_socket);
1744 #endif /* CONFIG_FEATURE_HTTPD_WITHOUT_INETD */
1747 /****************************************************************************
1749 > $Function: miniHttpd()
1751 * $Description: The main http server function.
1753 * Given an open socket fildes, listen for new connections and farm out
1754 * the processing as a forked process.
1757 * (int) server. . . The server socket fildes.
1759 * $Return: (int) . . . . Always 0.
1761 ****************************************************************************/
1762 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
1763 static int miniHttpd(int server)
1765 fd_set readfd, portfd;
1768 FD_SET(server, &portfd);
1770 /* copy the ports we are watching to the readfd set */
1774 /* Now wait INDEFINITELY on the set of sockets! */
1775 if (select(server + 1, &readfd, 0, 0, 0) > 0) {
1776 if (FD_ISSET(server, &readfd)) {
1778 struct sockaddr_in fromAddr;
1780 socklen_t fromAddrLen = sizeof(fromAddr);
1781 int s = accept(server,
1782 (struct sockaddr *)&fromAddr, &fromAddrLen);
1787 config->accepted_socket = s;
1788 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1789 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1790 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1791 (unsigned char)(config->rmt_ip >> 24),
1792 (unsigned char)(config->rmt_ip >> 16),
1793 (unsigned char)(config->rmt_ip >> 8),
1794 config->rmt_ip & 0xff);
1795 config->port = ntohs(fromAddr.sin_port);
1797 bb_error_msg("connection from IP=%s, port %u",
1798 config->rmt_ip_str, config->port);
1800 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1802 /* set the KEEPALIVE option to cull dead connections */
1804 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
1810 /* This is the spawned thread */
1811 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1812 /* protect reload config, may be confuse checking */
1813 signal(SIGHUP, SIG_IGN);
1830 static int miniHttpd(void)
1832 struct sockaddr_in fromAddrLen;
1833 socklen_t sinlen = sizeof(struct sockaddr_in);
1835 getpeername(0, (struct sockaddr *)&fromAddrLen, &sinlen);
1836 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1837 #if ENABLE_FEATURE_HTTPD_CGI
1838 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1839 (unsigned char)(config->rmt_ip >> 24),
1840 (unsigned char)(config->rmt_ip >> 16),
1841 (unsigned char)(config->rmt_ip >> 8),
1842 config->rmt_ip & 0xff);
1844 config->port = ntohs(fromAddrLen.sin_port);
1848 #endif /* CONFIG_FEATURE_HTTPD_WITHOUT_INETD */
1850 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1851 static void sighup_handler(int sig)
1854 struct sigaction sa;
1856 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1857 sa.sa_handler = sighup_handler;
1858 sigemptyset(&sa.sa_mask);
1859 sa.sa_flags = SA_RESTART;
1860 sigaction(SIGHUP, &sa, NULL);
1864 enum httpd_opts_nums {
1865 c_opt_config_file = 0,
1868 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1869 USE_FEATURE_HTTPD_BASIC_AUTH(r_opt_realm,)
1870 USE_FEATURE_HTTPD_AUTH_MD5(m_opt_md5,)
1871 USE_FEATURE_HTTPD_SETUID(u_opt_setuid,)
1872 USE_FEATURE_HTTPD_WITHOUT_INETD(p_opt_port,)
1875 static const char httpd_opts[] = "c:d:h:"
1876 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1877 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1878 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1879 USE_FEATURE_HTTPD_SETUID("u:")
1880 USE_FEATURE_HTTPD_WITHOUT_INETD("p:");
1882 #define OPT_CONFIG_FILE (1<<c_opt_config_file)
1883 #define OPT_DECODE_URL (1<<d_opt_decode_url)
1884 #define OPT_HOME_HTTPD (1<<h_opt_home_httpd)
1886 #define OPT_ENCODE_URL USE_FEATURE_HTTPD_ENCODE_URL_STR((1<<e_opt_encode_url)) \
1887 SKIP_FEATURE_HTTPD_ENCODE_URL_STR(0)
1889 #define OPT_REALM USE_FEATURE_HTTPD_BASIC_AUTH((1<<r_opt_realm)) \
1890 SKIP_FEATURE_HTTPD_BASIC_AUTH(0)
1892 #define OPT_MD5 USE_FEATURE_HTTPD_AUTH_MD5((1<<m_opt_md5)) \
1893 SKIP_FEATURE_HTTPD_AUTH_MD5(0)
1895 #define OPT_SETUID USE_FEATURE_HTTPD_SETUID((1<<u_opt_setuid)) \
1896 SKIP_FEATURE_HTTPD_SETUID(0)
1898 #define OPT_PORT USE_FEATURE_HTTPD_WITHOUT_INETD((1<<p_opt_port)) \
1899 SKIP_FEATURE_HTTPD_WITHOUT_INETD(0)
1902 int httpd_main(int argc, char *argv[])
1905 const char *home_httpd = home;
1906 char *url_for_decode;
1907 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1908 USE_FEATURE_HTTPD_WITHOUT_INETD(const char *s_port;)
1909 USE_FEATURE_HTTPD_WITHOUT_INETD(int server;)
1911 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1912 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1914 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1916 config = xzalloc(sizeof(*config));
1917 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1918 config->realm = "Web Server Authentication";
1921 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
1925 config->ContentLength = -1;
1927 opt = getopt32(argc, argv, httpd_opts,
1928 &(config->configFile), &url_for_decode, &home_httpd
1929 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1930 USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
1931 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1932 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1933 USE_FEATURE_HTTPD_WITHOUT_INETD(, &s_port)
1936 if (opt & OPT_DECODE_URL) {
1937 printf("%s", decodeString(url_for_decode, 1));
1940 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1941 if (opt & OPT_ENCODE_URL) {
1942 printf("%s", encodeString(url_for_encode));
1946 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1947 if (opt & OPT_MD5) {
1948 puts(pw_encrypt(pass, "$1$"));
1952 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
1954 config->port = xatou16(s_port);
1955 #if ENABLE_FEATURE_HTTPD_SETUID
1956 if (opt & OPT_SETUID) {
1958 // FIXME: what the default group should be?
1960 ugid.uid = strtoul(s_ugid, &e, 0);
1963 ugid.gid = strtoul(e, &e, 0);
1967 if (!uidgid_get(&ugid, s_ugid))
1968 bb_error_msg_and_die("unrecognized user[:group] "
1969 "name '%s'", s_ugid);
1976 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
1977 server = openServer();
1978 # ifdef CONFIG_FEATURE_HTTPD_SETUID
1979 /* drop privileges */
1980 if (opt & OPT_SETUID) {
1981 if (ugid.gid != (gid_t)-1) {
1983 //if (setgroups(1, &ugid.gid) == -1)
1984 // bb_perror_msg_and_die("setgroups");
1992 #if ENABLE_FEATURE_HTTPD_CGI
1994 char *p = getenv("PATH");
2000 setenv("PATH", p, 1);
2001 # ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
2002 addEnvPort("SERVER");
2007 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2010 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2013 #if ENABLE_FEATURE_HTTPD_WITHOUT_INETD
2015 xdaemon(1, 0); /* don't change curent directory */
2017 return miniHttpd(server);