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[] = "./";
101 # define cont_l_fmt "%lld"
102 # define cont_l_type (long long)
104 # define cont_l_fmt "%ld"
105 # define cont_l_type (long)
110 // Note: busybox xfuncs are not used because we want the server to keep running
111 // if something bad happens due to a malformed user request.
112 // As a result, all memory allocation after daemonize
113 // is checked rigorously
121 #define MAX_MEMORY_BUFF 8192 /* IO buffer */
123 typedef struct HT_ACCESS {
125 struct HT_ACCESS *next;
126 char before_colon[1]; /* really bigger, must last */
129 typedef struct HT_ACCESS_IP {
133 struct HT_ACCESS_IP *next;
138 char buf[MAX_MEMORY_BUFF];
140 USE_FEATURE_HTTPD_BASIC_AUTH(const char *realm;)
141 USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
145 USE_FEATURE_HTTPD_CGI(char *referer;)
147 const char *configFile;
150 #if defined(CONFIG_FEATURE_HTTPD_CGI) || DEBUG
151 char rmt_ip_str[16]; /* for set env REMOTE_ADDR */
153 unsigned port; /* server initial port and for
154 set env REMOTE_PORT */
156 const char *found_mime_type;
157 const char *found_moved_temporarily;
160 off_t ContentLength; /* -1 - unknown */
163 Htaccess_IP *ip_a_d; /* config allow/deny lines */
165 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
166 Htaccess *auth; /* config user:password lines */
168 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
169 Htaccess *mime_a; /* config mime types */
172 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
174 # define a_c_r config->accepted_socket
175 # define a_c_w config->accepted_socket
180 volatile int alarm_signaled;
182 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
183 Htaccess *script_i; /* config script interpreters */
187 static HttpdConfig *config;
189 static const char request_GET[] = "GET"; /* size algorithmic optimize */
191 static const char* const suffixTable [] = {
192 /* Warning: shorted equivalent suffix in one line must be first */
193 ".htm.html", "text/html",
194 ".jpg.jpeg", "image/jpeg",
197 ".txt.h.c.cc.cpp", "text/plain",
200 ".avi", "video/x-msvideo",
201 ".qt.mov", "video/quicktime",
202 ".mpe.mpeg", "video/mpeg",
203 ".mid.midi", "audio/midi",
204 ".mp3", "audio/mpeg",
205 #if 0 /* unpopular */
206 ".au", "audio/basic",
207 ".pac", "application/x-ns-proxy-autoconfig",
208 ".vrml.wrl", "model/vrml",
210 0, "application/octet-stream" /* default */
216 HTTP_MOVED_TEMPORARILY = 302,
217 HTTP_BAD_REQUEST = 400, /* malformed syntax */
218 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
219 HTTP_NOT_FOUND = 404,
220 HTTP_FORBIDDEN = 403,
221 HTTP_REQUEST_TIMEOUT = 408,
222 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
223 HTTP_INTERNAL_SERVER_ERROR = 500,
224 #if 0 /* future use */
226 HTTP_SWITCHING_PROTOCOLS = 101,
229 HTTP_NON_AUTHORITATIVE_INFO = 203,
230 HTTP_NO_CONTENT = 204,
231 HTTP_MULTIPLE_CHOICES = 300,
232 HTTP_MOVED_PERMANENTLY = 301,
233 HTTP_NOT_MODIFIED = 304,
234 HTTP_PAYMENT_REQUIRED = 402,
235 HTTP_BAD_GATEWAY = 502,
236 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
237 HTTP_RESPONSE_SETSIZE=0xffffffff
243 HttpResponseNum type;
248 static const HttpEnumString httpResponseNames[] = {
249 { HTTP_OK, "OK", NULL },
250 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
251 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
252 "No request appeared within a reasonable time period." },
253 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
254 "The requested method is not recognized by this server." },
255 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
256 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
258 { HTTP_NOT_FOUND, "Not Found",
259 "The requested URL was not found on this server." },
260 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
261 { HTTP_FORBIDDEN, "Forbidden", "" },
262 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
263 "Internal Server Error" },
264 #if 0 /* not implemented */
265 { HTTP_CREATED, "Created" },
266 { HTTP_ACCEPTED, "Accepted" },
267 { HTTP_NO_CONTENT, "No Content" },
268 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
269 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
270 { HTTP_NOT_MODIFIED, "Not Modified" },
271 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
272 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
277 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
278 static const char Content_length[] = "Content-length:";
282 scan_ip (const char **ep, unsigned int *ip, unsigned char endc)
289 for (j = 0; j < 4; j++) {
292 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
295 while (*p >= '0' && *p <= '9') {
304 if (*p != '/' && *p != 0)
306 *ip = ((*ip) << 8) | octet;
320 scan_ip_mask (const char *ipm, unsigned int *ip, unsigned int *mask)
325 i = scan_ip(&ipm, ip, '/');
333 if (*p < '0' || *p > '9') {
335 i = scan_ip (&ipm, mask, 0);
357 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
358 static void free_config_lines(Htaccess **pprev)
360 Htaccess *prev = *pprev;
363 Htaccess *cur = prev;
373 #define FIRST_PARSE 0
374 #define SUBDIR_PARSE 1
375 #define SIGNALED_PARSE 2
376 #define FIND_FROM_HTTPD_ROOT 3
377 /****************************************************************************
379 > $Function: parse_conf()
381 * $Description: parse configuration file into in-memory linked list.
383 * The first non-white character is examined to determine if the config line
384 * is one of the following:
385 * .ext:mime/type # new mime type not compiled into httpd
386 * [adAD]:from # ip address allow/deny, * for wildcard
387 * /path:user:pass # username/password
389 * Any previous IP rules are discarded.
390 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
391 * are also discarded. That is, previous settings are retained if flag is
395 * (const char *) path . . null for ip address checks, path for password
397 * (int) flag . . . . . . the source of the parse request.
401 ****************************************************************************/
402 static void parse_conf(const char *path, int flag)
405 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
406 Htaccess *prev, *cur;
407 #elif CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
411 const char *cf = config->configFile;
416 /* free previous ip setup if present */
417 Htaccess_IP *pip = config->ip_a_d;
420 Htaccess_IP *cur_ipl = pip;
425 config->ip_a_d = NULL;
427 config->flg_deny_all = 0;
429 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR)
430 /* retain previous auth and mime config only for subdir parse */
431 if(flag != SUBDIR_PARSE) {
432 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
433 free_config_lines(&config->auth);
435 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
436 free_config_lines(&config->mime_a);
438 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
439 free_config_lines(&config->script_i);
444 if(flag == SUBDIR_PARSE || cf == NULL) {
445 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
447 if(flag == FIRST_PARSE)
448 bb_error_msg_and_die(bb_msg_memory_exhausted);
451 sprintf((char *)cf, "%s/%s", path, httpd_conf);
454 while((f = fopen(cf, "r")) == NULL) {
455 if(flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
456 /* config file not found, no changes to config */
459 if(config->configFile && flag == FIRST_PARSE) /* if -c option given */
460 bb_perror_msg_and_die("%s", cf);
461 flag = FIND_FROM_HTTPD_ROOT;
465 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
468 /* This could stand some work */
469 while ( (p0 = fgets(buf, sizeof(buf), f)) != NULL) {
471 for(p = p0; *p0 != 0 && *p0 != '#'; p0++) {
474 if(*p0 == ':' && c == NULL)
480 /* test for empty or strange line */
481 if (c == NULL || *c == 0)
488 /* memorize deny all */
489 config->flg_deny_all++;
491 /* skip default other "word:*" config lines */
497 else if(*p0 != 'D' && *p0 != 'A'
498 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
501 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
504 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
509 if(*p0 == 'A' || *p0 == 'D') {
510 /* storing current config IP line */
511 pip = calloc(1, sizeof(Htaccess_IP));
513 if(scan_ip_mask (c, &(pip->ip), &(pip->mask))) {
514 /* syntax IP{/mask} error detected, protect all */
518 pip->allow_deny = *p0;
520 /* Deny:form_IP move top */
521 pip->next = config->ip_a_d;
522 config->ip_a_d = pip;
524 /* add to bottom A:form_IP config line */
525 Htaccess_IP *prev_IP = config->ip_a_d;
527 if(prev_IP == NULL) {
528 config->ip_a_d = pip;
531 prev_IP = prev_IP->next;
538 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
540 /* make full path from httpd root / curent_path / config_line_path */
541 cf = flag == SUBDIR_PARSE ? path : "";
542 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
546 sprintf(p0, "/%s%s", cf, buf);
548 /* another call bb_simplify_path */
553 if (*cf == '/') { /* skip duplicate (or initial) slash */
555 } else if (*cf == '.') {
556 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
558 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
561 while (*--p != '/'); /* omit previous dir */
570 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
571 ++p; /* so keep last character */
574 sprintf(p0, "%s:%s", p0, c);
578 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR)
579 /* storing current config line */
580 cur = calloc(1, sizeof(Htaccess) + strlen(p0));
582 cf = strcpy(cur->before_colon, p0);
585 cur->after_colon = c;
586 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
588 /* config .mime line move top for overwrite previous */
589 cur->next = config->mime_a;
590 config->mime_a = cur;
594 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
595 if(*cf == '*' && cf[1] == '.') {
596 /* config script interpreter line move top for overwrite previous */
597 cur->next = config->script_i;
598 config->script_i = cur;
602 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
606 config->auth = prev = cur;
608 /* sort path, if current lenght eq or bigger then move up */
609 Htaccess *prev_hti = config->auth;
610 size_t l = strlen(cf);
613 for(hti = prev_hti; hti; hti = hti->next) {
614 if(l >= strlen(hti->before_colon)) {
615 /* insert before hti */
617 if(prev_hti != hti) {
618 prev_hti->next = cur;
626 prev_hti = prev_hti->next;
628 if(!hti) { /* not inserted, add to bottom */
640 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
641 /****************************************************************************
643 > $Function: encodeString()
645 * $Description: Given a string, html encode special characters.
646 * This is used for the -e command line option to provide an easy way
647 * for scripts to encode result data without confusing browsers. The
648 * returned string pointer is memory allocated by malloc().
651 * (const char *) string . . The first string to encode.
653 * $Return: (char *) . . . .. . . A pointer to the encoded string.
655 * $Errors: Returns a null string ("") if memory is not available.
657 ****************************************************************************/
658 static char *encodeString(const char *string)
660 /* take the simple route and encode everything */
661 /* could possibly scan once to get length. */
662 int len = strlen(string);
663 char *out = malloc(len * 6 + 1);
668 while ((ch = *string++)) {
669 // very simple check for what to encode
670 if (isalnum(ch)) *p++ = ch;
671 else p += sprintf(p, "&#%d;", (unsigned char) ch);
676 #endif /* CONFIG_FEATURE_HTTPD_ENCODE_URL_STR */
678 /****************************************************************************
680 > $Function: decodeString()
682 * $Description: Given a URL encoded string, convert it to plain ascii.
683 * Since decoding always makes strings smaller, the decode is done in-place.
684 * Thus, callers should strdup() the argument if they do not want the
685 * argument modified. The return is the original pointer, allowing this
686 * function to be easily used as arguments to other functions.
689 * (char *) string . . . The first string to decode.
690 * (int) flag . . . 1 if require decode '+' as ' ' for CGI
692 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
696 ****************************************************************************/
697 static char *decodeString(char *orig, int flag_plus_to_space)
699 /* note that decoded string is always shorter than original */
705 if (*ptr == '+' && flag_plus_to_space) { *string++ = ' '; ptr++; }
706 else if (*ptr != '%') *string++ = *ptr++;
708 unsigned int value1, value2;
711 if(sscanf(ptr, "%1X", &value1) != 1 ||
712 sscanf(ptr+1, "%1X", &value2) != 1) {
713 if(!flag_plus_to_space)
717 value1 = value1 * 16 + value2;
718 if(value1 == '/' || value1 == 0)
730 #ifdef CONFIG_FEATURE_HTTPD_CGI
731 /****************************************************************************
733 > $Function: addEnv()
735 * $Description: Add an environment variable setting to the global list.
736 * A NAME=VALUE string is allocated, filled, and added to the list of
737 * environment settings passed to the cgi execution script.
740 * (char *) name_before_underline - The first part environment variable name.
741 * (char *) name_after_underline - The second part environment variable name.
742 * (char *) value . . The value to which the env variable is set.
746 * $Errors: Silently returns if the env runs out of space to hold the new item
748 ****************************************************************************/
749 static void addEnv(const char *name_before_underline,
750 const char *name_after_underline, const char *value)
753 const char *underline;
757 underline = *name_after_underline ? "_" : "";
758 asprintf(&s, "%s%s%s=%s", name_before_underline, underline,
759 name_after_underline, value);
765 #if defined(CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV) || defined(CONFIG_FEATURE_HTTPD_WITHOUT_INETD)
766 /* set environs SERVER_PORT and REMOTE_PORT */
767 static void addEnvPort(const char *port_name)
771 sprintf(buf, "%u", config->port);
772 addEnv(port_name, "PORT", buf);
775 #endif /* CONFIG_FEATURE_HTTPD_CGI */
778 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
779 /****************************************************************************
781 > $Function: decodeBase64()
783 > $Description: Decode a base 64 data stream as per rfc1521.
784 * Note that the rfc states that none base64 chars are to be ignored.
785 * Since the decode always results in a shorter size than the input, it is
786 * OK to pass the input arg as an output arg.
789 * (char *) Data . . . . A pointer to a base64 encoded string.
790 * Where to place the decoded data.
796 ****************************************************************************/
797 static void decodeBase64(char *Data)
800 const unsigned char *in = (const unsigned char *)Data;
801 // The decoded size will be at most 3/4 the size of the encoded
802 unsigned long ch = 0;
808 if(t >= '0' && t <= '9')
810 else if(t >= 'A' && t <= 'Z')
812 else if(t >= 'a' && t <= 'z')
826 *Data++ = (char) (ch >> 16);
827 *Data++ = (char) (ch >> 8);
837 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
838 /****************************************************************************
840 > $Function: openServer()
842 * $Description: create a listen server socket on the designated port.
844 * $Return: (int) . . . A connection socket. -1 for errors.
848 ****************************************************************************/
849 static int openServer(void)
851 struct sockaddr_in lsocket;
855 /* create the socket right now */
856 /* inet_addr() returns a value that is already in network order */
857 memset(&lsocket, 0, sizeof(lsocket));
858 lsocket.sin_family = AF_INET;
859 lsocket.sin_addr.s_addr = INADDR_ANY;
860 lsocket.sin_port = htons(config->port);
861 fd = xsocket(AF_INET, SOCK_STREAM, 0);
862 /* tell the OS it's OK to reuse a previous address even though */
863 /* it may still be in a close down state. Allows bind to succeed. */
865 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on)) ;
867 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)) ;
869 xbind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket));
871 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
874 #endif /* CONFIG_FEATURE_HTTPD_WITHOUT_INETD */
876 /****************************************************************************
878 > $Function: sendHeaders()
880 * $Description: Create and send HTTP response headers.
881 * The arguments are combined and sent as one write operation. Note that
882 * IE will puke big-time if the headers are not sent in one packet and the
883 * second packet is delayed for any reason.
886 * (HttpResponseNum) responseNum . . . The result code to send.
888 * $Return: (int) . . . . writing errors
890 ****************************************************************************/
891 static int sendHeaders(HttpResponseNum responseNum)
893 char *buf = config->buf;
894 const char *responseString = "";
895 const char *infoString = 0;
896 const char *mime_type;
898 time_t timer = time(0);
903 i < (sizeof(httpResponseNames)/sizeof(httpResponseNames[0])); i++) {
904 if (httpResponseNames[i].type == responseNum) {
905 responseString = httpResponseNames[i].name;
906 infoString = httpResponseNames[i].info;
910 /* error message is HTML */
911 mime_type = responseNum == HTTP_OK ?
912 config->httpd_found.found_mime_type : "text/html";
914 /* emit the current date */
915 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
917 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
918 "Date: %s\r\nConnection: close\r\n",
919 responseNum, responseString, mime_type, timeStr);
921 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
922 if (responseNum == HTTP_UNAUTHORIZED) {
923 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
927 if(responseNum == HTTP_MOVED_TEMPORARILY) {
928 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
929 config->httpd_found.found_moved_temporarily,
930 (config->query ? "?" : ""),
931 (config->query ? config->query : ""));
934 if (config->ContentLength != -1) { /* file */
935 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
936 len += sprintf(buf+len, "Last-Modified: %s\r\n%s " cont_l_fmt "\r\n",
937 timeStr, Content_length, cont_l_type config->ContentLength);
942 len += sprintf(buf+len,
943 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
944 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
945 responseNum, responseString,
946 responseNum, responseString, infoString);
949 fprintf(stderr, "Headers: '%s'", buf);
951 return full_write(a_c_w, buf, len);
954 /****************************************************************************
956 > $Function: getLine()
958 * $Description: Read from the socket until an end of line char found.
960 * Characters are read one at a time until an eol sequence is found.
962 * $Return: (int) . . . . number of characters read. -1 if error.
964 ****************************************************************************/
965 static int getLine(void)
968 char *buf = config->buf;
970 while (read(a_c_r, buf + count, 1) == 1) {
971 if (buf[count] == '\r') continue;
972 if (buf[count] == '\n') {
976 if(count < (MAX_MEMORY_BUFF-1)) /* check owerflow */
979 if (count) return count;
983 #ifdef CONFIG_FEATURE_HTTPD_CGI
984 /****************************************************************************
986 > $Function: sendCgi()
988 * $Description: Execute a CGI script and send it's stdout back
990 * Environment variables are set up and the script is invoked with pipes
991 * for stdin/stdout. If a post is being done the script is fed the POST
992 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
995 * (const char *) url . . . . . . The requested URL (with leading /).
996 * (int bodyLen) . . . . . . . . Length of the post body.
997 * (const char *cookie) . . . . . For set HTTP_COOKIE.
998 * (const char *content_type) . . For set CONTENT_TYPE.
1001 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
1005 ****************************************************************************/
1006 static int sendCgi(const char *url,
1007 const char *request, int bodyLen, const char *cookie,
1008 const char *content_type)
1010 int fromCgi[2]; /* pipe for reading data from CGI */
1011 int toCgi[2]; /* pipe for sending data to CGI */
1013 static char * argp[] = { 0, 0 };
1020 if (pipe(fromCgi) != 0) {
1023 if (pipe(toCgi) != 0) {
1036 char *purl = strdup( url );
1037 char realpath_buff[MAXPATHLEN];
1045 dup2(inFd, 0); // replace stdin with the pipe
1046 dup2(outFd, 1); // replace stdout with the pipe
1048 dup2(outFd, 2); // replace stderr with the pipe
1059 while((script = strchr( script + 1, '/' )) != NULL) {
1060 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1064 if(is_directory(purl + 1, 1, &sb) == 0) {
1065 /* not directory, found script.cgi/PATH_INFO */
1069 *script = '/'; /* is directory, find next '/' */
1071 addEnv("PATH", "INFO", script); /* set /PATH_INFO or NULL */
1072 addEnv("PATH", "", getenv("PATH"));
1073 addEnv("REQUEST", "METHOD", request);
1075 char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
1077 sprintf(uri, "%s?%s", purl, config->query);
1078 addEnv("REQUEST", "URI", uri);
1080 addEnv("REQUEST", "URI", purl);
1083 *script = '\0'; /* reduce /PATH_INFO */
1084 /* SCRIPT_FILENAME required by PHP in CGI mode */
1085 if(realpath(purl + 1, realpath_buff))
1086 addEnv("SCRIPT", "FILENAME", realpath_buff);
1089 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1090 addEnv("SCRIPT_NAME", "", purl);
1091 addEnv("QUERY_STRING", "", config->query);
1092 addEnv("SERVER", "SOFTWARE", httpdVersion);
1093 addEnv("SERVER", "PROTOCOL", "HTTP/1.0");
1094 addEnv("GATEWAY_INTERFACE", "", "CGI/1.1");
1095 addEnv("REMOTE", "ADDR", config->rmt_ip_str);
1096 #ifdef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1097 addEnvPort("REMOTE");
1102 sprintf(sbl, "%d", bodyLen);
1103 addEnv("CONTENT", "LENGTH", sbl);
1106 addEnv("HTTP", "COOKIE", cookie);
1108 addEnv("CONTENT", "TYPE", content_type);
1109 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1110 if(config->remoteuser) {
1111 addEnv("REMOTE", "USER", config->remoteuser);
1112 addEnv("AUTH_TYPE", "", "Basic");
1116 addEnv("HTTP", "REFERER", config->referer);
1118 /* set execve argp[0] without path */
1119 argp[0] = strrchr( purl, '/' ) + 1;
1120 /* but script argp[0] must have absolute path and chdiring to this */
1121 if(*realpath_buff) {
1122 script = strrchr(realpath_buff, '/');
1125 if(chdir(realpath_buff) == 0) {
1126 // now run the program. If it fails,
1127 // use _exit() so no destructors
1128 // get called and make a mess.
1129 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1130 char *interpr = NULL;
1131 char *suffix = strrchr(purl, '.');
1135 for (cur = config->script_i; cur; cur = cur->next)
1136 if(strcmp(cur->before_colon + 1, suffix) == 0) {
1137 interpr = cur->after_colon;
1143 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1145 execv(interpr, argp);
1148 execv(realpath_buff, argp);
1152 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
1153 config->accepted_socket = 1; /* send to stdout */
1155 sendHeaders(HTTP_NOT_FOUND);
1162 /* parent process */
1164 size_t post_readed_size = 0, post_readed_idx = 0;
1170 signal(SIGPIPE, SIG_IGN);
1181 FD_SET(inFd, &readSet);
1182 if(bodyLen > 0 || post_readed_size > 0) {
1183 FD_SET(outFd, &writeSet);
1184 nfound = outFd > inFd ? outFd : inFd;
1185 if(post_readed_size == 0) {
1186 FD_SET(a_c_r, &readSet);
1190 /* Now wait on the set of sockets! */
1191 nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
1197 nfound = select(inFd + 1, &readSet, 0, 0, NULL);
1201 if (waitpid(pid, &status, WNOHANG) > 0) {
1204 if (WIFEXITED(status))
1205 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1206 if (WIFSIGNALED(status))
1207 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1211 } else if(post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1212 count = full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1214 post_readed_size -= count;
1215 post_readed_idx += count;
1216 if(post_readed_size == 0)
1217 post_readed_idx = 0;
1219 post_readed_size = post_readed_idx = bodyLen = 0; /* broken pipe to CGI */
1221 } else if(bodyLen > 0 && post_readed_size == 0 && FD_ISSET(a_c_r, &readSet)) {
1222 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1223 count = safe_read(a_c_r, wbuf, count);
1225 post_readed_size += count;
1228 bodyLen = 0; /* closed */
1231 if(FD_ISSET(inFd, &readSet)) {
1233 char *rbuf = config->buf;
1236 # define PIPESIZE 4096 /* amount of buffering in a pipe */
1238 # define PIPESIZE PIPE_BUF
1240 #if PIPESIZE >= MAX_MEMORY_BUFF
1241 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1244 // There is something to read
1245 count = safe_read(inFd, rbuf, PIPESIZE);
1251 /* check to see if the user script added headers */
1252 if(strncmp(rbuf, "HTTP/1.0 200 OK\r\n", 4) != 0) {
1253 full_write(s, "HTTP/1.0 200 OK\r\n", 17);
1255 if (strstr(rbuf, "ontent-") == 0) {
1256 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1260 if (full_write(s, rbuf, count) != count)
1264 fprintf(stderr, "cgi read %d bytes\n", count);
1272 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1274 /****************************************************************************
1276 > $Function: sendFile()
1278 * $Description: Send a file response to an HTTP request
1281 * (const char *) url . . The URL requested.
1283 * $Return: (int) . . . . . . Always 0.
1285 ****************************************************************************/
1286 static int sendFile(const char *url)
1290 const char * const * table;
1291 const char * try_suffix;
1293 suffix = strrchr(url, '.');
1295 for (table = suffixTable; *table; table += 2)
1296 if(suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1297 try_suffix += strlen(suffix);
1298 if(*try_suffix == 0 || *try_suffix == '.')
1301 /* also, if not found, set default as "application/octet-stream"; */
1302 config->httpd_found.found_mime_type = *(table+1);
1303 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1307 for (cur = config->mime_a; cur; cur = cur->next) {
1308 if(strcmp(cur->before_colon, suffix) == 0) {
1309 config->httpd_found.found_mime_type = cur->after_colon;
1314 #endif /* CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1317 fprintf(stderr, "Sending file '%s' Content-type: %s\n",
1318 url, config->httpd_found.found_mime_type);
1321 f = open(url, O_RDONLY);
1324 char *buf = config->buf;
1326 sendHeaders(HTTP_OK);
1327 while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1328 if (full_write(a_c_w, buf, count) != count)
1334 bb_perror_msg("Unable to open '%s'", url);
1336 sendHeaders(HTTP_NOT_FOUND);
1342 static int checkPermIP(void)
1346 /* This could stand some work */
1347 for (cur = config->ip_a_d; cur; cur = cur->next) {
1349 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1350 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1351 (unsigned char)(cur->ip >> 24),
1352 (unsigned char)(cur->ip >> 16),
1353 (unsigned char)(cur->ip >> 8),
1355 (unsigned char)(cur->mask >> 24),
1356 (unsigned char)(cur->mask >> 16),
1357 (unsigned char)(cur->mask >> 8),
1360 if((config->rmt_ip & cur->mask) == cur->ip)
1361 return cur->allow_deny == 'A'; /* Allow/Deny */
1364 /* if unconfigured, return 1 - access from all */
1365 return !config->flg_deny_all;
1368 /****************************************************************************
1370 > $Function: checkPerm()
1372 * $Description: Check the permission file for access password protected.
1374 * If config file isn't present, everything is allowed.
1375 * Entries are of the form you can see example from header source
1378 * (const char *) path . . . . The file path.
1379 * (const char *) request . . . User information to validate.
1381 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1383 ****************************************************************************/
1385 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1386 static int checkPerm(const char *path, const char *request)
1392 const char *prev = NULL;
1394 /* This could stand some work */
1395 for (cur = config->auth; cur; cur = cur->next) {
1396 p0 = cur->before_colon;
1397 if(prev != NULL && strcmp(prev, p0) != 0)
1398 continue; /* find next identical */
1399 p = cur->after_colon;
1401 fprintf(stderr,"checkPerm: '%s' ? '%s'\n", p0, request);
1404 size_t l = strlen(p0);
1406 if(strncmp(p0, path, l) == 0 &&
1407 (l == 1 || path[l] == '/' || path[l] == 0)) {
1409 /* path match found. Check request */
1410 /* for check next /path:user:password */
1412 u = strchr(request, ':');
1414 /* bad request, ':' required */
1418 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1423 if(strncmp(p, request, u-request) != 0) {
1424 /* user uncompared */
1427 pp = strchr(p, ':');
1428 if(pp && pp[1] == '$' && pp[2] == '1' &&
1429 pp[3] == '$' && pp[4]) {
1431 cipher = pw_encrypt(u+1, pp);
1432 if (strcmp(cipher, pp) == 0)
1433 goto set_remoteuser_var; /* Ok */
1439 if (strcmp(p, request) == 0) {
1440 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1443 config->remoteuser = strdup(request);
1444 if(config->remoteuser)
1445 config->remoteuser[(u - request)] = 0;
1453 return prev == NULL;
1456 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1458 /****************************************************************************
1460 > $Function: handle_sigalrm()
1462 * $Description: Handle timeouts
1464 ****************************************************************************/
1467 handle_sigalrm( int sig )
1469 sendHeaders(HTTP_REQUEST_TIMEOUT);
1470 config->alarm_signaled = sig;
1473 /****************************************************************************
1475 > $Function: handleIncoming()
1477 * $Description: Handle an incoming http request.
1479 ****************************************************************************/
1480 static void handleIncoming(void)
1482 char *buf = config->buf;
1489 #ifdef CONFIG_FEATURE_HTTPD_CGI
1490 const char *prequest = request_GET;
1493 char *content_type = 0;
1498 struct sigaction sa;
1500 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1501 int credentials = -1; /* if not requred this is Ok */
1504 sa.sa_handler = handle_sigalrm;
1505 sigemptyset(&sa.sa_mask);
1506 sa.sa_flags = 0; /* no SA_RESTART */
1507 sigaction(SIGALRM, &sa, NULL);
1512 (void) alarm( TIMEOUT );
1516 purl = strpbrk(buf, " \t");
1519 sendHeaders(HTTP_BAD_REQUEST);
1523 #ifdef CONFIG_FEATURE_HTTPD_CGI
1524 if(strcasecmp(buf, prequest) != 0) {
1526 if(strcasecmp(buf, prequest) != 0) {
1527 sendHeaders(HTTP_NOT_IMPLEMENTED);
1532 if(strcasecmp(buf, request_GET) != 0) {
1533 sendHeaders(HTTP_NOT_IMPLEMENTED);
1538 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1540 if (count < 1 || buf[0] != '/') {
1541 /* Garbled request/URL */
1544 url = alloca(strlen(buf) + 12); /* + sizeof("/index.html\0") */
1546 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1550 /* extract url args if present */
1551 test = strchr(url, '?');
1554 config->query = test;
1557 test = decodeString(url, 0);
1560 if(test == (buf+1)) {
1561 sendHeaders(HTTP_NOT_FOUND);
1564 /* algorithm stolen from libbb bb_simplify_path(),
1565 but don`t strdup and reducing trailing slash and protect out root */
1570 if (*test == '/') { /* skip duplicate (or initial) slash */
1572 } else if (*test == '.') {
1573 if (test[1] == '/' || test[1] == 0) { /* skip extra '.' */
1575 } else if ((test[1] == '.') && (test[2] == '/' || test[2] == 0)) {
1578 /* protect out root */
1581 while (*--purl != '/'); /* omit previous dir */
1589 *++purl = 0; /* so keep last character */
1590 test = purl; /* end ptr */
1592 /* If URL is directory, adding '/' */
1593 if(test[-1] != '/') {
1594 if ( is_directory(url + 1, 1, &sb) ) {
1595 config->httpd_found.found_moved_temporarily = url;
1599 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1603 ip_allowed = checkPermIP();
1604 while(ip_allowed && (test = strchr( test + 1, '/' )) != NULL) {
1605 /* have path1/path2 */
1607 if( is_directory(url + 1, 1, &sb) ) {
1608 /* may be having subdir config */
1609 parse_conf(url + 1, SUBDIR_PARSE);
1610 ip_allowed = checkPermIP();
1615 // read until blank line for HTTP version specified, else parse immediate
1623 fprintf(stderr, "Header: '%s'\n", buf);
1626 #ifdef CONFIG_FEATURE_HTTPD_CGI
1627 /* try and do our best to parse more lines */
1628 if ((strncasecmp(buf, Content_length, 15) == 0)) {
1629 if(prequest != request_GET)
1630 length = strtol(buf + 15, 0, 0); // extra read only for POST
1631 } else if ((strncasecmp(buf, "Cookie:", 7) == 0)) {
1632 for(test = buf + 7; isspace(*test); test++)
1634 cookie = strdup(test);
1635 } else if ((strncasecmp(buf, "Content-Type:", 13) == 0)) {
1636 for(test = buf + 13; isspace(*test); test++)
1638 content_type = strdup(test);
1639 } else if ((strncasecmp(buf, "Referer:", 8) == 0)) {
1640 for(test = buf + 8; isspace(*test); test++)
1642 config->referer = strdup(test);
1646 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1647 if (strncasecmp(buf, "Authorization:", 14) == 0) {
1648 /* We only allow Basic credentials.
1649 * It shows up as "Authorization: Basic <userid:password>" where
1650 * the userid:password is base64 encoded.
1652 for(test = buf + 14; isspace(*test); test++)
1654 if (strncasecmp(test, "Basic", 5) != 0)
1657 test += 5; /* decodeBase64() skiping space self */
1659 credentials = checkPerm(url, test);
1661 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1663 } /* while extra header reading */
1666 if(config->alarm_signaled)
1669 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1670 /* protect listing [/path]/httpd_conf or IP deny */
1671 #ifdef CONFIG_FEATURE_HTTPD_CGI
1672 FORBIDDEN: /* protect listing /cgi-bin */
1674 sendHeaders(HTTP_FORBIDDEN);
1678 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1679 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1680 sendHeaders(HTTP_UNAUTHORIZED);
1685 if(config->httpd_found.found_moved_temporarily) {
1686 sendHeaders(HTTP_MOVED_TEMPORARILY);
1688 /* clear unforked memory flag */
1689 config->httpd_found.found_moved_temporarily = NULL;
1694 test = url + 1; /* skip first '/' */
1696 #ifdef CONFIG_FEATURE_HTTPD_CGI
1697 /* if strange Content-Length */
1701 if (strncmp(test, "cgi-bin", 7) == 0) {
1702 if(test[7] == '/' && test[8] == 0)
1703 goto FORBIDDEN; // protect listing cgi-bin/
1704 sendCgi(url, prequest, length, cookie, content_type);
1706 if (prequest != request_GET)
1707 sendHeaders(HTTP_NOT_IMPLEMENTED);
1709 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1711 strcpy(purl, "index.html");
1712 if ( stat(test, &sb ) == 0 ) {
1713 config->ContentLength = sb.st_size;
1714 config->last_mod = sb.st_mtime;
1717 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
1718 /* unset if non inetd looped */
1719 config->ContentLength = -1;
1722 #ifdef CONFIG_FEATURE_HTTPD_CGI
1730 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
1731 /* from inetd don`t looping: freeing, closing automatic from exit always */
1733 fprintf(stderr, "closing socket\n");
1735 # ifdef CONFIG_FEATURE_HTTPD_CGI
1738 free(config->referer);
1739 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1740 free(config->remoteuser);
1743 #endif /* CONFIG_FEATURE_HTTPD_WITHOUT_INETD */
1744 shutdown(a_c_w, SHUT_WR);
1746 /* Properly wait for remote to closed */
1748 FD_SET (a_c_r, &s_fd) ;
1753 retval = select (a_c_r + 1, &s_fd, NULL, NULL, &tv);
1754 } while (retval > 0 && (read (a_c_r, buf, sizeof (config->buf)) > 0));
1756 shutdown(a_c_r, SHUT_RD);
1757 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
1758 close(config->accepted_socket);
1759 #endif /* CONFIG_FEATURE_HTTPD_WITHOUT_INETD */
1762 /****************************************************************************
1764 > $Function: miniHttpd()
1766 * $Description: The main http server function.
1768 * Given an open socket fildes, listen for new connections and farm out
1769 * the processing as a forked process.
1772 * (int) server. . . The server socket fildes.
1774 * $Return: (int) . . . . Always 0.
1776 ****************************************************************************/
1777 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
1778 static int miniHttpd(int server)
1780 fd_set readfd, portfd;
1783 FD_SET(server, &portfd);
1785 /* copy the ports we are watching to the readfd set */
1789 /* Now wait INDEFINITELY on the set of sockets! */
1790 if (select(server + 1, &readfd, 0, 0, 0) > 0) {
1791 if (FD_ISSET(server, &readfd)) {
1793 struct sockaddr_in fromAddr;
1795 socklen_t fromAddrLen = sizeof(fromAddr);
1796 int s = accept(server,
1797 (struct sockaddr *)&fromAddr, &fromAddrLen);
1802 config->accepted_socket = s;
1803 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1804 #if defined(CONFIG_FEATURE_HTTPD_CGI) || DEBUG
1805 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1806 (unsigned char)(config->rmt_ip >> 24),
1807 (unsigned char)(config->rmt_ip >> 16),
1808 (unsigned char)(config->rmt_ip >> 8),
1809 config->rmt_ip & 0xff);
1810 config->port = ntohs(fromAddr.sin_port);
1812 bb_error_msg("connection from IP=%s, port %u",
1813 config->rmt_ip_str, config->port);
1815 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1817 /* set the KEEPALIVE option to cull dead connections */
1819 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof (on));
1825 /* This is the spawned thread */
1826 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1827 /* protect reload config, may be confuse checking */
1828 signal(SIGHUP, SIG_IGN);
1845 static int miniHttpd(void)
1847 struct sockaddr_in fromAddrLen;
1848 socklen_t sinlen = sizeof (struct sockaddr_in);
1850 getpeername (0, (struct sockaddr *)&fromAddrLen, &sinlen);
1851 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1852 #ifdef CONFIG_FEATURE_HTTPD_CGI
1853 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1854 (unsigned char)(config->rmt_ip >> 24),
1855 (unsigned char)(config->rmt_ip >> 16),
1856 (unsigned char)(config->rmt_ip >> 8),
1857 config->rmt_ip & 0xff);
1859 config->port = ntohs(fromAddrLen.sin_port);
1863 #endif /* CONFIG_FEATURE_HTTPD_WITHOUT_INETD */
1865 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1866 static void sighup_handler(int sig)
1869 struct sigaction sa;
1871 parse_conf(default_path_httpd_conf,
1872 sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1873 sa.sa_handler = sighup_handler;
1874 sigemptyset(&sa.sa_mask);
1875 sa.sa_flags = SA_RESTART;
1876 sigaction(SIGHUP, &sa, NULL);
1880 enum httpd_opts_nums {
1881 c_opt_config_file = 0,
1884 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1885 USE_FEATURE_HTTPD_BASIC_AUTH(r_opt_realm,)
1886 USE_FEATURE_HTTPD_AUTH_MD5(m_opt_md5,)
1887 USE_FEATURE_HTTPD_SETUID(u_opt_setuid,)
1888 USE_FEATURE_HTTPD_WITHOUT_INETD(p_opt_port,)
1891 static const char httpd_opts[]="c:d:h:"
1892 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1893 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1894 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1895 USE_FEATURE_HTTPD_SETUID("u:")
1896 USE_FEATURE_HTTPD_WITHOUT_INETD("p:");
1898 #define OPT_CONFIG_FILE (1<<c_opt_config_file)
1899 #define OPT_DECODE_URL (1<<d_opt_decode_url)
1900 #define OPT_HOME_HTTPD (1<<h_opt_home_httpd)
1902 #define OPT_ENCODE_URL USE_FEATURE_HTTPD_ENCODE_URL_STR((1<<e_opt_encode_url)) \
1903 SKIP_FEATURE_HTTPD_ENCODE_URL_STR(0)
1905 #define OPT_REALM USE_FEATURE_HTTPD_BASIC_AUTH((1<<r_opt_realm)) \
1906 SKIP_FEATURE_HTTPD_BASIC_AUTH(0)
1908 #define OPT_MD5 USE_FEATURE_HTTPD_AUTH_MD5((1<<m_opt_md5)) \
1909 SKIP_FEATURE_HTTPD_AUTH_MD5(0)
1911 #define OPT_SETUID USE_FEATURE_HTTPD_SETUID((1<<u_opt_setuid)) \
1912 SKIP_FEATURE_HTTPD_SETUID(0)
1914 #define OPT_PORT USE_FEATURE_HTTPD_WITHOUT_INETD((1<<p_opt_port)) \
1915 SKIP_FEATURE_HTTPD_WITHOUT_INETD(0)
1918 int httpd_main(int argc, char *argv[])
1921 const char *home_httpd = home;
1922 char *url_for_decode;
1923 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1924 USE_FEATURE_HTTPD_WITHOUT_INETD(const char *s_port;)
1925 USE_FEATURE_HTTPD_WITHOUT_INETD(int server;)
1927 USE_FEATURE_HTTPD_SETUID(const char *s_uid;)
1928 USE_FEATURE_HTTPD_SETUID(long uid = -1;)
1930 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1932 config = xzalloc(sizeof(*config));
1933 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1934 config->realm = "Web Server Authentication";
1937 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
1941 config->ContentLength = -1;
1943 opt = bb_getopt_ulflags(argc, argv, httpd_opts,
1944 &(config->configFile), &url_for_decode, &home_httpd
1945 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1946 USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
1947 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1948 USE_FEATURE_HTTPD_SETUID(, &s_uid)
1949 USE_FEATURE_HTTPD_WITHOUT_INETD(, &s_port)
1952 if(opt & OPT_DECODE_URL) {
1953 printf("%s", decodeString(url_for_decode, 1));
1956 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1957 if(opt & OPT_ENCODE_URL) {
1958 printf("%s", encodeString(url_for_encode));
1962 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1964 printf("%s\n", pw_encrypt(pass, "$1$"));
1968 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
1970 config->port = bb_xgetlarg(s_port, 10, 1, 0xffff);
1971 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1972 if(opt & OPT_SETUID) {
1975 uid = strtol(s_uid, &e, 0);
1978 uid = bb_xgetpwnam(s_uid);
1985 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
1986 server = openServer();
1987 # ifdef CONFIG_FEATURE_HTTPD_SETUID
1988 /* drop privileges */
1994 #ifdef CONFIG_FEATURE_HTTPD_CGI
1996 char *p = getenv("PATH");
2002 setenv("PATH", p, 1);
2003 # ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
2004 addEnvPort("SERVER");
2009 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2012 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2015 #ifdef CONFIG_FEATURE_HTTPD_WITHOUT_INETD
2017 xdaemon(1, 0); /* don`t change curent directory */
2019 return miniHttpd(server);