2 * httpd implementation for busybox
4 * Copyright (C) 2002,2003 Glenn Engel <glenne@engel.org>
5 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
7 * simplify patch stolen from libbb without using strdup
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 *****************************************************************************
27 * httpd -p 8080 -h $HOME/public_html
28 * or for daemon start from rc script with uid=0:
30 * This is equivalent if www user have uid=80 to
31 * httpd -p 80 -u 80 -h /www -c /etc/httpd.conf -r "Web Server Authentication"
34 * When a url contains "cgi-bin" it is assumed to be a cgi script. The
35 * server changes directory to the location of the script and executes it
36 * after setting QUERY_STRING and other environment variables. If url args
37 * are included in the url or as a post, the args are placed into decoded
38 * environment variables. e.g. /cgi-bin/setup?foo=Hello%20World will set
39 * the $CGI_foo environment variable to "Hello World" while
40 * CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV enabled.
42 * The server can also be invoked as a url arg decoder and html text encoder
44 * foo=`httpd -d $foo` # decode "Hello%20World" as "Hello World"
45 * bar=`httpd -e "<Hello World>"` # encode as "<Hello World>"
46 * Note that url encoding for arguments is not the same as html encoding for
47 * presenation. -d decodes a url-encoded argument while -e encodes in html
50 * httpd.conf has the following format:
52 * A:172.20. # Allow address from 172.20.0.0/16
53 * A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
54 * A:10.0.0.0/255.255.255.128 # Allow any address that previous set
55 * A:127.0.0.1 # Allow local loopback connections
56 * D:* # Deny from other IP connections
57 * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
58 * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
59 * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
60 * .au:audio/basic # additional mime type for audio.au files
62 * A/D may be as a/d or allow/deny - first char case unsensitive
63 * Deny IP rules take precedence over allow rules.
66 * The Deny/Allow IP logic:
68 * - Default is to allow all. No addresses are denied unless
69 * denied with a D: rule.
70 * - Order of Deny/Allow rules is significant
71 * - Deny rules take precedence over allow rules.
72 * - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
74 * - Specification of Allow all (A:*) is a no-op
77 * 1. Allow only specified addresses
78 * A:172.20 # Allow any address that begins with 172.20.
79 * A:10.10. # Allow any address that begins with 10.10.
80 * A:127.0.0.1 # Allow local loopback connections
81 * D:* # Deny from other IP connections
83 * 2. Only deny specified addresses
84 * D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
85 * D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
86 * A:* # (optional line added for clarity)
88 * If a sub directory contains a config file it is parsed and merged with
89 * any existing settings as if it was appended to the original configuration.
91 * subdir paths are relative to the containing subdir and thus cannot
92 * affect the parent rules.
94 * Note that since the sub dir is parsed in the forked thread servicing the
95 * subdir http request, any merge is discarded when the process exits. As a
96 * result, the subdir settings only have a lifetime of a single request.
99 * If -c is not set, an attempt will be made to open the default
100 * root configuration file. If -c is set and the file is not found, the
101 * server exits with an error.
107 #include <ctype.h> /* for isspace */
109 #include <stdlib.h> /* for malloc */
111 #include <unistd.h> /* for close */
113 #include <sys/types.h>
114 #include <sys/socket.h> /* for connect and socket*/
115 #include <netinet/in.h> /* for sockaddr_in */
116 #include <sys/time.h>
117 #include <sys/stat.h>
118 #include <sys/wait.h>
119 #include <fcntl.h> /* for open modes */
123 static const char httpdVersion[] = "busybox httpd/1.30 7-Sep-2003";
124 static const char default_path_httpd_conf[] = "/etc";
125 static const char httpd_conf[] = "httpd.conf";
126 static const char home[] = "./";
129 # define cont_l_fmt "%lld"
131 # define cont_l_fmt "%ld"
135 // Note: bussybox xfuncs are not used because we want the server to keep running
136 // if something bad happens due to a malformed user request.
137 // As a result, all memory allocation after daemonize
138 // is checked rigorously
142 /* Configure options, disabled by default as custom httpd feature */
144 /* disabled as optional features */
145 //#define CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
146 //#define CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
147 //#define CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
148 //#define CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
149 //#define CONFIG_FEATURE_HTTPD_SETUID
150 //#define CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
152 /* If set, use this server from internet superserver only */
153 //#define CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
155 /* You can use this server as standalone, require libbb.a for linking */
156 //#define HTTPD_STANDALONE
158 /* Config options, disable this for do very small module */
159 //#define CONFIG_FEATURE_HTTPD_CGI
160 //#define CONFIG_FEATURE_HTTPD_BASIC_AUTH
161 //#define CONFIG_FEATURE_HTTPD_AUTH_MD5
163 #ifdef HTTPD_STANDALONE
164 /* standalone, enable all features */
165 #undef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
166 /* unset config option for remove warning as redefined */
167 #undef CONFIG_FEATURE_HTTPD_BASIC_AUTH
168 #undef CONFIG_FEATURE_HTTPD_AUTH_MD5
169 #undef CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
170 #undef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
171 #undef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
172 #undef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
173 #undef CONFIG_FEATURE_HTTPD_CGI
174 #undef CONFIG_FEATURE_HTTPD_SETUID
175 #undef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
176 /* enable all features now */
177 #define CONFIG_FEATURE_HTTPD_BASIC_AUTH
178 #define CONFIG_FEATURE_HTTPD_AUTH_MD5
179 #define CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
180 #define CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
181 #define CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
182 #define CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
183 #define CONFIG_FEATURE_HTTPD_CGI
184 #define CONFIG_FEATURE_HTTPD_SETUID
185 #define CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
187 /* require from libbb.a for linking */
188 const char *bb_applet_name = "httpd";
190 void bb_show_usage(void)
192 fprintf(stderr, "Usage: %s [-p <port>] [-c configFile] [-d/-e <string>] "
193 "[-r realm] [-u user] [-h homedir]\n", bb_applet_name);
198 #ifdef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
199 #undef CONFIG_FEATURE_HTTPD_SETUID /* use inetd user.group config settings */
200 #undef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP /* so is not daemon */
201 /* inetd set stderr to accepted socket and we can`t true see debug messages */
205 #define MAX_POST_SIZE (64*1024) /* 64k. Its Small? May be ;) */
207 #define MAX_MEMORY_BUFF 8192 /* IO buffer */
209 typedef struct HT_ACCESS {
211 struct HT_ACCESS *next;
212 char before_colon[1]; /* really bigger, must last */
215 typedef struct HT_ACCESS_IP {
219 struct HT_ACCESS_IP *next;
224 char buf[MAX_MEMORY_BUFF];
226 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
229 const char *configFile;
232 #if defined(CONFIG_FEATURE_HTTPD_CGI) || defined(DEBUG)
233 char rmt_ip_str[16]; /* for set env REMOTE_ADDR */
235 unsigned port; /* server initial port and for
236 set env REMOTE_PORT */
238 const char *found_mime_type;
239 off_t ContentLength; /* -1 - unknown */
242 Htaccess_IP *ip_a_d; /* config allow/deny lines */
244 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
245 Htaccess *auth; /* config user:password lines */
247 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
248 Htaccess *mime_a; /* config mime types */
251 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
253 #define a_c_r config->accepted_socket
254 #define a_c_w config->accepted_socket
255 int debugHttpd; /* if seted, don`t stay daemon */
262 static HttpdConfig *config;
264 static const char request_GET[] = "GET"; /* size algorithic optimize */
266 static const char* const suffixTable [] = {
267 /* Warning: shorted equalent suffix in one line must be first */
268 ".htm.html", "text/html",
269 ".jpg.jpeg", "image/jpeg",
272 ".txt.h.c.cc.cpp", "text/plain",
275 ".avi", "video/x-msvideo",
276 ".qt.mov", "video/quicktime",
277 ".mpe.mpeg", "video/mpeg",
278 ".mid.midi", "audio/midi",
279 ".mp3", "audio/mpeg",
280 #if 0 /* unpopular */
281 ".au", "audio/basic",
282 ".pac", "application/x-ns-proxy-autoconfig",
283 ".vrml.wrl", "model/vrml",
285 0, "application/octet-stream" /* default */
291 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
292 HTTP_NOT_FOUND = 404,
293 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
294 HTTP_BAD_REQUEST = 400, /* malformed syntax */
295 HTTP_FORBIDDEN = 403,
296 HTTP_INTERNAL_SERVER_ERROR = 500,
297 #if 0 /* future use */
299 HTTP_SWITCHING_PROTOCOLS = 101,
302 HTTP_NON_AUTHORITATIVE_INFO = 203,
303 HTTP_NO_CONTENT = 204,
304 HTTP_MULTIPLE_CHOICES = 300,
305 HTTP_MOVED_PERMANENTLY = 301,
306 HTTP_MOVED_TEMPORARILY = 302,
307 HTTP_NOT_MODIFIED = 304,
308 HTTP_PAYMENT_REQUIRED = 402,
309 HTTP_BAD_GATEWAY = 502,
310 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
311 HTTP_RESPONSE_SETSIZE=0xffffffff
317 HttpResponseNum type;
322 static const HttpEnumString httpResponseNames[] = {
324 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
325 "The requested method is not recognized by this server." },
326 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
327 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
329 { HTTP_NOT_FOUND, "Not Found",
330 "The requested URL was not found on this server." },
331 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
332 { HTTP_FORBIDDEN, "Forbidden", "" },
333 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
334 "Internal Server Error" },
335 #if 0 /* not implemented */
336 { HTTP_CREATED, "Created" },
337 { HTTP_ACCEPTED, "Accepted" },
338 { HTTP_NO_CONTENT, "No Content" },
339 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
340 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
341 { HTTP_MOVED_TEMPORARILY, "Moved Temporarily" },
342 { HTTP_NOT_MODIFIED, "Not Modified" },
343 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
344 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
349 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
350 static const char Content_length[] = "Content-length:";
354 scan_ip (const char **ep, unsigned int *ip, unsigned char endc)
361 for (j = 0; j < 4; j++) {
364 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
367 while (*p >= '0' && *p <= '9') {
376 if (*p != '/' && *p != 0)
378 *ip = ((*ip) << 8) | octet;
392 scan_ip_mask (const char *ipm, unsigned int *ip, unsigned int *mask)
397 i = scan_ip(&ipm, ip, '/');
405 if (*p < '0' || *p > '9') {
407 i = scan_ip (&ipm, mask, 0);
429 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
430 static void free_config_lines(Htaccess **pprev)
432 Htaccess *prev = *pprev;
435 Htaccess *cur = prev;
445 #define FIRST_PARSE 0
446 #define SUBDIR_PARSE 1
447 #define SIGNALED_PARSE 2
448 #define FIND_FROM_HTTPD_ROOT 3
449 /****************************************************************************
451 > $Function: parse_conf()
453 * $Description: parse configuration file into in-memory linked list.
455 * The first non-white character is examined to determine if the config line
456 * is one of the following:
457 * .ext:mime/type # new mime type not compiled into httpd
458 * [adAD]:from # ip address allow/deny, * for wildcard
459 * /path:user:pass # username/password
461 * Any previous IP rules are discarded.
462 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
463 * are also discarded. That is, previous settings are retained if flag is
467 * (const char *) path . . null for ip address checks, path for password
469 * (int) flag . . . . . . the source of the parse request.
473 ****************************************************************************/
474 static void parse_conf(const char *path, int flag)
478 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
482 const char *cf = config->configFile;
487 /* free previous ip setup if present */
488 Htaccess_IP *pip = config->ip_a_d;
491 Htaccess_IP *cur_ipl = pip;
496 config->ip_a_d = NULL;
498 config->flg_deny_all = 0;
500 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
501 /* retain previous auth and mime config only for subdir parse */
502 if(flag != SUBDIR_PARSE) {
503 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
504 free_config_lines(&config->auth);
506 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
507 free_config_lines(&config->mime_a);
512 if(flag == SUBDIR_PARSE || cf == NULL) {
513 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
515 if(flag == FIRST_PARSE)
516 bb_error_msg_and_die(bb_msg_memory_exhausted);
519 sprintf((char *)cf, "%s/%s", path, httpd_conf);
522 while((f = fopen(cf, "r")) == NULL) {
523 if(flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
524 /* config file not found, no changes to config */
527 if(config->configFile && flag == FIRST_PARSE) /* if -c option given */
528 bb_perror_msg_and_die("%s", cf);
529 flag = FIND_FROM_HTTPD_ROOT;
533 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
536 /* This could stand some work */
537 while ( (p0 = fgets(buf, sizeof(buf), f)) != NULL) {
539 for(p = p0; *p0 != 0 && *p0 != '#'; p0++) {
542 if(*p0 == ':' && c == NULL)
548 /* test for empty or strange line */
549 if (c == NULL || *c == 0)
556 /* memorize deny all */
557 config->flg_deny_all++;
559 /* skip default other "word:*" config lines */
565 else if(*p0 != 'D' && *p0 != 'A'
566 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
569 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
574 if(*p0 == 'A' || *p0 == 'D') {
575 /* storing current config IP line */
576 pip = calloc(1, sizeof(Htaccess_IP));
578 if(scan_ip_mask (c, &(pip->ip), &(pip->mask))) {
579 /* syntax IP{/mask} error detected, protect all */
583 pip->allow_deny = *p0;
585 /* Deny:form_IP move top */
586 pip->next = config->ip_a_d;
587 config->ip_a_d = pip;
589 /* add to bottom A:form_IP config line */
590 Htaccess_IP *prev_IP = config->ip_a_d;
592 if(prev_IP == NULL) {
593 config->ip_a_d = pip;
596 prev_IP = prev_IP->next;
603 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
605 /* make full path from httpd root / curent_path / config_line_path */
606 cf = flag == SUBDIR_PARSE ? path : "";
607 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
611 sprintf(p0, "/%s%s", cf, buf);
613 /* another call bb_simplify_path */
618 if (*cf == '/') { /* skip duplicate (or initial) slash */
620 } else if (*cf == '.') {
621 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
623 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
626 while (*--p != '/'); /* omit previous dir */
635 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
636 ++p; /* so keep last character */
639 sprintf(p0, "%s:%s", p0, c);
643 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
644 /* storing current config line */
645 cur = calloc(1, sizeof(Htaccess) + strlen(p0));
647 cf = strcpy(cur->before_colon, p0);
650 cur->after_colon = c;
651 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
653 /* config .mime line move top for overwrite previous */
654 cur->next = config->mime_a;
655 config->mime_a = cur;
659 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
663 config->auth = prev = cur;
665 /* sort path, if current lenght eq or bigger then move up */
666 Htaccess *prev_hti = config->auth;
670 for(hti = prev_hti; hti; hti = hti->next) {
671 if(l >= strlen(hti->before_colon)) {
672 /* insert before hti */
674 if(prev_hti != hti) {
675 prev_hti->next = cur;
683 prev_hti = prev_hti->next;
685 if(!hti) { /* not inserted, add to bottom */
697 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
698 /****************************************************************************
700 > $Function: encodeString()
702 * $Description: Given a string, html encode special characters.
703 * This is used for the -e command line option to provide an easy way
704 * for scripts to encode result data without confusing browsers. The
705 * returned string pointer is memory allocated by malloc().
708 * (const char *) string . . The first string to encode.
710 * $Return: (char *) . . . .. . . A pointer to the encoded string.
712 * $Errors: Returns a null string ("") if memory is not available.
714 ****************************************************************************/
715 static char *encodeString(const char *string)
717 /* take the simple route and encode everything */
718 /* could possibly scan once to get length. */
719 int len = strlen(string);
720 char *out = malloc(len*5 +1);
725 while ((ch = *string++)) {
726 // very simple check for what to encode
727 if (isalnum(ch)) *p++ = ch;
728 else p += sprintf(p, "&#%d", (unsigned char) ch);
733 #endif /* CONFIG_FEATURE_HTTPD_ENCODE_URL_STR */
735 /****************************************************************************
737 > $Function: decodeString()
739 * $Description: Given a URL encoded string, convert it to plain ascii.
740 * Since decoding always makes strings smaller, the decode is done in-place.
741 * Thus, callers should strdup() the argument if they do not want the
742 * argument modified. The return is the original pointer, allowing this
743 * function to be easily used as arguments to other functions.
746 * (char *) string . . . The first string to decode.
747 * (int) flag . . . 1 if require decode '+' as ' ' for CGI
749 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
753 ****************************************************************************/
754 static char *decodeString(char *orig, int flag_plus_to_space)
756 /* note that decoded string is always shorter than original */
762 if (*ptr == '+' && flag_plus_to_space) { *string++ = ' '; ptr++; }
763 else if (*ptr != '%') *string++ = *ptr++;
766 sscanf(ptr+1, "%2X", &value);
776 #ifdef CONFIG_FEATURE_HTTPD_CGI
777 /****************************************************************************
779 > $Function: addEnv()
781 * $Description: Add an enviornment variable setting to the global list.
782 * A NAME=VALUE string is allocated, filled, and added to the list of
783 * environment settings passed to the cgi execution script.
786 * (char *) name_before_underline - The first part environment variable name.
787 * (char *) name_after_underline - The second part environment variable name.
788 * (char *) value . . The value to which the env variable is set.
792 * $Errors: Silently returns if the env runs out of space to hold the new item
794 ****************************************************************************/
795 static void addEnv(const char *name_before_underline,
796 const char *name_after_underline, const char *value)
799 const char *underline;
803 underline = *name_after_underline ? "_" : "";
804 asprintf(&s, "%s%s%s=%s", name_before_underline, underline,
805 name_after_underline, value);
811 #if defined(CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV) || !defined(CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY)
812 /* set environs SERVER_PORT and REMOTE_PORT */
813 static void addEnvPort(const char *port_name)
817 sprintf(buf, "%u", config->port);
818 addEnv(port_name, "PORT", buf);
821 #endif /* CONFIG_FEATURE_HTTPD_CGI */
823 #ifdef CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
824 /****************************************************************************
826 > $Function: addEnvCgi
828 * $Description: Create environment variables given a URL encoded arg list.
829 * For each variable setting the URL encoded arg list, create a corresponding
830 * environment variable. URL encoded arguments have the form
831 * name1=value1&name2=value2&name3=&ignores
832 * from this example, name3 set empty value, tail without '=' skiping
835 * (char *) pargs . . . . A pointer to the URL encoded arguments.
841 ****************************************************************************/
842 static void addEnvCgi(const char *pargs)
846 char *namelist; /* space separated list of arg names */
847 if (pargs==0) return;
849 /* args are a list of name=value&name2=value2 sequences */
850 namelist = (char *) malloc(strlen(pargs));
851 if (namelist) namelist[0]=0;
852 memargs = args = strdup(pargs);
853 while (args && *args) {
854 const char *name = args;
855 char *value = strchr(args, '=');
857 if (!value) /* &XXX without '=' */
860 args = strchr(value, '&');
863 addEnv("CGI", name, decodeString(value, 1));
864 if (*namelist) strcat(namelist, " ");
865 strcat(namelist, name);
869 addEnv("CGI", "ARGLIST_", namelist);
873 #endif /* CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV */
876 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
877 /****************************************************************************
879 > $Function: decodeBase64()
881 > $Description: Decode a base 64 data stream as per rfc1521.
882 * Note that the rfc states that none base64 chars are to be ignored.
883 * Since the decode always results in a shorter size than the input, it is
884 * OK to pass the input arg as an output arg.
887 * (char *) Data . . . . A pointer to a base64 encoded string.
888 * Where to place the decoded data.
894 ****************************************************************************/
895 static void decodeBase64(char *Data)
898 const unsigned char *in = Data;
899 // The decoded size will be at most 3/4 the size of the encoded
900 unsigned long ch = 0;
906 if(t >= '0' && t <= '9')
908 else if(t >= 'A' && t <= 'Z')
910 else if(t >= 'a' && t <= 'z')
924 *Data++ = (char) (ch >> 16);
925 *Data++ = (char) (ch >> 8);
935 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
936 /****************************************************************************
938 > $Function: openServer()
940 * $Description: create a listen server socket on the designated port.
942 * $Return: (int) . . . A connection socket. -1 for errors.
946 ****************************************************************************/
947 static int openServer(void)
949 struct sockaddr_in lsocket;
952 /* create the socket right now */
953 /* inet_addr() returns a value that is already in network order */
954 memset(&lsocket, 0, sizeof(lsocket));
955 lsocket.sin_family = AF_INET;
956 lsocket.sin_addr.s_addr = INADDR_ANY;
957 lsocket.sin_port = htons(config->port) ;
958 fd = socket(AF_INET, SOCK_STREAM, 0);
960 /* tell the OS it's OK to reuse a previous address even though */
961 /* it may still be in a close down state. Allows bind to succeed. */
964 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on)) ;
966 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)) ;
968 if (bind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket)) == 0) {
970 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
972 bb_perror_msg_and_die("bind");
975 bb_perror_msg_and_die("create socket");
979 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
981 /****************************************************************************
983 > $Function: sendHeaders()
985 * $Description: Create and send HTTP response headers.
986 * The arguments are combined and sent as one write operation. Note that
987 * IE will puke big-time if the headers are not sent in one packet and the
988 * second packet is delayed for any reason.
991 * (HttpResponseNum) responseNum . . . The result code to send.
993 * $Return: (int) . . . . writing errors
995 ****************************************************************************/
996 static int sendHeaders(HttpResponseNum responseNum)
998 char *buf = config->buf;
999 const char *responseString = "";
1000 const char *infoString = 0;
1002 time_t timer = time(0);
1007 i < (sizeof(httpResponseNames)/sizeof(httpResponseNames[0])); i++) {
1008 if (httpResponseNames[i].type == responseNum) {
1009 responseString = httpResponseNames[i].name;
1010 infoString = httpResponseNames[i].info;
1014 if (responseNum != HTTP_OK) {
1015 config->found_mime_type = "text/html"; // error message is HTML
1018 /* emit the current date */
1019 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
1021 "HTTP/1.0 %d %s\nContent-type: %s\r\n"
1022 "Date: %s\r\nConnection: close\r\n",
1023 responseNum, responseString, config->found_mime_type, timeStr);
1025 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1026 if (responseNum == HTTP_UNAUTHORIZED) {
1027 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
1031 if (config->ContentLength != -1) { /* file */
1032 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
1033 len += sprintf(buf+len, "Last-Modified: %s\r\n%s " cont_l_fmt "\r\n",
1034 timeStr, Content_length, config->ContentLength);
1036 strcat(buf, "\r\n");
1039 len += sprintf(buf+len,
1040 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
1041 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
1042 responseNum, responseString,
1043 responseNum, responseString, infoString);
1046 if (config->debugHttpd) fprintf(stderr, "Headers: '%s'", buf);
1048 return bb_full_write(a_c_w, buf, len);
1051 /****************************************************************************
1053 > $Function: getLine()
1055 * $Description: Read from the socket until an end of line char found.
1057 * Characters are read one at a time until an eol sequence is found.
1060 * (char *) buf . . Where to place the read result.
1062 * $Return: (int) . . . . number of characters read. -1 if error.
1064 ****************************************************************************/
1065 static int getLine(char *buf)
1069 while (read(a_c_r, buf + count, 1) == 1) {
1070 if (buf[count] == '\r') continue;
1071 if (buf[count] == '\n') {
1075 if(count < (MAX_MEMORY_BUFF-1)) /* check owerflow */
1078 if (count) return count;
1082 #ifdef CONFIG_FEATURE_HTTPD_CGI
1083 /****************************************************************************
1085 > $Function: sendCgi()
1087 * $Description: Execute a CGI script and send it's stdout back
1089 * Environment variables are set up and the script is invoked with pipes
1090 * for stdin/stdout. If a post is being done the script is fed the POST
1091 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
1094 * (const char *) url . . . The requested URL (with leading /).
1095 * (const char *urlArgs). . Any URL arguments.
1096 * (const char *body) . . . POST body contents.
1097 * (int bodyLen) . . . . . Length of the post body.
1098 * (const char *cookie) . . For set HTTP_COOKIE.
1101 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
1105 ****************************************************************************/
1106 static int sendCgi(const char *url,
1107 const char *request, const char *urlArgs,
1108 const char *body, int bodyLen, const char *cookie)
1110 int fromCgi[2]; /* pipe for reading data from CGI */
1111 int toCgi[2]; /* pipe for sending data to CGI */
1113 static char * argp[] = { 0, 0 };
1120 if (pipe(fromCgi) != 0) {
1123 if (pipe(toCgi) != 0) {
1136 char *purl = strdup( url );
1137 char realpath_buff[MAXPATHLEN];
1145 dup2(inFd, 0); // replace stdin with the pipe
1146 dup2(outFd, 1); // replace stdout with the pipe
1148 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1149 if (!config->debugHttpd)
1151 dup2(outFd, 2); // replace stderr with the pipe
1162 while((script = strchr( script + 1, '/' )) != NULL) {
1163 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1167 if(is_directory(purl + 1, 1, &sb) == 0) {
1168 /* not directory, found script.cgi/PATH_INFO */
1172 *script = '/'; /* is directory, find next '/' */
1174 addEnv("PATH", "INFO", script); /* set /PATH_INFO or NULL */
1175 addEnv("PATH", "", getenv("PATH"));
1176 addEnv("REQUEST", "METHOD", request);
1178 char *uri = alloca(strlen(purl) + 2 + strlen(urlArgs));
1180 sprintf(uri, "%s?%s", purl, urlArgs);
1181 addEnv("REQUEST", "URI", uri);
1183 addEnv("REQUEST", "URI", purl);
1186 *script = '\0'; /* reduce /PATH_INFO */
1187 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1188 addEnv("SCRIPT_NAME", "", purl);
1189 addEnv("QUERY_STRING", "", urlArgs);
1190 addEnv("SERVER", "SOFTWARE", httpdVersion);
1191 addEnv("SERVER", "PROTOCOL", "HTTP/1.0");
1192 addEnv("GATEWAY_INTERFACE", "", "CGI/1.1");
1193 #ifdef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1194 addEnv("REMOTE", "ADDR", config->rmt_ip_str);
1195 addEnvPort("REMOTE");
1197 addEnv("REMOTE_ADDR", "", config->rmt_ip_str);
1202 sprintf(sbl, "%d", bodyLen);
1203 addEnv("CONTENT_LENGTH", "", sbl);
1206 addEnv("HTTP_COOKIE", "", cookie);
1208 #ifdef CONFIG_FEATURE_HTTPD_SET_CGI_VARS_TO_ENV
1209 if (request != request_GET) {
1216 /* set execve argp[0] without path */
1217 argp[0] = strrchr( purl, '/' ) + 1;
1218 /* but script argp[0] must have absolute path and chdiring to this */
1219 if(realpath(purl + 1, realpath_buff) != NULL) {
1220 script = strrchr(realpath_buff, '/');
1223 if(chdir(realpath_buff) == 0) {
1225 // now run the program. If it fails,
1226 // use _exit() so no destructors
1227 // get called and make a mess.
1228 execv(realpath_buff, argp);
1232 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1233 config->accepted_socket = 1; /* send to stdout */
1235 sendHeaders(HTTP_NOT_FOUND);
1242 /* parent process */
1249 if (body) bb_full_write(outFd, body, bodyLen);
1253 struct timeval timeout;
1260 FD_SET(inFd, &readSet);
1262 /* Now wait on the set of sockets! */
1264 timeout.tv_usec = 10000;
1265 nfound = select(inFd + 1, &readSet, 0, 0, &timeout);
1268 if (waitpid(pid, &status, WNOHANG) > 0) {
1271 if (config->debugHttpd) {
1272 if (WIFEXITED(status))
1273 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1274 if (WIFSIGNALED(status))
1275 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1284 // There is something to read
1285 count = bb_full_read(inFd, buf, sizeof(buf)-1);
1286 // If a read returns 0 at this point then some type of error has
1287 // occurred. Bail now.
1288 if (count == 0) break;
1291 /* check to see if the user script added headers */
1292 if (strncmp(buf, "HTTP/1.0 200 OK\n", 4) != 0) {
1293 bb_full_write(s, "HTTP/1.0 200 OK\n", 16);
1295 if (strstr(buf, "ontent-") == 0) {
1296 bb_full_write(s, "Content-type: text/plain\n\n", 26);
1300 bb_full_write(s, buf, count);
1302 if (config->debugHttpd)
1303 fprintf(stderr, "cgi read %d bytes\n", count);
1311 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1313 /****************************************************************************
1315 > $Function: sendFile()
1317 * $Description: Send a file response to an HTTP request
1320 * (const char *) url . . The URL requested.
1321 * (char *) buf . . . . . The stack buffer.
1323 * $Return: (int) . . . . . . Always 0.
1325 ****************************************************************************/
1326 static int sendFile(const char *url, char *buf)
1330 const char * const * table;
1331 const char * try_suffix;
1333 suffix = strrchr(url, '.');
1335 for (table = suffixTable; *table; table += 2)
1336 if(suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1337 try_suffix += strlen(suffix);
1338 if(*try_suffix == 0 || *try_suffix == '.')
1341 /* also, if not found, set default as "application/octet-stream"; */
1342 config->found_mime_type = *(table+1);
1343 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1347 for (cur = config->mime_a; cur; cur = cur->next) {
1348 if(strcmp(cur->before_colon, suffix) == 0) {
1349 config->found_mime_type = cur->after_colon;
1354 #endif /* CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1357 if (config->debugHttpd)
1358 fprintf(stderr, "Sending file '%s' Content-type: %s\n",
1359 url, config->found_mime_type);
1362 f = open(url, O_RDONLY);
1366 sendHeaders(HTTP_OK);
1367 while ((count = bb_full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1368 bb_full_write(a_c_w, buf, count);
1373 if (config->debugHttpd)
1374 bb_perror_msg("Unable to open '%s'", url);
1376 sendHeaders(HTTP_NOT_FOUND);
1382 static int checkPermIP(void)
1386 /* This could stand some work */
1387 for (cur = config->ip_a_d; cur; cur = cur->next) {
1389 if (config->debugHttpd) {
1390 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1391 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1392 (unsigned char)(cur->ip >> 24),
1393 (unsigned char)(cur->ip >> 16),
1394 (unsigned char)(cur->ip >> 8),
1396 (unsigned char)(cur->mask >> 24),
1397 (unsigned char)(cur->mask >> 16),
1398 (unsigned char)(cur->mask >> 8),
1402 if((config->rmt_ip & cur->mask) == cur->ip)
1403 return cur->allow_deny == 'A'; /* Allow/Deny */
1406 /* if uncofigured, return 1 - access from all */
1407 return !config->flg_deny_all;
1410 /****************************************************************************
1412 > $Function: checkPerm()
1414 * $Description: Check the permission file for access password protected.
1416 * If config file isn't present, everything is allowed.
1417 * Entries are of the form you can see example from header source
1420 * (const char *) path . . . . The file path.
1421 * (const char *) request . . . User information to validate.
1423 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1425 ****************************************************************************/
1427 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1428 static int checkPerm(const char *path, const char *request)
1434 const char *prev = NULL;
1436 /* This could stand some work */
1437 for (cur = config->auth; cur; cur = cur->next) {
1438 p0 = cur->before_colon;
1439 if(prev != NULL && strcmp(prev, p0) != 0)
1440 continue; /* find next identical */
1441 p = cur->after_colon;
1443 if (config->debugHttpd)
1444 fprintf(stderr,"checkPerm: '%s' ? '%s'\n", p0, request);
1449 if(strncmp(p0, path, l) == 0 &&
1450 (l == 1 || path[l] == '/' || path[l] == 0)) {
1451 /* path match found. Check request */
1453 /* for check next /path:user:password */
1455 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1459 char *u = strchr(request, ':');
1462 /* bad request, ':' required */
1465 if(strncmp(p, request, u-request) != 0) {
1466 /* user uncompared */
1469 pp = strchr(p, ':');
1470 if(pp && pp[1] == '$' && pp[2] == '1' &&
1471 pp[3] == '$' && pp[4]) {
1473 cipher = pw_encrypt(u+1, pp);
1474 if (strcmp(cipher, pp) == 0)
1481 if (strcmp(p, request) == 0)
1488 return prev == NULL;
1491 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1494 /****************************************************************************
1496 > $Function: handleIncoming()
1498 * $Description: Handle an incoming http request.
1500 ****************************************************************************/
1501 static void handleIncoming(void)
1503 char *buf = config->buf;
1508 #ifdef CONFIG_FEATURE_HTTPD_CGI
1509 const char *prequest = request_GET;
1518 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1519 int credentials = -1; /* if not requred this is Ok */
1525 if (getLine(buf) <= 0)
1528 purl = strpbrk(buf, " \t");
1531 sendHeaders(HTTP_BAD_REQUEST);
1535 #ifdef CONFIG_FEATURE_HTTPD_CGI
1536 if(strcasecmp(buf, prequest) != 0) {
1538 if(strcasecmp(buf, prequest) != 0) {
1539 sendHeaders(HTTP_NOT_IMPLEMENTED);
1544 if(strcasecmp(buf, request_GET) != 0) {
1545 sendHeaders(HTTP_NOT_IMPLEMENTED);
1550 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1552 decodeString(buf, 0);
1553 if (count < 1 || buf[0] != '/') {
1554 /* Garbled request/URL */
1557 url = alloca(strlen(buf) + 12); /* + sizeof("/index.html\0") */
1559 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1563 /* extract url args if present */
1564 urlArgs = strchr(url, '?');
1568 /* algorithm stolen from libbb bb_simplify_path(),
1569 but don`t strdup and reducing trailing slash and protect out root */
1574 if (*test == '/') { /* skip duplicate (or initial) slash */
1576 } else if (*test == '.') {
1577 if (test[1] == '/' || test[1] == 0) { /* skip extra '.' */
1579 } else if ((test[1] == '.') && (test[2] == '/' || test[2] == 0)) {
1582 /* protect out root */
1585 while (*--purl != '/'); /* omit previous dir */
1593 *++purl = 0; /* so keep last character */
1594 test = purl; /* end ptr */
1596 /* If URL is directory, adding '/' */
1597 if(test[-1] != '/') {
1598 if ( is_directory(url + 1, 1, &sb) ) {
1601 purl = test; /* end ptr */
1605 if (config->debugHttpd)
1606 fprintf(stderr, "url='%s', args=%s\n", url, urlArgs);
1610 ip_allowed = checkPermIP();
1611 while(ip_allowed && (test = strchr( test + 1, '/' )) != NULL) {
1612 /* have path1/path2 */
1614 if( is_directory(url + 1, 1, &sb) ) {
1615 /* may be having subdir config */
1616 parse_conf(url + 1, SUBDIR_PARSE);
1617 ip_allowed = checkPermIP();
1622 // read until blank line for HTTP version specified, else parse immediate
1623 while (blank >= 0 && (count = getLine(buf)) > 0) {
1626 if (config->debugHttpd) fprintf(stderr, "Header: '%s'\n", buf);
1629 #ifdef CONFIG_FEATURE_HTTPD_CGI
1630 /* try and do our best to parse more lines */
1631 if ((strncasecmp(buf, Content_length, 15) == 0)) {
1632 if(prequest != request_GET)
1633 length = strtol(buf + 15, 0, 0); // extra read only for POST
1634 } else if ((strncasecmp(buf, "Cookie:", 7) == 0)) {
1635 for(test = buf + 7; isspace(*test); test++)
1637 cookie = strdup(test);
1641 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1642 if (strncasecmp(buf, "Authorization:", 14) == 0) {
1643 /* We only allow Basic credentials.
1644 * It shows up as "Authorization: Basic <userid:password>" where
1645 * the userid:password is base64 encoded.
1647 for(test = buf + 14; isspace(*test); test++)
1649 if (strncasecmp(test, "Basic", 5) != 0)
1652 test += 5; /* decodeBase64() skiping space self */
1654 credentials = checkPerm(url, test);
1656 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1658 } /* while extra header reading */
1661 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1662 /* protect listing [/path]/httpd_conf or IP deny */
1663 #ifdef CONFIG_FEATURE_HTTPD_CGI
1664 FORBIDDEN: /* protect listing /cgi-bin */
1666 sendHeaders(HTTP_FORBIDDEN);
1670 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1671 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1672 sendHeaders(HTTP_UNAUTHORIZED);
1677 test = url + 1; /* skip first '/' */
1679 #ifdef CONFIG_FEATURE_HTTPD_CGI
1680 /* if strange Content-Length */
1681 if (length < 0 || length > MAX_POST_SIZE)
1685 body = malloc(length + 1);
1687 length = bb_full_read(a_c_r, body, length);
1688 if(length < 0) // closed
1690 body[length] = 0; // always null terminate for safety
1694 if (strncmp(test, "cgi-bin", 7) == 0) {
1695 if(test[7] == '/' && test[8] == 0)
1696 goto FORBIDDEN; // protect listing cgi-bin/
1697 sendCgi(url, prequest, urlArgs, body, length, cookie);
1699 if (prequest != request_GET)
1700 sendHeaders(HTTP_NOT_IMPLEMENTED);
1702 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1704 strcpy(purl, "index.html");
1705 if ( stat(test, &sb ) == 0 ) {
1706 config->ContentLength = sb.st_size;
1707 config->last_mod = sb.st_mtime;
1709 sendFile(test, buf);
1710 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1711 /* unset if non inetd looped */
1712 config->ContentLength = -1;
1715 #ifdef CONFIG_FEATURE_HTTPD_CGI
1723 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1724 /* from inetd don`t looping: freeing, closing automatic from exit always */
1726 if (config->debugHttpd) fprintf(stderr, "closing socket\n");
1728 # ifdef CONFIG_FEATURE_HTTPD_CGI
1732 shutdown(a_c_w, SHUT_WR);
1733 shutdown(a_c_r, SHUT_RD);
1734 close(config->accepted_socket);
1735 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1738 /****************************************************************************
1740 > $Function: miniHttpd()
1742 * $Description: The main http server function.
1744 * Given an open socket fildes, listen for new connections and farm out
1745 * the processing as a forked process.
1748 * (int) server. . . The server socket fildes.
1750 * $Return: (int) . . . . Always 0.
1752 ****************************************************************************/
1753 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1754 static int miniHttpd(int server)
1756 fd_set readfd, portfd;
1759 FD_SET(server, &portfd);
1761 /* copy the ports we are watching to the readfd set */
1765 /* Now wait INDEFINATELY on the set of sockets! */
1766 if (select(server + 1, &readfd, 0, 0, 0) > 0) {
1767 if (FD_ISSET(server, &readfd)) {
1769 struct sockaddr_in fromAddr;
1771 socklen_t fromAddrLen = sizeof(fromAddr);
1772 int s = accept(server,
1773 (struct sockaddr *)&fromAddr, &fromAddrLen);
1778 config->accepted_socket = s;
1779 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1780 #if defined(CONFIG_FEATURE_HTTPD_CGI) || defined(DEBUG)
1781 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1782 (unsigned char)(config->rmt_ip >> 24),
1783 (unsigned char)(config->rmt_ip >> 16),
1784 (unsigned char)(config->rmt_ip >> 8),
1785 config->rmt_ip & 0xff);
1786 config->port = ntohs(fromAddr.sin_port);
1788 if (config->debugHttpd) {
1789 bb_error_msg("connection from IP=%s, port %u\n",
1790 config->rmt_ip_str, config->port);
1793 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1795 /* set the KEEPALIVE option to cull dead connections */
1797 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof (on));
1799 if (config->debugHttpd || fork() == 0) {
1800 /* This is the spawned thread */
1801 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1802 /* protect reload config, may be confuse checking */
1803 signal(SIGHUP, SIG_IGN);
1806 if(!config->debugHttpd)
1819 static int miniHttpd(void)
1821 struct sockaddr_in fromAddrLen;
1822 socklen_t sinlen = sizeof (struct sockaddr_in);
1824 getpeername (0, (struct sockaddr *)&fromAddrLen, &sinlen);
1825 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1826 #if defined(CONFIG_FEATURE_HTTPD_CGI) || defined(DEBUG)
1827 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1828 (unsigned char)(config->rmt_ip >> 24),
1829 (unsigned char)(config->rmt_ip >> 16),
1830 (unsigned char)(config->rmt_ip >> 8),
1831 config->rmt_ip & 0xff);
1833 config->port = ntohs(fromAddrLen.sin_port);
1837 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1839 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1840 static void sighup_handler(int sig)
1843 struct sigaction sa;
1845 parse_conf(default_path_httpd_conf,
1846 sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1847 sa.sa_handler = sighup_handler;
1848 sigemptyset(&sa.sa_mask);
1849 sa.sa_flags = SA_RESTART;
1850 sigaction(SIGHUP, &sa, NULL);
1855 static const char httpd_opts[]="c:d:h:"
1856 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1862 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1864 # ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1866 # define OPT_INC_2 2
1868 # define OPT_INC_2 1
1873 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1875 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1878 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1881 #define OPT_CONFIG_FILE (1<<0)
1882 #define OPT_DECODE_URL (1<<1)
1883 #define OPT_HOME_HTTPD (1<<2)
1884 #define OPT_ENCODE_URL (1<<(2+OPT_INC_1))
1885 #define OPT_REALM (1<<(3+OPT_INC_1))
1886 #define OPT_MD5 (1<<(4+OPT_INC_1))
1887 #define OPT_PORT (1<<(3+OPT_INC_1+OPT_INC_2))
1888 #define OPT_DEBUG (1<<(4+OPT_INC_1+OPT_INC_2))
1889 #define OPT_SETUID (1<<(5+OPT_INC_1+OPT_INC_2))
1892 #ifdef HTTPD_STANDALONE
1893 int main(int argc, char *argv[])
1895 int httpd_main(int argc, char *argv[])
1899 const char *home_httpd = home;
1900 char *url_for_decode;
1901 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1902 const char *url_for_encode;
1904 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1908 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1912 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1917 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1921 config = xcalloc(1, sizeof(*config));
1922 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1923 config->realm = "Web Server Authentication";
1926 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1930 config->ContentLength = -1;
1932 opt = bb_getopt_ulflags(argc, argv, httpd_opts,
1933 &(config->configFile), &url_for_decode, &home_httpd
1934 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1937 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1939 # ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1943 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1945 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1951 if(opt & OPT_DECODE_URL) {
1952 printf("%s", decodeString(url_for_decode, 1));
1955 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1956 if(opt & OPT_ENCODE_URL) {
1957 printf("%s", encodeString(url_for_encode));
1961 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1963 printf("%s\n", pw_encrypt(pass, "$1$"));
1967 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1969 config->port = bb_xgetlarg(s_port, 10, 1, 0xffff);
1970 config->debugHttpd = opt & OPT_DEBUG;
1971 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1972 if(opt & OPT_SETUID) {
1975 uid = strtol(s_uid, &e, 0);
1978 uid = my_getpwnam(s_uid);
1984 if(chdir(home_httpd)) {
1985 bb_perror_msg_and_die("can`t chdir to %s", home_httpd);
1987 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1988 server = openServer();
1989 # ifdef CONFIG_FEATURE_HTTPD_SETUID
1990 /* drop privilegies */
1994 # ifdef CONFIG_FEATURE_HTTPD_CGI
1995 addEnvPort("SERVER");
1999 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2002 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2005 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2006 if (!config->debugHttpd) {
2007 if (daemon(1, 0) < 0) /* don`t change curent directory */
2008 bb_perror_msg_and_die("daemon");
2010 return miniHttpd(server);