1 /* vi: set sw=4 ts=4: */
3 * httpd implementation for busybox
5 * Copyright (C) 2002,2003 Glenn Engel <glenne@engel.org>
6 * Copyright (C) 2003-2006 Vladimir Oleynik <dzo@simtreas.ru>
8 * simplify patch stolen from libbb without using strdup
10 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
12 *****************************************************************************
16 * httpd -p 8080 -h $HOME/public_html
17 * or for daemon start from rc script with uid=0:
19 * This is equivalent if www user have uid=80 to
20 * httpd -p 80 -u 80 -h /www -c /etc/httpd.conf -r "Web Server Authentication"
23 * When a url contains "cgi-bin" it is assumed to be a cgi script. The
24 * server changes directory to the location of the script and executes it
25 * after setting QUERY_STRING and other environment variables.
27 * The server can also be invoked as a url arg decoder and html text encoder
29 * foo=`httpd -d $foo` # decode "Hello%20World" as "Hello World"
30 * bar=`httpd -e "<Hello World>"` # encode as "<Hello World>"
31 * Note that url encoding for arguments is not the same as html encoding for
32 * presentation. -d decodes a url-encoded argument while -e encodes in html
35 * httpd.conf has the following format:
37 * A:172.20. # Allow address from 172.20.0.0/16
38 * A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
39 * A:10.0.0.0/255.255.255.128 # Allow any address that previous set
40 * A:127.0.0.1 # Allow local loopback connections
41 * D:* # Deny from other IP connections
42 * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
43 * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
44 * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
45 * .au:audio/basic # additional mime type for audio.au files
46 * *.php:/path/php # running cgi.php scripts through an interpreter
48 * A/D may be as a/d or allow/deny - first char case insensitive
49 * Deny IP rules take precedence over allow rules.
52 * The Deny/Allow IP logic:
54 * - Default is to allow all. No addresses are denied unless
55 * denied with a D: rule.
56 * - Order of Deny/Allow rules is significant
57 * - Deny rules take precedence over allow rules.
58 * - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
60 * - Specification of Allow all (A:*) is a no-op
63 * 1. Allow only specified addresses
64 * A:172.20 # Allow any address that begins with 172.20.
65 * A:10.10. # Allow any address that begins with 10.10.
66 * A:127.0.0.1 # Allow local loopback connections
67 * D:* # Deny from other IP connections
69 * 2. Only deny specified addresses
70 * D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
71 * D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
72 * A:* # (optional line added for clarity)
74 * If a sub directory contains a config file it is parsed and merged with
75 * any existing settings as if it was appended to the original configuration.
77 * subdir paths are relative to the containing subdir and thus cannot
78 * affect the parent rules.
80 * Note that since the sub dir is parsed in the forked thread servicing the
81 * subdir http request, any merge is discarded when the process exits. As a
82 * result, the subdir settings only have a lifetime of a single request.
85 * If -c is not set, an attempt will be made to open the default
86 * root configuration file. If -c is set and the file is not found, the
87 * server exits with an error.
93 #include <ctype.h> /* for isspace */
95 #include <stdlib.h> /* for malloc */
97 #include <unistd.h> /* for close */
99 #include <sys/types.h>
100 #include <sys/socket.h> /* for connect and socket*/
101 #include <netinet/in.h> /* for sockaddr_in */
102 #include <sys/time.h>
103 #include <sys/stat.h>
104 #include <sys/wait.h>
105 #include <fcntl.h> /* for open modes */
109 static const char httpdVersion[] = "busybox httpd/1.35 6-Oct-2004";
110 static const char default_path_httpd_conf[] = "/etc";
111 static const char httpd_conf[] = "httpd.conf";
112 static const char home[] = "./";
115 # define cont_l_fmt "%lld"
116 # define cont_l_type (long long)
118 # define cont_l_fmt "%ld"
119 # define cont_l_type (long)
124 // Note: busybox xfuncs are not used because we want the server to keep running
125 // if something bad happens due to a malformed user request.
126 // As a result, all memory allocation after daemonize
127 // is checked rigorously
135 #define MAX_MEMORY_BUFF 8192 /* IO buffer */
137 typedef struct HT_ACCESS {
139 struct HT_ACCESS *next;
140 char before_colon[1]; /* really bigger, must last */
143 typedef struct HT_ACCESS_IP {
147 struct HT_ACCESS_IP *next;
152 char buf[MAX_MEMORY_BUFF];
154 USE_FEATURE_HTTPD_BASIC_AUTH(const char *realm;)
155 USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
159 USE_FEATURE_HTTPD_CGI(char *referer;)
161 const char *configFile;
164 #if defined(CONFIG_FEATURE_HTTPD_CGI) || DEBUG
165 char rmt_ip_str[16]; /* for set env REMOTE_ADDR */
167 unsigned port; /* server initial port and for
168 set env REMOTE_PORT */
170 const char *found_mime_type;
171 const char *found_moved_temporarily;
174 off_t ContentLength; /* -1 - unknown */
177 Htaccess_IP *ip_a_d; /* config allow/deny lines */
179 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
180 Htaccess *auth; /* config user:password lines */
182 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
183 Htaccess *mime_a; /* config mime types */
186 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
188 # define a_c_r config->accepted_socket
189 # define a_c_w config->accepted_socket
194 volatile int alarm_signaled;
196 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
197 Htaccess *script_i; /* config script interpreters */
201 static HttpdConfig *config;
203 static const char request_GET[] = "GET"; /* size algorithic optimize */
205 static const char* const suffixTable [] = {
206 /* Warning: shorted equivalent suffix in one line must be first */
207 ".htm.html", "text/html",
208 ".jpg.jpeg", "image/jpeg",
211 ".txt.h.c.cc.cpp", "text/plain",
214 ".avi", "video/x-msvideo",
215 ".qt.mov", "video/quicktime",
216 ".mpe.mpeg", "video/mpeg",
217 ".mid.midi", "audio/midi",
218 ".mp3", "audio/mpeg",
219 #if 0 /* unpopular */
220 ".au", "audio/basic",
221 ".pac", "application/x-ns-proxy-autoconfig",
222 ".vrml.wrl", "model/vrml",
224 0, "application/octet-stream" /* default */
230 HTTP_MOVED_TEMPORARILY = 302,
231 HTTP_BAD_REQUEST = 400, /* malformed syntax */
232 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
233 HTTP_NOT_FOUND = 404,
234 HTTP_FORBIDDEN = 403,
235 HTTP_REQUEST_TIMEOUT = 408,
236 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
237 HTTP_INTERNAL_SERVER_ERROR = 500,
238 #if 0 /* future use */
240 HTTP_SWITCHING_PROTOCOLS = 101,
243 HTTP_NON_AUTHORITATIVE_INFO = 203,
244 HTTP_NO_CONTENT = 204,
245 HTTP_MULTIPLE_CHOICES = 300,
246 HTTP_MOVED_PERMANENTLY = 301,
247 HTTP_NOT_MODIFIED = 304,
248 HTTP_PAYMENT_REQUIRED = 402,
249 HTTP_BAD_GATEWAY = 502,
250 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
251 HTTP_RESPONSE_SETSIZE=0xffffffff
257 HttpResponseNum type;
262 static const HttpEnumString httpResponseNames[] = {
263 { HTTP_OK, "OK", NULL },
264 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
265 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
266 "No request appeared within a reasonable time period." },
267 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
268 "The requested method is not recognized by this server." },
269 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
270 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
272 { HTTP_NOT_FOUND, "Not Found",
273 "The requested URL was not found on this server." },
274 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
275 { HTTP_FORBIDDEN, "Forbidden", "" },
276 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
277 "Internal Server Error" },
278 #if 0 /* not implemented */
279 { HTTP_CREATED, "Created" },
280 { HTTP_ACCEPTED, "Accepted" },
281 { HTTP_NO_CONTENT, "No Content" },
282 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
283 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
284 { HTTP_NOT_MODIFIED, "Not Modified" },
285 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
286 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
291 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
292 static const char Content_length[] = "Content-length:";
296 scan_ip (const char **ep, unsigned int *ip, unsigned char endc)
303 for (j = 0; j < 4; j++) {
306 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
309 while (*p >= '0' && *p <= '9') {
318 if (*p != '/' && *p != 0)
320 *ip = ((*ip) << 8) | octet;
334 scan_ip_mask (const char *ipm, unsigned int *ip, unsigned int *mask)
339 i = scan_ip(&ipm, ip, '/');
347 if (*p < '0' || *p > '9') {
349 i = scan_ip (&ipm, mask, 0);
371 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
372 static void free_config_lines(Htaccess **pprev)
374 Htaccess *prev = *pprev;
377 Htaccess *cur = prev;
387 #define FIRST_PARSE 0
388 #define SUBDIR_PARSE 1
389 #define SIGNALED_PARSE 2
390 #define FIND_FROM_HTTPD_ROOT 3
391 /****************************************************************************
393 > $Function: parse_conf()
395 * $Description: parse configuration file into in-memory linked list.
397 * The first non-white character is examined to determine if the config line
398 * is one of the following:
399 * .ext:mime/type # new mime type not compiled into httpd
400 * [adAD]:from # ip address allow/deny, * for wildcard
401 * /path:user:pass # username/password
403 * Any previous IP rules are discarded.
404 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
405 * are also discarded. That is, previous settings are retained if flag is
409 * (const char *) path . . null for ip address checks, path for password
411 * (int) flag . . . . . . the source of the parse request.
415 ****************************************************************************/
416 static void parse_conf(const char *path, int flag)
419 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
420 Htaccess *prev, *cur;
421 #elif CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
425 const char *cf = config->configFile;
430 /* free previous ip setup if present */
431 Htaccess_IP *pip = config->ip_a_d;
434 Htaccess_IP *cur_ipl = pip;
439 config->ip_a_d = NULL;
441 config->flg_deny_all = 0;
443 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR)
444 /* retain previous auth and mime config only for subdir parse */
445 if(flag != SUBDIR_PARSE) {
446 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
447 free_config_lines(&config->auth);
449 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
450 free_config_lines(&config->mime_a);
452 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
453 free_config_lines(&config->script_i);
458 if(flag == SUBDIR_PARSE || cf == NULL) {
459 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
461 if(flag == FIRST_PARSE)
462 bb_error_msg_and_die(bb_msg_memory_exhausted);
465 sprintf((char *)cf, "%s/%s", path, httpd_conf);
468 while((f = fopen(cf, "r")) == NULL) {
469 if(flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
470 /* config file not found, no changes to config */
473 if(config->configFile && flag == FIRST_PARSE) /* if -c option given */
474 bb_perror_msg_and_die("%s", cf);
475 flag = FIND_FROM_HTTPD_ROOT;
479 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
482 /* This could stand some work */
483 while ( (p0 = fgets(buf, sizeof(buf), f)) != NULL) {
485 for(p = p0; *p0 != 0 && *p0 != '#'; p0++) {
488 if(*p0 == ':' && c == NULL)
494 /* test for empty or strange line */
495 if (c == NULL || *c == 0)
502 /* memorize deny all */
503 config->flg_deny_all++;
505 /* skip default other "word:*" config lines */
511 else if(*p0 != 'D' && *p0 != 'A'
512 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
515 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
518 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
523 if(*p0 == 'A' || *p0 == 'D') {
524 /* storing current config IP line */
525 pip = calloc(1, sizeof(Htaccess_IP));
527 if(scan_ip_mask (c, &(pip->ip), &(pip->mask))) {
528 /* syntax IP{/mask} error detected, protect all */
532 pip->allow_deny = *p0;
534 /* Deny:form_IP move top */
535 pip->next = config->ip_a_d;
536 config->ip_a_d = pip;
538 /* add to bottom A:form_IP config line */
539 Htaccess_IP *prev_IP = config->ip_a_d;
541 if(prev_IP == NULL) {
542 config->ip_a_d = pip;
545 prev_IP = prev_IP->next;
552 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
554 /* make full path from httpd root / curent_path / config_line_path */
555 cf = flag == SUBDIR_PARSE ? path : "";
556 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
560 sprintf(p0, "/%s%s", cf, buf);
562 /* another call bb_simplify_path */
567 if (*cf == '/') { /* skip duplicate (or initial) slash */
569 } else if (*cf == '.') {
570 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
572 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
575 while (*--p != '/'); /* omit previous dir */
584 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
585 ++p; /* so keep last character */
588 sprintf(p0, "%s:%s", p0, c);
592 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR)
593 /* storing current config line */
594 cur = calloc(1, sizeof(Htaccess) + strlen(p0));
596 cf = strcpy(cur->before_colon, p0);
599 cur->after_colon = c;
600 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
602 /* config .mime line move top for overwrite previous */
603 cur->next = config->mime_a;
604 config->mime_a = cur;
608 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
609 if(*cf == '*' && cf[1] == '.') {
610 /* config script interpreter line move top for overwrite previous */
611 cur->next = config->script_i;
612 config->script_i = cur;
616 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
620 config->auth = prev = cur;
622 /* sort path, if current lenght eq or bigger then move up */
623 Htaccess *prev_hti = config->auth;
624 size_t l = strlen(cf);
627 for(hti = prev_hti; hti; hti = hti->next) {
628 if(l >= strlen(hti->before_colon)) {
629 /* insert before hti */
631 if(prev_hti != hti) {
632 prev_hti->next = cur;
640 prev_hti = prev_hti->next;
642 if(!hti) { /* not inserted, add to bottom */
654 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
655 /****************************************************************************
657 > $Function: encodeString()
659 * $Description: Given a string, html encode special characters.
660 * This is used for the -e command line option to provide an easy way
661 * for scripts to encode result data without confusing browsers. The
662 * returned string pointer is memory allocated by malloc().
665 * (const char *) string . . The first string to encode.
667 * $Return: (char *) . . . .. . . A pointer to the encoded string.
669 * $Errors: Returns a null string ("") if memory is not available.
671 ****************************************************************************/
672 static char *encodeString(const char *string)
674 /* take the simple route and encode everything */
675 /* could possibly scan once to get length. */
676 int len = strlen(string);
677 char *out = malloc(len * 6 + 1);
682 while ((ch = *string++)) {
683 // very simple check for what to encode
684 if (isalnum(ch)) *p++ = ch;
685 else p += sprintf(p, "&#%d;", (unsigned char) ch);
690 #endif /* CONFIG_FEATURE_HTTPD_ENCODE_URL_STR */
692 /****************************************************************************
694 > $Function: decodeString()
696 * $Description: Given a URL encoded string, convert it to plain ascii.
697 * Since decoding always makes strings smaller, the decode is done in-place.
698 * Thus, callers should strdup() the argument if they do not want the
699 * argument modified. The return is the original pointer, allowing this
700 * function to be easily used as arguments to other functions.
703 * (char *) string . . . The first string to decode.
704 * (int) flag . . . 1 if require decode '+' as ' ' for CGI
706 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
710 ****************************************************************************/
711 static char *decodeString(char *orig, int flag_plus_to_space)
713 /* note that decoded string is always shorter than original */
719 if (*ptr == '+' && flag_plus_to_space) { *string++ = ' '; ptr++; }
720 else if (*ptr != '%') *string++ = *ptr++;
722 unsigned int value1, value2;
725 if(sscanf(ptr, "%1X", &value1) != 1 ||
726 sscanf(ptr+1, "%1X", &value2) != 1) {
727 if(!flag_plus_to_space)
731 value1 = value1 * 16 + value2;
732 if(value1 == '/' || value1 == 0)
744 #ifdef CONFIG_FEATURE_HTTPD_CGI
745 /****************************************************************************
747 > $Function: addEnv()
749 * $Description: Add an environment variable setting to the global list.
750 * A NAME=VALUE string is allocated, filled, and added to the list of
751 * environment settings passed to the cgi execution script.
754 * (char *) name_before_underline - The first part environment variable name.
755 * (char *) name_after_underline - The second part environment variable name.
756 * (char *) value . . The value to which the env variable is set.
760 * $Errors: Silently returns if the env runs out of space to hold the new item
762 ****************************************************************************/
763 static void addEnv(const char *name_before_underline,
764 const char *name_after_underline, const char *value)
767 const char *underline;
771 underline = *name_after_underline ? "_" : "";
772 asprintf(&s, "%s%s%s=%s", name_before_underline, underline,
773 name_after_underline, value);
779 #if defined(CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV) || !defined(CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY)
780 /* set environs SERVER_PORT and REMOTE_PORT */
781 static void addEnvPort(const char *port_name)
785 sprintf(buf, "%u", config->port);
786 addEnv(port_name, "PORT", buf);
789 #endif /* CONFIG_FEATURE_HTTPD_CGI */
792 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
793 /****************************************************************************
795 > $Function: decodeBase64()
797 > $Description: Decode a base 64 data stream as per rfc1521.
798 * Note that the rfc states that none base64 chars are to be ignored.
799 * Since the decode always results in a shorter size than the input, it is
800 * OK to pass the input arg as an output arg.
803 * (char *) Data . . . . A pointer to a base64 encoded string.
804 * Where to place the decoded data.
810 ****************************************************************************/
811 static void decodeBase64(char *Data)
814 const unsigned char *in = (const unsigned char *)Data;
815 // The decoded size will be at most 3/4 the size of the encoded
816 unsigned long ch = 0;
822 if(t >= '0' && t <= '9')
824 else if(t >= 'A' && t <= 'Z')
826 else if(t >= 'a' && t <= 'z')
840 *Data++ = (char) (ch >> 16);
841 *Data++ = (char) (ch >> 8);
851 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
852 /****************************************************************************
854 > $Function: openServer()
856 * $Description: create a listen server socket on the designated port.
858 * $Return: (int) . . . A connection socket. -1 for errors.
862 ****************************************************************************/
863 static int openServer(void)
865 struct sockaddr_in lsocket;
868 /* create the socket right now */
869 /* inet_addr() returns a value that is already in network order */
870 memset(&lsocket, 0, sizeof(lsocket));
871 lsocket.sin_family = AF_INET;
872 lsocket.sin_addr.s_addr = INADDR_ANY;
873 lsocket.sin_port = htons(config->port);
874 fd = bb_xsocket(AF_INET, SOCK_STREAM, 0);
875 /* tell the OS it's OK to reuse a previous address even though */
876 /* it may still be in a close down state. Allows bind to succeed. */
879 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on)) ;
881 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)) ;
883 bb_xbind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket));
884 listen(fd, 9); /* bb_xlisten? */
885 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
888 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
890 /****************************************************************************
892 > $Function: sendHeaders()
894 * $Description: Create and send HTTP response headers.
895 * The arguments are combined and sent as one write operation. Note that
896 * IE will puke big-time if the headers are not sent in one packet and the
897 * second packet is delayed for any reason.
900 * (HttpResponseNum) responseNum . . . The result code to send.
902 * $Return: (int) . . . . writing errors
904 ****************************************************************************/
905 static int sendHeaders(HttpResponseNum responseNum)
907 char *buf = config->buf;
908 const char *responseString = "";
909 const char *infoString = 0;
910 const char *mime_type;
912 time_t timer = time(0);
917 i < (sizeof(httpResponseNames)/sizeof(httpResponseNames[0])); i++) {
918 if (httpResponseNames[i].type == responseNum) {
919 responseString = httpResponseNames[i].name;
920 infoString = httpResponseNames[i].info;
924 /* error message is HTML */
925 mime_type = responseNum == HTTP_OK ?
926 config->httpd_found.found_mime_type : "text/html";
928 /* emit the current date */
929 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
931 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
932 "Date: %s\r\nConnection: close\r\n",
933 responseNum, responseString, mime_type, timeStr);
935 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
936 if (responseNum == HTTP_UNAUTHORIZED) {
937 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
941 if(responseNum == HTTP_MOVED_TEMPORARILY) {
942 len += sprintf(buf+len, "Location: %s/%s%s\r\n",
943 config->httpd_found.found_moved_temporarily,
944 (config->query ? "?" : ""),
945 (config->query ? config->query : ""));
948 if (config->ContentLength != -1) { /* file */
949 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
950 len += sprintf(buf+len, "Last-Modified: %s\r\n%s " cont_l_fmt "\r\n",
951 timeStr, Content_length, cont_l_type config->ContentLength);
956 len += sprintf(buf+len,
957 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
958 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
959 responseNum, responseString,
960 responseNum, responseString, infoString);
963 fprintf(stderr, "Headers: '%s'", buf);
965 return bb_full_write(a_c_w, buf, len);
968 /****************************************************************************
970 > $Function: getLine()
972 * $Description: Read from the socket until an end of line char found.
974 * Characters are read one at a time until an eol sequence is found.
976 * $Return: (int) . . . . number of characters read. -1 if error.
978 ****************************************************************************/
979 static int getLine(void)
982 char *buf = config->buf;
984 while (read(a_c_r, buf + count, 1) == 1) {
985 if (buf[count] == '\r') continue;
986 if (buf[count] == '\n') {
990 if(count < (MAX_MEMORY_BUFF-1)) /* check owerflow */
993 if (count) return count;
997 #ifdef CONFIG_FEATURE_HTTPD_CGI
998 /****************************************************************************
1000 > $Function: sendCgi()
1002 * $Description: Execute a CGI script and send it's stdout back
1004 * Environment variables are set up and the script is invoked with pipes
1005 * for stdin/stdout. If a post is being done the script is fed the POST
1006 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
1009 * (const char *) url . . . . . . The requested URL (with leading /).
1010 * (int bodyLen) . . . . . . . . Length of the post body.
1011 * (const char *cookie) . . . . . For set HTTP_COOKIE.
1012 * (const char *content_type) . . For set CONTENT_TYPE.
1015 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
1019 ****************************************************************************/
1020 static int sendCgi(const char *url,
1021 const char *request, int bodyLen, const char *cookie,
1022 const char *content_type)
1024 int fromCgi[2]; /* pipe for reading data from CGI */
1025 int toCgi[2]; /* pipe for sending data to CGI */
1027 static char * argp[] = { 0, 0 };
1034 if (pipe(fromCgi) != 0) {
1037 if (pipe(toCgi) != 0) {
1050 char *purl = strdup( url );
1051 char realpath_buff[MAXPATHLEN];
1059 dup2(inFd, 0); // replace stdin with the pipe
1060 dup2(outFd, 1); // replace stdout with the pipe
1062 dup2(outFd, 2); // replace stderr with the pipe
1073 while((script = strchr( script + 1, '/' )) != NULL) {
1074 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1078 if(is_directory(purl + 1, 1, &sb) == 0) {
1079 /* not directory, found script.cgi/PATH_INFO */
1083 *script = '/'; /* is directory, find next '/' */
1085 addEnv("PATH", "INFO", script); /* set /PATH_INFO or NULL */
1086 addEnv("PATH", "", getenv("PATH"));
1087 addEnv("REQUEST", "METHOD", request);
1089 char *uri = alloca(strlen(purl) + 2 + strlen(config->query));
1091 sprintf(uri, "%s?%s", purl, config->query);
1092 addEnv("REQUEST", "URI", uri);
1094 addEnv("REQUEST", "URI", purl);
1097 *script = '\0'; /* reduce /PATH_INFO */
1098 /* SCRIPT_FILENAME required by PHP in CGI mode */
1099 if(realpath(purl + 1, realpath_buff))
1100 addEnv("SCRIPT", "FILENAME", realpath_buff);
1103 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1104 addEnv("SCRIPT_NAME", "", purl);
1105 addEnv("QUERY_STRING", "", config->query);
1106 addEnv("SERVER", "SOFTWARE", httpdVersion);
1107 addEnv("SERVER", "PROTOCOL", "HTTP/1.0");
1108 addEnv("GATEWAY_INTERFACE", "", "CGI/1.1");
1109 addEnv("REMOTE", "ADDR", config->rmt_ip_str);
1110 #ifdef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1111 addEnvPort("REMOTE");
1116 sprintf(sbl, "%d", bodyLen);
1117 addEnv("CONTENT", "LENGTH", sbl);
1120 addEnv("HTTP", "COOKIE", cookie);
1122 addEnv("CONTENT", "TYPE", content_type);
1123 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1124 if(config->remoteuser) {
1125 addEnv("REMOTE", "USER", config->remoteuser);
1126 addEnv("AUTH_TYPE", "", "Basic");
1130 addEnv("HTTP", "REFERER", config->referer);
1132 /* set execve argp[0] without path */
1133 argp[0] = strrchr( purl, '/' ) + 1;
1134 /* but script argp[0] must have absolute path and chdiring to this */
1135 if(*realpath_buff) {
1136 script = strrchr(realpath_buff, '/');
1139 if(chdir(realpath_buff) == 0) {
1140 // now run the program. If it fails,
1141 // use _exit() so no destructors
1142 // get called and make a mess.
1143 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1144 char *interpr = NULL;
1145 char *suffix = strrchr(purl, '.');
1149 for (cur = config->script_i; cur; cur = cur->next)
1150 if(strcmp(cur->before_colon + 1, suffix) == 0) {
1151 interpr = cur->after_colon;
1157 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1159 execv(interpr, argp);
1162 execv(realpath_buff, argp);
1166 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1167 config->accepted_socket = 1; /* send to stdout */
1169 sendHeaders(HTTP_NOT_FOUND);
1176 /* parent process */
1178 size_t post_readed_size = 0, post_readed_idx = 0;
1184 signal(SIGPIPE, SIG_IGN);
1195 FD_SET(inFd, &readSet);
1196 if(bodyLen > 0 || post_readed_size > 0) {
1197 FD_SET(outFd, &writeSet);
1198 nfound = outFd > inFd ? outFd : inFd;
1199 if(post_readed_size == 0) {
1200 FD_SET(a_c_r, &readSet);
1204 /* Now wait on the set of sockets! */
1205 nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
1211 nfound = select(inFd + 1, &readSet, 0, 0, NULL);
1215 if (waitpid(pid, &status, WNOHANG) > 0) {
1218 if (WIFEXITED(status))
1219 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1220 if (WIFSIGNALED(status))
1221 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1225 } else if(post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1226 count = bb_full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1228 post_readed_size -= count;
1229 post_readed_idx += count;
1230 if(post_readed_size == 0)
1231 post_readed_idx = 0;
1233 post_readed_size = post_readed_idx = bodyLen = 0; /* broken pipe to CGI */
1235 } else if(bodyLen > 0 && post_readed_size == 0 && FD_ISSET(a_c_r, &readSet)) {
1236 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1237 count = safe_read(a_c_r, wbuf, count);
1239 post_readed_size += count;
1242 bodyLen = 0; /* closed */
1245 if(FD_ISSET(inFd, &readSet)) {
1247 char *rbuf = config->buf;
1250 # define PIPESIZE 4096 /* amount of buffering in a pipe */
1252 # define PIPESIZE PIPE_BUF
1254 #if PIPESIZE >= MAX_MEMORY_BUFF
1255 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1258 // There is something to read
1259 count = safe_read(inFd, rbuf, PIPESIZE);
1265 /* check to see if the user script added headers */
1266 if(strncmp(rbuf, "HTTP/1.0 200 OK\r\n", 4) != 0) {
1267 bb_full_write(s, "HTTP/1.0 200 OK\r\n", 17);
1269 if (strstr(rbuf, "ontent-") == 0) {
1270 bb_full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1274 if (bb_full_write(s, rbuf, count) != count)
1278 fprintf(stderr, "cgi read %d bytes\n", count);
1286 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1288 /****************************************************************************
1290 > $Function: sendFile()
1292 * $Description: Send a file response to an HTTP request
1295 * (const char *) url . . The URL requested.
1297 * $Return: (int) . . . . . . Always 0.
1299 ****************************************************************************/
1300 static int sendFile(const char *url)
1304 const char * const * table;
1305 const char * try_suffix;
1307 suffix = strrchr(url, '.');
1309 for (table = suffixTable; *table; table += 2)
1310 if(suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1311 try_suffix += strlen(suffix);
1312 if(*try_suffix == 0 || *try_suffix == '.')
1315 /* also, if not found, set default as "application/octet-stream"; */
1316 config->httpd_found.found_mime_type = *(table+1);
1317 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1321 for (cur = config->mime_a; cur; cur = cur->next) {
1322 if(strcmp(cur->before_colon, suffix) == 0) {
1323 config->httpd_found.found_mime_type = cur->after_colon;
1328 #endif /* CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1331 fprintf(stderr, "Sending file '%s' Content-type: %s\n",
1332 url, config->httpd_found.found_mime_type);
1335 f = open(url, O_RDONLY);
1338 char *buf = config->buf;
1340 sendHeaders(HTTP_OK);
1341 while ((count = bb_full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1342 if (bb_full_write(a_c_w, buf, count) != count)
1348 bb_perror_msg("Unable to open '%s'", url);
1350 sendHeaders(HTTP_NOT_FOUND);
1356 static int checkPermIP(void)
1360 /* This could stand some work */
1361 for (cur = config->ip_a_d; cur; cur = cur->next) {
1363 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1364 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1365 (unsigned char)(cur->ip >> 24),
1366 (unsigned char)(cur->ip >> 16),
1367 (unsigned char)(cur->ip >> 8),
1369 (unsigned char)(cur->mask >> 24),
1370 (unsigned char)(cur->mask >> 16),
1371 (unsigned char)(cur->mask >> 8),
1374 if((config->rmt_ip & cur->mask) == cur->ip)
1375 return cur->allow_deny == 'A'; /* Allow/Deny */
1378 /* if unconfigured, return 1 - access from all */
1379 return !config->flg_deny_all;
1382 /****************************************************************************
1384 > $Function: checkPerm()
1386 * $Description: Check the permission file for access password protected.
1388 * If config file isn't present, everything is allowed.
1389 * Entries are of the form you can see example from header source
1392 * (const char *) path . . . . The file path.
1393 * (const char *) request . . . User information to validate.
1395 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1397 ****************************************************************************/
1399 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1400 static int checkPerm(const char *path, const char *request)
1406 const char *prev = NULL;
1408 /* This could stand some work */
1409 for (cur = config->auth; cur; cur = cur->next) {
1410 p0 = cur->before_colon;
1411 if(prev != NULL && strcmp(prev, p0) != 0)
1412 continue; /* find next identical */
1413 p = cur->after_colon;
1415 fprintf(stderr,"checkPerm: '%s' ? '%s'\n", p0, request);
1418 size_t l = strlen(p0);
1420 if(strncmp(p0, path, l) == 0 &&
1421 (l == 1 || path[l] == '/' || path[l] == 0)) {
1423 /* path match found. Check request */
1424 /* for check next /path:user:password */
1426 u = strchr(request, ':');
1428 /* bad request, ':' required */
1432 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1437 if(strncmp(p, request, u-request) != 0) {
1438 /* user uncompared */
1441 pp = strchr(p, ':');
1442 if(pp && pp[1] == '$' && pp[2] == '1' &&
1443 pp[3] == '$' && pp[4]) {
1445 cipher = pw_encrypt(u+1, pp);
1446 if (strcmp(cipher, pp) == 0)
1447 goto set_remoteuser_var; /* Ok */
1453 if (strcmp(p, request) == 0) {
1454 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1457 config->remoteuser = strdup(request);
1458 if(config->remoteuser)
1459 config->remoteuser[(u - request)] = 0;
1467 return prev == NULL;
1470 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1472 /****************************************************************************
1474 > $Function: handle_sigalrm()
1476 * $Description: Handle timeouts
1478 ****************************************************************************/
1481 handle_sigalrm( int sig )
1483 sendHeaders(HTTP_REQUEST_TIMEOUT);
1484 config->alarm_signaled = sig;
1487 /****************************************************************************
1489 > $Function: handleIncoming()
1491 * $Description: Handle an incoming http request.
1493 ****************************************************************************/
1494 static void handleIncoming(void)
1496 char *buf = config->buf;
1503 #ifdef CONFIG_FEATURE_HTTPD_CGI
1504 const char *prequest = request_GET;
1507 char *content_type = 0;
1512 struct sigaction sa;
1514 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1515 int credentials = -1; /* if not requred this is Ok */
1518 sa.sa_handler = handle_sigalrm;
1519 sigemptyset(&sa.sa_mask);
1520 sa.sa_flags = 0; /* no SA_RESTART */
1521 sigaction(SIGALRM, &sa, NULL);
1526 (void) alarm( TIMEOUT );
1530 purl = strpbrk(buf, " \t");
1533 sendHeaders(HTTP_BAD_REQUEST);
1537 #ifdef CONFIG_FEATURE_HTTPD_CGI
1538 if(strcasecmp(buf, prequest) != 0) {
1540 if(strcasecmp(buf, prequest) != 0) {
1541 sendHeaders(HTTP_NOT_IMPLEMENTED);
1546 if(strcasecmp(buf, request_GET) != 0) {
1547 sendHeaders(HTTP_NOT_IMPLEMENTED);
1552 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1554 if (count < 1 || buf[0] != '/') {
1555 /* Garbled request/URL */
1558 url = alloca(strlen(buf) + 12); /* + sizeof("/index.html\0") */
1560 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1564 /* extract url args if present */
1565 test = strchr(url, '?');
1568 config->query = test;
1571 test = decodeString(url, 0);
1574 if(test == (buf+1)) {
1575 sendHeaders(HTTP_NOT_FOUND);
1578 /* algorithm stolen from libbb bb_simplify_path(),
1579 but don`t strdup and reducing trailing slash and protect out root */
1584 if (*test == '/') { /* skip duplicate (or initial) slash */
1586 } else if (*test == '.') {
1587 if (test[1] == '/' || test[1] == 0) { /* skip extra '.' */
1589 } else if ((test[1] == '.') && (test[2] == '/' || test[2] == 0)) {
1592 /* protect out root */
1595 while (*--purl != '/'); /* omit previous dir */
1603 *++purl = 0; /* so keep last character */
1604 test = purl; /* end ptr */
1606 /* If URL is directory, adding '/' */
1607 if(test[-1] != '/') {
1608 if ( is_directory(url + 1, 1, &sb) ) {
1609 config->httpd_found.found_moved_temporarily = url;
1613 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1617 ip_allowed = checkPermIP();
1618 while(ip_allowed && (test = strchr( test + 1, '/' )) != NULL) {
1619 /* have path1/path2 */
1621 if( is_directory(url + 1, 1, &sb) ) {
1622 /* may be having subdir config */
1623 parse_conf(url + 1, SUBDIR_PARSE);
1624 ip_allowed = checkPermIP();
1629 // read until blank line for HTTP version specified, else parse immediate
1637 fprintf(stderr, "Header: '%s'\n", buf);
1640 #ifdef CONFIG_FEATURE_HTTPD_CGI
1641 /* try and do our best to parse more lines */
1642 if ((strncasecmp(buf, Content_length, 15) == 0)) {
1643 if(prequest != request_GET)
1644 length = strtol(buf + 15, 0, 0); // extra read only for POST
1645 } else if ((strncasecmp(buf, "Cookie:", 7) == 0)) {
1646 for(test = buf + 7; isspace(*test); test++)
1648 cookie = strdup(test);
1649 } else if ((strncasecmp(buf, "Content-Type:", 13) == 0)) {
1650 for(test = buf + 13; isspace(*test); test++)
1652 content_type = strdup(test);
1653 } else if ((strncasecmp(buf, "Referer:", 8) == 0)) {
1654 for(test = buf + 8; isspace(*test); test++)
1656 config->referer = strdup(test);
1660 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1661 if (strncasecmp(buf, "Authorization:", 14) == 0) {
1662 /* We only allow Basic credentials.
1663 * It shows up as "Authorization: Basic <userid:password>" where
1664 * the userid:password is base64 encoded.
1666 for(test = buf + 14; isspace(*test); test++)
1668 if (strncasecmp(test, "Basic", 5) != 0)
1671 test += 5; /* decodeBase64() skiping space self */
1673 credentials = checkPerm(url, test);
1675 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1677 } /* while extra header reading */
1680 if(config->alarm_signaled)
1683 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1684 /* protect listing [/path]/httpd_conf or IP deny */
1685 #ifdef CONFIG_FEATURE_HTTPD_CGI
1686 FORBIDDEN: /* protect listing /cgi-bin */
1688 sendHeaders(HTTP_FORBIDDEN);
1692 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1693 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1694 sendHeaders(HTTP_UNAUTHORIZED);
1699 if(config->httpd_found.found_moved_temporarily) {
1700 sendHeaders(HTTP_MOVED_TEMPORARILY);
1702 /* clear unforked memory flag */
1703 config->httpd_found.found_moved_temporarily = NULL;
1708 test = url + 1; /* skip first '/' */
1710 #ifdef CONFIG_FEATURE_HTTPD_CGI
1711 /* if strange Content-Length */
1715 if (strncmp(test, "cgi-bin", 7) == 0) {
1716 if(test[7] == '/' && test[8] == 0)
1717 goto FORBIDDEN; // protect listing cgi-bin/
1718 sendCgi(url, prequest, length, cookie, content_type);
1720 if (prequest != request_GET)
1721 sendHeaders(HTTP_NOT_IMPLEMENTED);
1723 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1725 strcpy(purl, "index.html");
1726 if ( stat(test, &sb ) == 0 ) {
1727 config->ContentLength = sb.st_size;
1728 config->last_mod = sb.st_mtime;
1731 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1732 /* unset if non inetd looped */
1733 config->ContentLength = -1;
1736 #ifdef CONFIG_FEATURE_HTTPD_CGI
1744 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1745 /* from inetd don`t looping: freeing, closing automatic from exit always */
1747 fprintf(stderr, "closing socket\n");
1749 # ifdef CONFIG_FEATURE_HTTPD_CGI
1752 free(config->referer);
1753 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1754 free(config->remoteuser);
1757 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1758 shutdown(a_c_w, SHUT_WR);
1760 /* Properly wait for remote to closed */
1762 FD_SET (a_c_r, &s_fd) ;
1767 retval = select (a_c_r + 1, &s_fd, NULL, NULL, &tv);
1768 } while (retval > 0 && (read (a_c_r, buf, sizeof (config->buf)) > 0));
1770 shutdown(a_c_r, SHUT_RD);
1771 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1772 close(config->accepted_socket);
1773 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1776 /****************************************************************************
1778 > $Function: miniHttpd()
1780 * $Description: The main http server function.
1782 * Given an open socket fildes, listen for new connections and farm out
1783 * the processing as a forked process.
1786 * (int) server. . . The server socket fildes.
1788 * $Return: (int) . . . . Always 0.
1790 ****************************************************************************/
1791 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1792 static int miniHttpd(int server)
1794 fd_set readfd, portfd;
1797 FD_SET(server, &portfd);
1799 /* copy the ports we are watching to the readfd set */
1803 /* Now wait INDEFINITELY on the set of sockets! */
1804 if (select(server + 1, &readfd, 0, 0, 0) > 0) {
1805 if (FD_ISSET(server, &readfd)) {
1807 struct sockaddr_in fromAddr;
1809 socklen_t fromAddrLen = sizeof(fromAddr);
1810 int s = accept(server,
1811 (struct sockaddr *)&fromAddr, &fromAddrLen);
1816 config->accepted_socket = s;
1817 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1818 #if defined(CONFIG_FEATURE_HTTPD_CGI) || DEBUG
1819 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1820 (unsigned char)(config->rmt_ip >> 24),
1821 (unsigned char)(config->rmt_ip >> 16),
1822 (unsigned char)(config->rmt_ip >> 8),
1823 config->rmt_ip & 0xff);
1824 config->port = ntohs(fromAddr.sin_port);
1826 bb_error_msg("connection from IP=%s, port %u\n",
1827 config->rmt_ip_str, config->port);
1829 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1831 /* set the KEEPALIVE option to cull dead connections */
1833 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof (on));
1839 /* This is the spawned thread */
1840 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1841 /* protect reload config, may be confuse checking */
1842 signal(SIGHUP, SIG_IGN);
1859 static int miniHttpd(void)
1861 struct sockaddr_in fromAddrLen;
1862 socklen_t sinlen = sizeof (struct sockaddr_in);
1864 getpeername (0, (struct sockaddr *)&fromAddrLen, &sinlen);
1865 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1866 #ifdef CONFIG_FEATURE_HTTPD_CGI
1867 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1868 (unsigned char)(config->rmt_ip >> 24),
1869 (unsigned char)(config->rmt_ip >> 16),
1870 (unsigned char)(config->rmt_ip >> 8),
1871 config->rmt_ip & 0xff);
1873 config->port = ntohs(fromAddrLen.sin_port);
1877 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1879 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1880 static void sighup_handler(int sig)
1883 struct sigaction sa;
1885 parse_conf(default_path_httpd_conf,
1886 sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1887 sa.sa_handler = sighup_handler;
1888 sigemptyset(&sa.sa_mask);
1889 sa.sa_flags = SA_RESTART;
1890 sigaction(SIGHUP, &sa, NULL);
1894 enum httpd_opts_nums {
1895 c_opt_config_file = 0,
1898 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1899 USE_FEATURE_HTTPD_BASIC_AUTH(r_opt_realm,)
1900 USE_FEATURE_HTTPD_AUTH_MD5(m_opt_md5,)
1901 USE_FEATURE_HTTPD_SETUID(u_opt_setuid,)
1902 SKIP_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY(p_opt_port,)
1905 static const char httpd_opts[]="c:d:h:"
1906 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1907 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1908 USE_FEATURE_HTTPD_AUTH_MD5("m:")
1909 USE_FEATURE_HTTPD_SETUID("u:")
1910 SKIP_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY("p:");
1912 #define OPT_CONFIG_FILE (1<<c_opt_config_file)
1913 #define OPT_DECODE_URL (1<<d_opt_decode_url)
1914 #define OPT_HOME_HTTPD (1<<h_opt_home_httpd)
1916 #define OPT_ENCODE_URL USE_FEATURE_HTTPD_ENCODE_URL_STR((1<<e_opt_encode_url)) \
1917 SKIP_FEATURE_HTTPD_ENCODE_URL_STR(0)
1919 #define OPT_REALM USE_FEATURE_HTTPD_BASIC_AUTH((1<<r_opt_realm)) \
1920 SKIP_FEATURE_HTTPD_BASIC_AUTH(0)
1922 #define OPT_MD5 USE_FEATURE_HTTPD_AUTH_MD5((1<<m_opt_md5)) \
1923 SKIP_FEATURE_HTTPD_AUTH_MD5(0)
1925 #define OPT_SETUID USE_FEATURE_HTTPD_SETUID((1<<u_opt_setuid)) \
1926 SKIP_FEATURE_HTTPD_SETUID(0)
1928 #define OPT_PORT SKIP_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY((1<<p_opt_port)) \
1929 USE_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY(0)
1932 int httpd_main(int argc, char *argv[])
1935 const char *home_httpd = home;
1936 char *url_for_decode;
1937 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1938 SKIP_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY(const char *s_port;)
1939 SKIP_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY(int server;)
1941 USE_FEATURE_HTTPD_SETUID(const char *s_uid;)
1942 USE_FEATURE_HTTPD_SETUID(long uid = -1;)
1944 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1946 config = xcalloc(1, sizeof(*config));
1947 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1948 config->realm = "Web Server Authentication";
1951 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1955 config->ContentLength = -1;
1957 opt = bb_getopt_ulflags(argc, argv, httpd_opts,
1958 &(config->configFile), &url_for_decode, &home_httpd
1959 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1960 USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
1961 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1962 USE_FEATURE_HTTPD_SETUID(, &s_uid)
1963 SKIP_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY(, &s_port)
1966 if(opt & OPT_DECODE_URL) {
1967 printf("%s", decodeString(url_for_decode, 1));
1970 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1971 if(opt & OPT_ENCODE_URL) {
1972 printf("%s", encodeString(url_for_encode));
1976 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1978 printf("%s\n", pw_encrypt(pass, "$1$"));
1982 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1984 config->port = bb_xgetlarg(s_port, 10, 1, 0xffff);
1985 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1986 if(opt & OPT_SETUID) {
1989 uid = strtol(s_uid, &e, 0);
1992 uid = bb_xgetpwnam(s_uid);
1998 bb_xchdir(home_httpd);
1999 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2000 server = openServer();
2001 # ifdef CONFIG_FEATURE_HTTPD_SETUID
2002 /* drop privileges */
2008 #ifdef CONFIG_FEATURE_HTTPD_CGI
2010 char *p = getenv("PATH");
2016 setenv("PATH", p, 1);
2017 # ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2018 addEnvPort("SERVER");
2023 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2026 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2029 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
2031 bb_xdaemon(1, 0); /* don`t change curent directory */
2033 return miniHttpd(server);