2 * httpd implementation for busybox
4 * Copyright (C) 2002,2003 Glenn Engel <glenne@engel.org>
5 * Copyright (C) 2003,2004 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.
38 * The server can also be invoked as a url arg decoder and html text encoder
40 * foo=`httpd -d $foo` # decode "Hello%20World" as "Hello World"
41 * bar=`httpd -e "<Hello World>"` # encode as "<Hello World>"
42 * Note that url encoding for arguments is not the same as html encoding for
43 * presentation. -d decodes a url-encoded argument while -e encodes in html
46 * httpd.conf has the following format:
48 * A:172.20. # Allow address from 172.20.0.0/16
49 * A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
50 * A:10.0.0.0/255.255.255.128 # Allow any address that previous set
51 * A:127.0.0.1 # Allow local loopback connections
52 * D:* # Deny from other IP connections
53 * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
54 * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
55 * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
56 * .au:audio/basic # additional mime type for audio.au files
58 * A/D may be as a/d or allow/deny - first char case insensitive
59 * Deny IP rules take precedence over allow rules.
62 * The Deny/Allow IP logic:
64 * - Default is to allow all. No addresses are denied unless
65 * denied with a D: rule.
66 * - Order of Deny/Allow rules is significant
67 * - Deny rules take precedence over allow rules.
68 * - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
70 * - Specification of Allow all (A:*) is a no-op
73 * 1. Allow only specified addresses
74 * A:172.20 # Allow any address that begins with 172.20.
75 * A:10.10. # Allow any address that begins with 10.10.
76 * A:127.0.0.1 # Allow local loopback connections
77 * D:* # Deny from other IP connections
79 * 2. Only deny specified addresses
80 * D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
81 * D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
82 * A:* # (optional line added for clarity)
84 * If a sub directory contains a config file it is parsed and merged with
85 * any existing settings as if it was appended to the original configuration.
87 * subdir paths are relative to the containing subdir and thus cannot
88 * affect the parent rules.
90 * Note that since the sub dir is parsed in the forked thread servicing the
91 * subdir http request, any merge is discarded when the process exits. As a
92 * result, the subdir settings only have a lifetime of a single request.
95 * If -c is not set, an attempt will be made to open the default
96 * root configuration file. If -c is set and the file is not found, the
97 * server exits with an error.
103 #include <ctype.h> /* for isspace */
105 #include <stdlib.h> /* for malloc */
107 #include <unistd.h> /* for close */
109 #include <sys/types.h>
110 #include <sys/socket.h> /* for connect and socket*/
111 #include <netinet/in.h> /* for sockaddr_in */
112 #include <sys/time.h>
113 #include <sys/stat.h>
114 #include <sys/wait.h>
115 #include <fcntl.h> /* for open modes */
119 static const char httpdVersion[] = "busybox httpd/1.35 6-Oct-2004";
120 static const char default_path_httpd_conf[] = "/etc";
121 static const char httpd_conf[] = "httpd.conf";
122 static const char home[] = "./";
125 # define cont_l_fmt "%lld"
127 # define cont_l_fmt "%ld"
132 // Note: busybox xfuncs are not used because we want the server to keep running
133 // if something bad happens due to a malformed user request.
134 // As a result, all memory allocation after daemonize
135 // is checked rigorously
139 /* Configure options, disabled by default as custom httpd feature */
141 /* disabled as optional features */
142 //#define CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
143 //#define CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
144 //#define CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
145 //#define CONFIG_FEATURE_HTTPD_SETUID
146 //#define CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
148 /* If set, use this server from internet superserver only */
149 //#define CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
151 /* You can use this server as standalone, require libbb.a for linking */
152 //#define HTTPD_STANDALONE
154 /* Config options, disable this for do very small module */
155 //#define CONFIG_FEATURE_HTTPD_CGI
156 //#define CONFIG_FEATURE_HTTPD_BASIC_AUTH
157 //#define CONFIG_FEATURE_HTTPD_AUTH_MD5
159 #ifdef HTTPD_STANDALONE
160 /* standalone, enable all features */
161 #undef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
162 /* unset config option for remove warning as redefined */
163 #undef CONFIG_FEATURE_HTTPD_BASIC_AUTH
164 #undef CONFIG_FEATURE_HTTPD_AUTH_MD5
165 #undef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
166 #undef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
167 #undef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
168 #undef CONFIG_FEATURE_HTTPD_CGI
169 #undef CONFIG_FEATURE_HTTPD_SETUID
170 #undef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
171 /* enable all features now */
172 #define CONFIG_FEATURE_HTTPD_BASIC_AUTH
173 #define CONFIG_FEATURE_HTTPD_AUTH_MD5
174 #define CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
175 #define CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
176 #define CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
177 #define CONFIG_FEATURE_HTTPD_CGI
178 #define CONFIG_FEATURE_HTTPD_SETUID
179 #define CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
181 /* require from libbb.a for linking */
182 const char *bb_applet_name = "httpd";
184 void bb_show_usage(void)
186 fprintf(stderr, "Usage: %s [-p <port>] [-c configFile] [-d/-e <string>] "
187 "[-r realm] [-u user] [-h homedir]\n", bb_applet_name);
192 #ifdef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
193 #undef CONFIG_FEATURE_HTTPD_SETUID /* use inetd user.group config settings */
194 #undef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP /* so is not daemon */
195 /* inetd set stderr to accepted socket and we can`t true see debug messages */
199 #define MAX_MEMORY_BUFF 8192 /* IO buffer */
201 typedef struct HT_ACCESS {
203 struct HT_ACCESS *next;
204 char before_colon[1]; /* really bigger, must last */
207 typedef struct HT_ACCESS_IP {
211 struct HT_ACCESS_IP *next;
216 char buf[MAX_MEMORY_BUFF];
218 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
225 #ifdef CONFIG_FEATURE_HTTPD_CGI
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 const char *found_moved_temporarily;
242 off_t ContentLength; /* -1 - unknown */
245 Htaccess_IP *ip_a_d; /* config allow/deny lines */
247 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
248 Htaccess *auth; /* config user:password lines */
250 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
251 Htaccess *mime_a; /* config mime types */
254 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
256 #define a_c_r config->accepted_socket
257 #define a_c_w config->accepted_socket
258 int debugHttpd; /* if seted, don`t stay daemon */
263 volatile int alarm_signaled;
267 static HttpdConfig *config;
269 static const char request_GET[] = "GET"; /* size algorithic optimize */
271 static const char* const suffixTable [] = {
272 /* Warning: shorted equivalent suffix in one line must be first */
273 ".htm.html", "text/html",
274 ".jpg.jpeg", "image/jpeg",
277 ".txt.h.c.cc.cpp", "text/plain",
280 ".avi", "video/x-msvideo",
281 ".qt.mov", "video/quicktime",
282 ".mpe.mpeg", "video/mpeg",
283 ".mid.midi", "audio/midi",
284 ".mp3", "audio/mpeg",
285 #if 0 /* unpopular */
286 ".au", "audio/basic",
287 ".pac", "application/x-ns-proxy-autoconfig",
288 ".vrml.wrl", "model/vrml",
290 0, "application/octet-stream" /* default */
296 HTTP_MOVED_TEMPORARILY = 302,
297 HTTP_BAD_REQUEST = 400, /* malformed syntax */
298 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
299 HTTP_NOT_FOUND = 404,
300 HTTP_FORBIDDEN = 403,
301 HTTP_REQUEST_TIMEOUT = 408,
302 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
303 HTTP_INTERNAL_SERVER_ERROR = 500,
304 #if 0 /* future use */
306 HTTP_SWITCHING_PROTOCOLS = 101,
309 HTTP_NON_AUTHORITATIVE_INFO = 203,
310 HTTP_NO_CONTENT = 204,
311 HTTP_MULTIPLE_CHOICES = 300,
312 HTTP_MOVED_PERMANENTLY = 301,
313 HTTP_NOT_MODIFIED = 304,
314 HTTP_PAYMENT_REQUIRED = 402,
315 HTTP_BAD_GATEWAY = 502,
316 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
317 HTTP_RESPONSE_SETSIZE=0xffffffff
323 HttpResponseNum type;
328 static const HttpEnumString httpResponseNames[] = {
329 { HTTP_OK, "OK", NULL },
330 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
331 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
332 "No request appeared within a reasonable time period." },
333 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
334 "The requested method is not recognized by this server." },
335 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
336 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
338 { HTTP_NOT_FOUND, "Not Found",
339 "The requested URL was not found on this server." },
340 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
341 { HTTP_FORBIDDEN, "Forbidden", "" },
342 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
343 "Internal Server Error" },
344 #if 0 /* not implemented */
345 { HTTP_CREATED, "Created" },
346 { HTTP_ACCEPTED, "Accepted" },
347 { HTTP_NO_CONTENT, "No Content" },
348 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
349 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
350 { HTTP_NOT_MODIFIED, "Not Modified" },
351 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
352 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
357 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
358 static const char Content_length[] = "Content-length:";
362 scan_ip (const char **ep, unsigned int *ip, unsigned char endc)
369 for (j = 0; j < 4; j++) {
372 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
375 while (*p >= '0' && *p <= '9') {
384 if (*p != '/' && *p != 0)
386 *ip = ((*ip) << 8) | octet;
400 scan_ip_mask (const char *ipm, unsigned int *ip, unsigned int *mask)
405 i = scan_ip(&ipm, ip, '/');
413 if (*p < '0' || *p > '9') {
415 i = scan_ip (&ipm, mask, 0);
437 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
438 static void free_config_lines(Htaccess **pprev)
440 Htaccess *prev = *pprev;
443 Htaccess *cur = prev;
453 #define FIRST_PARSE 0
454 #define SUBDIR_PARSE 1
455 #define SIGNALED_PARSE 2
456 #define FIND_FROM_HTTPD_ROOT 3
457 /****************************************************************************
459 > $Function: parse_conf()
461 * $Description: parse configuration file into in-memory linked list.
463 * The first non-white character is examined to determine if the config line
464 * is one of the following:
465 * .ext:mime/type # new mime type not compiled into httpd
466 * [adAD]:from # ip address allow/deny, * for wildcard
467 * /path:user:pass # username/password
469 * Any previous IP rules are discarded.
470 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
471 * are also discarded. That is, previous settings are retained if flag is
475 * (const char *) path . . null for ip address checks, path for password
477 * (int) flag . . . . . . the source of the parse request.
481 ****************************************************************************/
482 static void parse_conf(const char *path, int flag)
485 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
486 Htaccess *prev, *cur;
487 #elif CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
491 const char *cf = config->configFile;
496 /* free previous ip setup if present */
497 Htaccess_IP *pip = config->ip_a_d;
500 Htaccess_IP *cur_ipl = pip;
505 config->ip_a_d = NULL;
507 config->flg_deny_all = 0;
509 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
510 /* retain previous auth and mime config only for subdir parse */
511 if(flag != SUBDIR_PARSE) {
512 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
513 free_config_lines(&config->auth);
515 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
516 free_config_lines(&config->mime_a);
521 if(flag == SUBDIR_PARSE || cf == NULL) {
522 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
524 if(flag == FIRST_PARSE)
525 bb_error_msg_and_die(bb_msg_memory_exhausted);
528 sprintf((char *)cf, "%s/%s", path, httpd_conf);
531 while((f = fopen(cf, "r")) == NULL) {
532 if(flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
533 /* config file not found, no changes to config */
536 if(config->configFile && flag == FIRST_PARSE) /* if -c option given */
537 bb_perror_msg_and_die("%s", cf);
538 flag = FIND_FROM_HTTPD_ROOT;
542 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
545 /* This could stand some work */
546 while ( (p0 = fgets(buf, sizeof(buf), f)) != NULL) {
548 for(p = p0; *p0 != 0 && *p0 != '#'; p0++) {
551 if(*p0 == ':' && c == NULL)
557 /* test for empty or strange line */
558 if (c == NULL || *c == 0)
565 /* memorize deny all */
566 config->flg_deny_all++;
568 /* skip default other "word:*" config lines */
574 else if(*p0 != 'D' && *p0 != 'A'
575 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
578 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
583 if(*p0 == 'A' || *p0 == 'D') {
584 /* storing current config IP line */
585 pip = calloc(1, sizeof(Htaccess_IP));
587 if(scan_ip_mask (c, &(pip->ip), &(pip->mask))) {
588 /* syntax IP{/mask} error detected, protect all */
592 pip->allow_deny = *p0;
594 /* Deny:form_IP move top */
595 pip->next = config->ip_a_d;
596 config->ip_a_d = pip;
598 /* add to bottom A:form_IP config line */
599 Htaccess_IP *prev_IP = config->ip_a_d;
601 if(prev_IP == NULL) {
602 config->ip_a_d = pip;
605 prev_IP = prev_IP->next;
612 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
614 /* make full path from httpd root / curent_path / config_line_path */
615 cf = flag == SUBDIR_PARSE ? path : "";
616 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
620 sprintf(p0, "/%s%s", cf, buf);
622 /* another call bb_simplify_path */
627 if (*cf == '/') { /* skip duplicate (or initial) slash */
629 } else if (*cf == '.') {
630 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
632 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
635 while (*--p != '/'); /* omit previous dir */
644 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
645 ++p; /* so keep last character */
648 sprintf(p0, "%s:%s", p0, c);
652 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
653 /* storing current config line */
654 cur = calloc(1, sizeof(Htaccess) + strlen(p0));
656 cf = strcpy(cur->before_colon, p0);
659 cur->after_colon = c;
660 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
662 /* config .mime line move top for overwrite previous */
663 cur->next = config->mime_a;
664 config->mime_a = cur;
668 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
672 config->auth = prev = cur;
674 /* sort path, if current lenght eq or bigger then move up */
675 Htaccess *prev_hti = config->auth;
676 size_t l = strlen(cf);
679 for(hti = prev_hti; hti; hti = hti->next) {
680 if(l >= strlen(hti->before_colon)) {
681 /* insert before hti */
683 if(prev_hti != hti) {
684 prev_hti->next = cur;
692 prev_hti = prev_hti->next;
694 if(!hti) { /* not inserted, add to bottom */
706 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
707 /****************************************************************************
709 > $Function: encodeString()
711 * $Description: Given a string, html encode special characters.
712 * This is used for the -e command line option to provide an easy way
713 * for scripts to encode result data without confusing browsers. The
714 * returned string pointer is memory allocated by malloc().
717 * (const char *) string . . The first string to encode.
719 * $Return: (char *) . . . .. . . A pointer to the encoded string.
721 * $Errors: Returns a null string ("") if memory is not available.
723 ****************************************************************************/
724 static char *encodeString(const char *string)
726 /* take the simple route and encode everything */
727 /* could possibly scan once to get length. */
728 int len = strlen(string);
729 char *out = malloc(len*5 +1);
734 while ((ch = *string++)) {
735 // very simple check for what to encode
736 if (isalnum(ch)) *p++ = ch;
737 else p += sprintf(p, "&#%d;", (unsigned char) ch);
742 #endif /* CONFIG_FEATURE_HTTPD_ENCODE_URL_STR */
744 /****************************************************************************
746 > $Function: decodeString()
748 * $Description: Given a URL encoded string, convert it to plain ascii.
749 * Since decoding always makes strings smaller, the decode is done in-place.
750 * Thus, callers should strdup() the argument if they do not want the
751 * argument modified. The return is the original pointer, allowing this
752 * function to be easily used as arguments to other functions.
755 * (char *) string . . . The first string to decode.
756 * (int) flag . . . 1 if require decode '+' as ' ' for CGI
758 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
762 ****************************************************************************/
763 static char *decodeString(char *orig, int flag_plus_to_space)
765 /* note that decoded string is always shorter than original */
771 if (*ptr == '+' && flag_plus_to_space) { *string++ = ' '; ptr++; }
772 else if (*ptr != '%') *string++ = *ptr++;
775 sscanf(ptr+1, "%2X", &value);
785 #ifdef CONFIG_FEATURE_HTTPD_CGI
786 /****************************************************************************
788 > $Function: addEnv()
790 * $Description: Add an environment variable setting to the global list.
791 * A NAME=VALUE string is allocated, filled, and added to the list of
792 * environment settings passed to the cgi execution script.
795 * (char *) name_before_underline - The first part environment variable name.
796 * (char *) name_after_underline - The second part environment variable name.
797 * (char *) value . . The value to which the env variable is set.
801 * $Errors: Silently returns if the env runs out of space to hold the new item
803 ****************************************************************************/
804 static void addEnv(const char *name_before_underline,
805 const char *name_after_underline, const char *value)
808 const char *underline;
812 underline = *name_after_underline ? "_" : "";
813 asprintf(&s, "%s%s%s=%s", name_before_underline, underline,
814 name_after_underline, value);
820 #if defined(CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV) || !defined(CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY)
821 /* set environs SERVER_PORT and REMOTE_PORT */
822 static void addEnvPort(const char *port_name)
826 sprintf(buf, "%u", config->port);
827 addEnv(port_name, "PORT", buf);
830 #endif /* CONFIG_FEATURE_HTTPD_CGI */
833 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
834 /****************************************************************************
836 > $Function: decodeBase64()
838 > $Description: Decode a base 64 data stream as per rfc1521.
839 * Note that the rfc states that none base64 chars are to be ignored.
840 * Since the decode always results in a shorter size than the input, it is
841 * OK to pass the input arg as an output arg.
844 * (char *) Data . . . . A pointer to a base64 encoded string.
845 * Where to place the decoded data.
851 ****************************************************************************/
852 static void decodeBase64(char *Data)
855 const unsigned char *in = (const unsigned char *)Data;
856 // The decoded size will be at most 3/4 the size of the encoded
857 unsigned long ch = 0;
863 if(t >= '0' && t <= '9')
865 else if(t >= 'A' && t <= 'Z')
867 else if(t >= 'a' && t <= 'z')
881 *Data++ = (char) (ch >> 16);
882 *Data++ = (char) (ch >> 8);
892 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
893 /****************************************************************************
895 > $Function: openServer()
897 * $Description: create a listen server socket on the designated port.
899 * $Return: (int) . . . A connection socket. -1 for errors.
903 ****************************************************************************/
904 static int openServer(void)
906 struct sockaddr_in lsocket;
909 /* create the socket right now */
910 /* inet_addr() returns a value that is already in network order */
911 memset(&lsocket, 0, sizeof(lsocket));
912 lsocket.sin_family = AF_INET;
913 lsocket.sin_addr.s_addr = INADDR_ANY;
914 lsocket.sin_port = htons(config->port) ;
915 fd = socket(AF_INET, SOCK_STREAM, 0);
917 /* tell the OS it's OK to reuse a previous address even though */
918 /* it may still be in a close down state. Allows bind to succeed. */
921 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on)) ;
923 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)) ;
925 if (bind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket)) == 0) {
927 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
929 bb_perror_msg_and_die("bind");
932 bb_perror_msg_and_die("create socket");
936 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
938 /****************************************************************************
940 > $Function: sendHeaders()
942 * $Description: Create and send HTTP response headers.
943 * The arguments are combined and sent as one write operation. Note that
944 * IE will puke big-time if the headers are not sent in one packet and the
945 * second packet is delayed for any reason.
948 * (HttpResponseNum) responseNum . . . The result code to send.
950 * $Return: (int) . . . . writing errors
952 ****************************************************************************/
953 static int sendHeaders(HttpResponseNum responseNum)
955 char *buf = config->buf;
956 const char *responseString = "";
957 const char *infoString = 0;
958 const char *mime_type;
960 time_t timer = time(0);
965 i < (sizeof(httpResponseNames)/sizeof(httpResponseNames[0])); i++) {
966 if (httpResponseNames[i].type == responseNum) {
967 responseString = httpResponseNames[i].name;
968 infoString = httpResponseNames[i].info;
972 /* error message is HTML */
973 mime_type = responseNum == HTTP_OK ?
974 config->httpd_found.found_mime_type : "text/html";
976 /* emit the current date */
977 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
979 "HTTP/1.0 %d %s\nContent-type: %s\r\n"
980 "Date: %s\r\nConnection: close\r\n",
981 responseNum, responseString, mime_type, timeStr);
983 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
984 if (responseNum == HTTP_UNAUTHORIZED) {
985 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
989 if(responseNum == HTTP_MOVED_TEMPORARILY) {
990 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
991 config->httpd_found.found_moved_temporarily,
992 (config->query ? "?" : ""),
993 (config->query ? config->query : ""));
996 if (config->ContentLength != -1) { /* file */
997 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
998 len += sprintf(buf+len, "Last-Modified: %s\r\n%s " cont_l_fmt "\r\n",
999 timeStr, Content_length, config->ContentLength);
1001 strcat(buf, "\r\n");
1004 len += sprintf(buf+len,
1005 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
1006 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
1007 responseNum, responseString,
1008 responseNum, responseString, infoString);
1011 if (config->debugHttpd) fprintf(stderr, "Headers: '%s'", buf);
1013 return bb_full_write(a_c_w, buf, len);
1016 /****************************************************************************
1018 > $Function: getLine()
1020 * $Description: Read from the socket until an end of line char found.
1022 * Characters are read one at a time until an eol sequence is found.
1024 * $Return: (int) . . . . number of characters read. -1 if error.
1026 ****************************************************************************/
1027 static int getLine(void)
1030 char *buf = config->buf;
1032 while (read(a_c_r, buf + count, 1) == 1) {
1033 if (buf[count] == '\r') continue;
1034 if (buf[count] == '\n') {
1038 if(count < (MAX_MEMORY_BUFF-1)) /* check owerflow */
1041 if (count) return count;
1045 #ifdef CONFIG_FEATURE_HTTPD_CGI
1046 /****************************************************************************
1048 > $Function: sendCgi()
1050 * $Description: Execute a CGI script and send it's stdout back
1052 * Environment variables are set up and the script is invoked with pipes
1053 * for stdin/stdout. If a post is being done the script is fed the POST
1054 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
1057 * (const char *) url . . . . . . The requested URL (with leading /).
1058 * (int bodyLen) . . . . . . . . Length of the post body.
1059 * (const char *cookie) . . . . . For set HTTP_COOKIE.
1060 * (const char *content_type) . . For set CONTENT_TYPE.
1063 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
1067 ****************************************************************************/
1068 static int sendCgi(const char *url,
1069 const char *request, int bodyLen, const char *cookie,
1070 const char *content_type)
1072 int fromCgi[2]; /* pipe for reading data from CGI */
1073 int toCgi[2]; /* pipe for sending data to CGI */
1075 static char * argp[] = { 0, 0 };
1082 if (pipe(fromCgi) != 0) {
1085 if (pipe(toCgi) != 0) {
1098 char *purl = strdup( url );
1099 char realpath_buff[MAXPATHLEN];
1107 dup2(inFd, 0); // replace stdin with the pipe
1108 dup2(outFd, 1); // replace stdout with the pipe
1110 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1111 if (!config->debugHttpd)
1113 dup2(outFd, 2); // replace stderr with the pipe
1124 while((script = strchr( script + 1, '/' )) != NULL) {
1125 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1129 if(is_directory(purl + 1, 1, &sb) == 0) {
1130 /* not directory, found script.cgi/PATH_INFO */
1134 *script = '/'; /* is directory, find next '/' */
1136 addEnv("PATH", "INFO", script); /* set /PATH_INFO or NULL */
1137 addEnv("PATH", "", getenv("PATH"));
1138 addEnv("REQUEST", "METHOD", request);
1140 char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
1142 sprintf(uri, "%s?%s", purl, config->query);
1143 addEnv("REQUEST", "URI", uri);
1145 addEnv("REQUEST", "URI", purl);
1148 *script = '\0'; /* reduce /PATH_INFO */
1149 /* SCRIPT_FILENAME required by PHP in CGI mode */
1150 if(realpath(purl + 1, realpath_buff))
1151 addEnv("SCRIPT", "FILENAME", realpath_buff);
1154 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1155 addEnv("SCRIPT_NAME", "", purl);
1156 addEnv("QUERY_STRING", "", config->query);
1157 addEnv("SERVER", "SOFTWARE", httpdVersion);
1158 addEnv("SERVER", "PROTOCOL", "HTTP/1.0");
1159 addEnv("GATEWAY_INTERFACE", "", "CGI/1.1");
1160 addEnv("REMOTE", "ADDR", config->rmt_ip_str);
1161 #ifdef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1162 addEnvPort("REMOTE");
1167 sprintf(sbl, "%d", bodyLen);
1168 addEnv("CONTENT", "LENGTH", sbl);
1171 addEnv("HTTP", "COOKIE", cookie);
1173 addEnv("CONTENT", "TYPE", content_type);
1174 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1175 if(config->remoteuser) {
1176 addEnv("REMOTE", "USER", config->remoteuser);
1177 addEnv("AUTH_TYPE", "", "Basic");
1181 addEnv("HTTP", "REFERER", config->referer);
1183 /* set execve argp[0] without path */
1184 argp[0] = strrchr( purl, '/' ) + 1;
1185 /* but script argp[0] must have absolute path and chdiring to this */
1186 if(*realpath_buff) {
1187 script = strrchr(realpath_buff, '/');
1190 if(chdir(realpath_buff) == 0) {
1192 // now run the program. If it fails,
1193 // use _exit() so no destructors
1194 // get called and make a mess.
1195 execv(realpath_buff, argp);
1199 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1200 config->accepted_socket = 1; /* send to stdout */
1202 sendHeaders(HTTP_NOT_FOUND);
1209 /* parent process */
1211 size_t post_readed_size = 0, post_readed_idx = 0;
1217 signal(SIGPIPE, SIG_IGN);
1228 FD_SET(inFd, &readSet);
1229 if(bodyLen > 0 || post_readed_size > 0) {
1230 FD_SET(outFd, &writeSet);
1231 nfound = outFd > inFd ? outFd : inFd;
1232 if(post_readed_size == 0) {
1233 FD_SET(a_c_r, &readSet);
1237 /* Now wait on the set of sockets! */
1238 nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
1244 nfound = select(inFd + 1, &readSet, 0, 0, NULL);
1248 if (waitpid(pid, &status, WNOHANG) > 0) {
1251 if (config->debugHttpd) {
1252 if (WIFEXITED(status))
1253 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1254 if (WIFSIGNALED(status))
1255 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1260 } else if(post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1261 count = bb_full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1263 post_readed_size -= count;
1264 post_readed_idx += count;
1265 if(post_readed_size == 0)
1266 post_readed_idx = 0;
1268 post_readed_size = post_readed_idx = bodyLen = 0; /* broken pipe to CGI */
1270 } else if(bodyLen > 0 && post_readed_size == 0 && FD_ISSET(a_c_r, &readSet)) {
1271 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1272 count = safe_read(a_c_r, wbuf, count);
1274 post_readed_size += count;
1277 bodyLen = 0; /* closed */
1280 if(FD_ISSET(inFd, &readSet)) {
1282 char *rbuf = config->buf;
1285 # define PIPESIZE 4096 /* amount of buffering in a pipe */
1287 # define PIPESIZE PIPE_BUF
1289 #if PIPESIZE >= MAX_MEMORY_BUFF
1290 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1293 // There is something to read
1294 count = safe_read(inFd, rbuf, PIPESIZE);
1300 /* check to see if the user script added headers */
1301 if(strncmp(rbuf, "HTTP/1.0 200 OK\n", 4) != 0) {
1302 bb_full_write(s, "HTTP/1.0 200 OK\n", 16);
1304 if (strstr(rbuf, "ontent-") == 0) {
1305 bb_full_write(s, "Content-type: text/plain\n\n", 26);
1309 if (bb_full_write(s, rbuf, count) != count)
1313 if (config->debugHttpd)
1314 fprintf(stderr, "cgi read %d bytes\n", count);
1322 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1324 /****************************************************************************
1326 > $Function: sendFile()
1328 * $Description: Send a file response to an HTTP request
1331 * (const char *) url . . The URL requested.
1333 * $Return: (int) . . . . . . Always 0.
1335 ****************************************************************************/
1336 static int sendFile(const char *url)
1340 const char * const * table;
1341 const char * try_suffix;
1343 suffix = strrchr(url, '.');
1345 for (table = suffixTable; *table; table += 2)
1346 if(suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1347 try_suffix += strlen(suffix);
1348 if(*try_suffix == 0 || *try_suffix == '.')
1351 /* also, if not found, set default as "application/octet-stream"; */
1352 config->httpd_found.found_mime_type = *(table+1);
1353 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1357 for (cur = config->mime_a; cur; cur = cur->next) {
1358 if(strcmp(cur->before_colon, suffix) == 0) {
1359 config->httpd_found.found_mime_type = cur->after_colon;
1364 #endif /* CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1367 if (config->debugHttpd)
1368 fprintf(stderr, "Sending file '%s' Content-type: %s\n",
1369 url, config->httpd_found.found_mime_type);
1372 f = open(url, O_RDONLY);
1375 char *buf = config->buf;
1377 sendHeaders(HTTP_OK);
1378 while ((count = bb_full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1379 if (bb_full_write(a_c_w, buf, count) != count)
1385 if (config->debugHttpd)
1386 bb_perror_msg("Unable to open '%s'", url);
1388 sendHeaders(HTTP_NOT_FOUND);
1394 static int checkPermIP(void)
1398 /* This could stand some work */
1399 for (cur = config->ip_a_d; cur; cur = cur->next) {
1401 if (config->debugHttpd) {
1402 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1403 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1404 (unsigned char)(cur->ip >> 24),
1405 (unsigned char)(cur->ip >> 16),
1406 (unsigned char)(cur->ip >> 8),
1408 (unsigned char)(cur->mask >> 24),
1409 (unsigned char)(cur->mask >> 16),
1410 (unsigned char)(cur->mask >> 8),
1414 if((config->rmt_ip & cur->mask) == cur->ip)
1415 return cur->allow_deny == 'A'; /* Allow/Deny */
1418 /* if unconfigured, return 1 - access from all */
1419 return !config->flg_deny_all;
1422 /****************************************************************************
1424 > $Function: checkPerm()
1426 * $Description: Check the permission file for access password protected.
1428 * If config file isn't present, everything is allowed.
1429 * Entries are of the form you can see example from header source
1432 * (const char *) path . . . . The file path.
1433 * (const char *) request . . . User information to validate.
1435 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1437 ****************************************************************************/
1439 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1440 static int checkPerm(const char *path, const char *request)
1446 const char *prev = NULL;
1448 /* This could stand some work */
1449 for (cur = config->auth; cur; cur = cur->next) {
1450 p0 = cur->before_colon;
1451 if(prev != NULL && strcmp(prev, p0) != 0)
1452 continue; /* find next identical */
1453 p = cur->after_colon;
1455 if (config->debugHttpd)
1456 fprintf(stderr,"checkPerm: '%s' ? '%s'\n", p0, request);
1459 size_t l = strlen(p0);
1461 if(strncmp(p0, path, l) == 0 &&
1462 (l == 1 || path[l] == '/' || path[l] == 0)) {
1464 /* path match found. Check request */
1465 /* for check next /path:user:password */
1467 u = strchr(request, ':');
1469 /* bad request, ':' required */
1473 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1478 if(strncmp(p, request, u-request) != 0) {
1479 /* user uncompared */
1482 pp = strchr(p, ':');
1483 if(pp && pp[1] == '$' && pp[2] == '1' &&
1484 pp[3] == '$' && pp[4]) {
1486 cipher = pw_encrypt(u+1, pp);
1487 if (strcmp(cipher, pp) == 0)
1488 goto set_remoteuser_var; /* Ok */
1494 if (strcmp(p, request) == 0) {
1495 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1498 config->remoteuser = strdup(request);
1499 if(config->remoteuser)
1500 config->remoteuser[(u - request)] = 0;
1508 return prev == NULL;
1511 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1513 /****************************************************************************
1515 > $Function: handleIncoming()
1517 * $Description: Handle an incoming http request.
1519 ****************************************************************************/
1522 handle_sigalrm( int sig )
1524 sendHeaders(HTTP_REQUEST_TIMEOUT);
1525 config->alarm_signaled = sig;
1528 /****************************************************************************
1530 > $Function: handleIncoming()
1532 * $Description: Handle an incoming http request.
1534 ****************************************************************************/
1535 static void handleIncoming(void)
1537 char *buf = config->buf;
1544 #ifdef CONFIG_FEATURE_HTTPD_CGI
1545 const char *prequest = request_GET;
1548 char *content_type = 0;
1550 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1555 struct sigaction sa;
1557 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1558 int credentials = -1; /* if not requred this is Ok */
1561 sa.sa_handler = handle_sigalrm;
1562 sigemptyset(&sa.sa_mask);
1563 sa.sa_flags = 0; /* no SA_RESTART */
1564 sigaction(SIGALRM, &sa, NULL);
1569 (void) alarm( TIMEOUT );
1573 purl = strpbrk(buf, " \t");
1576 sendHeaders(HTTP_BAD_REQUEST);
1580 #ifdef CONFIG_FEATURE_HTTPD_CGI
1581 if(strcasecmp(buf, prequest) != 0) {
1583 if(strcasecmp(buf, prequest) != 0) {
1584 sendHeaders(HTTP_NOT_IMPLEMENTED);
1589 if(strcasecmp(buf, request_GET) != 0) {
1590 sendHeaders(HTTP_NOT_IMPLEMENTED);
1595 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1597 decodeString(buf, 0);
1598 if (count < 1 || buf[0] != '/') {
1599 /* Garbled request/URL */
1602 url = alloca(strlen(buf) + 12); /* + sizeof("/index.html\0") */
1604 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1608 /* extract url args if present */
1609 test = strchr(url, '?');
1612 config->query = test;
1615 /* algorithm stolen from libbb bb_simplify_path(),
1616 but don`t strdup and reducing trailing slash and protect out root */
1621 if (*test == '/') { /* skip duplicate (or initial) slash */
1623 } else if (*test == '.') {
1624 if (test[1] == '/' || test[1] == 0) { /* skip extra '.' */
1626 } else if ((test[1] == '.') && (test[2] == '/' || test[2] == 0)) {
1629 /* protect out root */
1632 while (*--purl != '/'); /* omit previous dir */
1640 *++purl = 0; /* so keep last character */
1641 test = purl; /* end ptr */
1643 /* If URL is directory, adding '/' */
1644 /* If URL is directory, adding '/' */
1645 if(test[-1] != '/') {
1646 if ( is_directory(url + 1, 1, &sb) ) {
1647 config->httpd_found.found_moved_temporarily = url;
1651 if (config->debugHttpd)
1652 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1656 ip_allowed = checkPermIP();
1657 while(ip_allowed && (test = strchr( test + 1, '/' )) != NULL) {
1658 /* have path1/path2 */
1660 if( is_directory(url + 1, 1, &sb) ) {
1661 /* may be having subdir config */
1662 parse_conf(url + 1, SUBDIR_PARSE);
1663 ip_allowed = checkPermIP();
1668 // read until blank line for HTTP version specified, else parse immediate
1676 if (config->debugHttpd) fprintf(stderr, "Header: '%s'\n", buf);
1679 #ifdef CONFIG_FEATURE_HTTPD_CGI
1680 /* try and do our best to parse more lines */
1681 if ((strncasecmp(buf, Content_length, 15) == 0)) {
1682 if(prequest != request_GET)
1683 length = strtol(buf + 15, 0, 0); // extra read only for POST
1684 } else if ((strncasecmp(buf, "Cookie:", 7) == 0)) {
1685 for(test = buf + 7; isspace(*test); test++)
1687 cookie = strdup(test);
1688 } else if ((strncasecmp(buf, "Content-Type:", 13) == 0)) {
1689 for(test = buf + 13; isspace(*test); test++)
1691 content_type = strdup(test);
1692 } else if ((strncasecmp(buf, "Referer:", 8) == 0)) {
1693 for(test = buf + 8; isspace(*test); test++)
1695 config->referer = strdup(test);
1699 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1700 if (strncasecmp(buf, "Authorization:", 14) == 0) {
1701 /* We only allow Basic credentials.
1702 * It shows up as "Authorization: Basic <userid:password>" where
1703 * the userid:password is base64 encoded.
1705 for(test = buf + 14; isspace(*test); test++)
1707 if (strncasecmp(test, "Basic", 5) != 0)
1710 test += 5; /* decodeBase64() skiping space self */
1712 credentials = checkPerm(url, test);
1714 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1716 } /* while extra header reading */
1719 if(config->alarm_signaled)
1722 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1723 /* protect listing [/path]/httpd_conf or IP deny */
1724 #ifdef CONFIG_FEATURE_HTTPD_CGI
1725 FORBIDDEN: /* protect listing /cgi-bin */
1727 sendHeaders(HTTP_FORBIDDEN);
1731 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1732 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1733 sendHeaders(HTTP_UNAUTHORIZED);
1738 if(config->httpd_found.found_moved_temporarily) {
1739 sendHeaders(HTTP_MOVED_TEMPORARILY);
1741 /* clear unforked memory flag */
1742 if(config->debugHttpd)
1743 config->httpd_found.found_moved_temporarily = NULL;
1748 test = url + 1; /* skip first '/' */
1750 #ifdef CONFIG_FEATURE_HTTPD_CGI
1751 /* if strange Content-Length */
1755 if (strncmp(test, "cgi-bin", 7) == 0) {
1756 if(test[7] == '/' && test[8] == 0)
1757 goto FORBIDDEN; // protect listing cgi-bin/
1758 sendCgi(url, prequest, length, cookie, content_type);
1760 if (prequest != request_GET)
1761 sendHeaders(HTTP_NOT_IMPLEMENTED);
1763 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1765 strcpy(purl, "index.html");
1766 if ( stat(test, &sb ) == 0 ) {
1767 config->ContentLength = sb.st_size;
1768 config->last_mod = sb.st_mtime;
1771 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1772 /* unset if non inetd looped */
1773 config->ContentLength = -1;
1776 #ifdef CONFIG_FEATURE_HTTPD_CGI
1784 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1785 /* from inetd don`t looping: freeing, closing automatic from exit always */
1787 if (config->debugHttpd) fprintf(stderr, "closing socket\n");
1789 # ifdef CONFIG_FEATURE_HTTPD_CGI
1792 free(config->referer);
1793 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1794 free(config->remoteuser);
1797 shutdown(a_c_w, SHUT_WR);
1799 /* Properly wait for remote to closed */
1801 FD_SET (a_c_w, &s_fd) ;
1806 retval = select (a_c_w + 1, &s_fd, NULL, NULL, &tv);
1807 } while (retval > 0 && (read (a_c_w, buf, sizeof (config->buf)) > 0));
1809 shutdown(a_c_r, SHUT_RD);
1810 close(config->accepted_socket);
1811 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1814 /****************************************************************************
1816 > $Function: miniHttpd()
1818 * $Description: The main http server function.
1820 * Given an open socket fildes, listen for new connections and farm out
1821 * the processing as a forked process.
1824 * (int) server. . . The server socket fildes.
1826 * $Return: (int) . . . . Always 0.
1828 ****************************************************************************/
1829 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1830 static int miniHttpd(int server)
1832 fd_set readfd, portfd;
1835 FD_SET(server, &portfd);
1837 /* copy the ports we are watching to the readfd set */
1841 /* Now wait INDEFINITELY on the set of sockets! */
1842 if (select(server + 1, &readfd, 0, 0, 0) > 0) {
1843 if (FD_ISSET(server, &readfd)) {
1845 struct sockaddr_in fromAddr;
1847 socklen_t fromAddrLen = sizeof(fromAddr);
1848 int s = accept(server,
1849 (struct sockaddr *)&fromAddr, &fromAddrLen);
1854 config->accepted_socket = s;
1855 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1856 #if defined(CONFIG_FEATURE_HTTPD_CGI) || defined(DEBUG)
1857 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1858 (unsigned char)(config->rmt_ip >> 24),
1859 (unsigned char)(config->rmt_ip >> 16),
1860 (unsigned char)(config->rmt_ip >> 8),
1861 config->rmt_ip & 0xff);
1862 config->port = ntohs(fromAddr.sin_port);
1864 if (config->debugHttpd) {
1865 bb_error_msg("connection from IP=%s, port %u\n",
1866 config->rmt_ip_str, config->port);
1869 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1871 /* set the KEEPALIVE option to cull dead connections */
1873 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof (on));
1875 if (config->debugHttpd || fork() == 0) {
1876 /* This is the spawned thread */
1877 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1878 /* protect reload config, may be confuse checking */
1879 signal(SIGHUP, SIG_IGN);
1882 if(!config->debugHttpd)
1895 static int miniHttpd(void)
1897 struct sockaddr_in fromAddrLen;
1898 socklen_t sinlen = sizeof (struct sockaddr_in);
1900 getpeername (0, (struct sockaddr *)&fromAddrLen, &sinlen);
1901 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1902 #if defined(CONFIG_FEATURE_HTTPD_CGI) || defined(DEBUG)
1903 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1904 (unsigned char)(config->rmt_ip >> 24),
1905 (unsigned char)(config->rmt_ip >> 16),
1906 (unsigned char)(config->rmt_ip >> 8),
1907 config->rmt_ip & 0xff);
1909 config->port = ntohs(fromAddrLen.sin_port);
1913 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1915 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1916 static void sighup_handler(int sig)
1919 struct sigaction sa;
1921 parse_conf(default_path_httpd_conf,
1922 sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1923 sa.sa_handler = sighup_handler;
1924 sigemptyset(&sa.sa_mask);
1925 sa.sa_flags = SA_RESTART;
1926 sigaction(SIGHUP, &sa, NULL);
1931 static const char httpd_opts[]="c:d:h:"
1932 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1935 #define OPT_INC_1 ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1937 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1940 #define OPT_INC_2 ENABLE_FEATURE_HTTPD_BASIC_AUTH
1942 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1945 #define OPT_INC_3 ENABLE_FEATURE_HTTPD_AUTH_MD5
1947 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1950 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1955 #define OPT_CONFIG_FILE (1<<0) /* c */
1956 #define OPT_DECODE_URL (1<<1) /* d */
1957 #define OPT_HOME_HTTPD (1<<2) /* h */
1958 #define OPT_ENCODE_URL (1<<(2+OPT_INC_1)) /* e */
1959 #define OPT_REALM (1<<(2+OPT_INC_1+OPT_INC_2)) /* r */
1960 #define OPT_MD5 (1<<(2+OPT_INC_1+OPT_INC_2+OPT_INC_3)) /* m */
1961 #define OPT_PORT (1<<(3+OPT_INC_1+OPT_INC_2+OPT_INC_3)) /* p */
1962 #define OPT_DEBUG (1<<(4+OPT_INC_1+OPT_INC_2+OPT_INC_3)) /* v */
1963 #define OPT_SETUID (1<<(5+OPT_INC_1+OPT_INC_2+OPT_INC_3)) /* u */
1966 #ifdef HTTPD_STANDALONE
1967 int main(int argc, char *argv[])
1969 int httpd_main(int argc, char *argv[])
1973 const char *home_httpd = home;
1974 char *url_for_decode;
1975 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1976 const char *url_for_encode;
1978 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1982 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1986 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1991 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1995 config = xcalloc(1, sizeof(*config));
1996 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1997 config->realm = "Web Server Authentication";
2000 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2004 config->ContentLength = -1;
2006 opt = bb_getopt_ulflags(argc, argv, httpd_opts,
2007 &(config->configFile), &url_for_decode, &home_httpd
2008 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
2011 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
2013 # ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
2017 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2019 #ifdef CONFIG_FEATURE_HTTPD_SETUID
2025 if(opt & OPT_DECODE_URL) {
2026 printf("%s", decodeString(url_for_decode, 1));
2029 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
2030 if(opt & OPT_ENCODE_URL) {
2031 printf("%s", encodeString(url_for_encode));
2035 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
2037 printf("%s\n", pw_encrypt(pass, "$1$"));
2041 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2043 config->port = bb_xgetlarg(s_port, 10, 1, 0xffff);
2044 config->debugHttpd = opt & OPT_DEBUG;
2045 #ifdef CONFIG_FEATURE_HTTPD_SETUID
2046 if(opt & OPT_SETUID) {
2049 uid = strtol(s_uid, &e, 0);
2052 uid = bb_xgetpwnam(s_uid);
2058 if(chdir(home_httpd)) {
2059 bb_perror_msg_and_die("can`t chdir to %s", home_httpd);
2061 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2062 server = openServer();
2063 # ifdef CONFIG_FEATURE_HTTPD_SETUID
2064 /* drop privileges */
2070 #ifdef CONFIG_FEATURE_HTTPD_CGI
2072 char *p = getenv("PATH");
2078 setenv("PATH", p, 1);
2079 # ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2080 addEnvPort("SERVER");
2085 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2088 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2091 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2092 if (!config->debugHttpd) {
2093 if (daemon(1, 0) < 0) /* don`t change curent directory */
2094 bb_perror_msg_and_die("daemon");
2096 return miniHttpd(server);