2 * httpd implementation for busybox
4 * Copyright (C) 2002,2003 Glenn Engel <glenne@engel.org>
5 * Copyright (C) 2003 Vladimir Oleynik <dzo@simtreas.ru>
7 * simplify patch stolen from libbb without using strdup
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 *****************************************************************************
27 * httpd -p 8080 -h $HOME/public_html
28 * or for daemon start from rc script with uid=0:
30 * This is equivalent if www user have uid=80 to
31 * httpd -p 80 -u 80 -h /www -c /etc/httpd.conf -r "Web Server Authentication"
34 * When a url contains "cgi-bin" it is assumed to be a cgi script. The
35 * server changes directory to the location of the script and executes it
36 * after setting QUERY_STRING and other environment variables.
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 * presenation. -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 unsensitive
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.34 2-Oct-2003";
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"
130 // Note: bussybox xfuncs are not used because we want the server to keep running
131 // if something bad happens due to a malformed user request.
132 // As a result, all memory allocation after daemonize
133 // is checked rigorously
137 /* Configure options, disabled by default as custom httpd feature */
139 /* disabled as optional features */
140 //#define CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
141 //#define CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
142 //#define CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
143 //#define CONFIG_FEATURE_HTTPD_SETUID
144 //#define CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
146 /* If set, use this server from internet superserver only */
147 //#define CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
149 /* You can use this server as standalone, require libbb.a for linking */
150 //#define HTTPD_STANDALONE
152 /* Config options, disable this for do very small module */
153 //#define CONFIG_FEATURE_HTTPD_CGI
154 //#define CONFIG_FEATURE_HTTPD_BASIC_AUTH
155 //#define CONFIG_FEATURE_HTTPD_AUTH_MD5
157 #ifdef HTTPD_STANDALONE
158 /* standalone, enable all features */
159 #undef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
160 /* unset config option for remove warning as redefined */
161 #undef CONFIG_FEATURE_HTTPD_BASIC_AUTH
162 #undef CONFIG_FEATURE_HTTPD_AUTH_MD5
163 #undef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
164 #undef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
165 #undef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
166 #undef CONFIG_FEATURE_HTTPD_CGI
167 #undef CONFIG_FEATURE_HTTPD_SETUID
168 #undef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
169 /* enable all features now */
170 #define CONFIG_FEATURE_HTTPD_BASIC_AUTH
171 #define CONFIG_FEATURE_HTTPD_AUTH_MD5
172 #define CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
173 #define CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
174 #define CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
175 #define CONFIG_FEATURE_HTTPD_CGI
176 #define CONFIG_FEATURE_HTTPD_SETUID
177 #define CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
179 /* require from libbb.a for linking */
180 const char *bb_applet_name = "httpd";
182 void bb_show_usage(void)
184 fprintf(stderr, "Usage: %s [-p <port>] [-c configFile] [-d/-e <string>] "
185 "[-r realm] [-u user] [-h homedir]\n", bb_applet_name);
190 #ifdef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
191 #undef CONFIG_FEATURE_HTTPD_SETUID /* use inetd user.group config settings */
192 #undef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP /* so is not daemon */
193 /* inetd set stderr to accepted socket and we can`t true see debug messages */
197 #define MAX_MEMORY_BUFF 8192 /* IO buffer */
199 typedef struct HT_ACCESS {
201 struct HT_ACCESS *next;
202 char before_colon[1]; /* really bigger, must last */
205 typedef struct HT_ACCESS_IP {
209 struct HT_ACCESS_IP *next;
214 char buf[MAX_MEMORY_BUFF];
216 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
221 #ifdef CONFIG_FEATURE_HTTPD_CGI
225 const char *configFile;
228 #if defined(CONFIG_FEATURE_HTTPD_CGI) || defined(DEBUG)
229 char rmt_ip_str[16]; /* for set env REMOTE_ADDR */
231 unsigned port; /* server initial port and for
232 set env REMOTE_PORT */
234 const char *found_mime_type;
235 off_t ContentLength; /* -1 - unknown */
238 Htaccess_IP *ip_a_d; /* config allow/deny lines */
240 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
241 Htaccess *auth; /* config user:password lines */
243 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
244 Htaccess *mime_a; /* config mime types */
247 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
249 #define a_c_r config->accepted_socket
250 #define a_c_w config->accepted_socket
251 int debugHttpd; /* if seted, don`t stay daemon */
258 static HttpdConfig *config;
260 static const char request_GET[] = "GET"; /* size algorithic optimize */
262 static const char* const suffixTable [] = {
263 /* Warning: shorted equalent suffix in one line must be first */
264 ".htm.html", "text/html",
265 ".jpg.jpeg", "image/jpeg",
268 ".txt.h.c.cc.cpp", "text/plain",
271 ".avi", "video/x-msvideo",
272 ".qt.mov", "video/quicktime",
273 ".mpe.mpeg", "video/mpeg",
274 ".mid.midi", "audio/midi",
275 ".mp3", "audio/mpeg",
276 #if 0 /* unpopular */
277 ".au", "audio/basic",
278 ".pac", "application/x-ns-proxy-autoconfig",
279 ".vrml.wrl", "model/vrml",
281 0, "application/octet-stream" /* default */
287 HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
288 HTTP_NOT_FOUND = 404,
289 HTTP_NOT_IMPLEMENTED = 501, /* used for unrecognized requests */
290 HTTP_BAD_REQUEST = 400, /* malformed syntax */
291 HTTP_FORBIDDEN = 403,
292 HTTP_INTERNAL_SERVER_ERROR = 500,
293 #if 0 /* future use */
295 HTTP_SWITCHING_PROTOCOLS = 101,
298 HTTP_NON_AUTHORITATIVE_INFO = 203,
299 HTTP_NO_CONTENT = 204,
300 HTTP_MULTIPLE_CHOICES = 300,
301 HTTP_MOVED_PERMANENTLY = 301,
302 HTTP_MOVED_TEMPORARILY = 302,
303 HTTP_NOT_MODIFIED = 304,
304 HTTP_PAYMENT_REQUIRED = 402,
305 HTTP_BAD_GATEWAY = 502,
306 HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
307 HTTP_RESPONSE_SETSIZE=0xffffffff
313 HttpResponseNum type;
318 static const HttpEnumString httpResponseNames[] = {
320 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
321 "The requested method is not recognized by this server." },
322 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
323 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
325 { HTTP_NOT_FOUND, "Not Found",
326 "The requested URL was not found on this server." },
327 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
328 { HTTP_FORBIDDEN, "Forbidden", "" },
329 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
330 "Internal Server Error" },
331 #if 0 /* not implemented */
332 { HTTP_CREATED, "Created" },
333 { HTTP_ACCEPTED, "Accepted" },
334 { HTTP_NO_CONTENT, "No Content" },
335 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
336 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
337 { HTTP_MOVED_TEMPORARILY, "Moved Temporarily" },
338 { HTTP_NOT_MODIFIED, "Not Modified" },
339 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
340 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
345 static const char RFC1123FMT[] = "%a, %d %b %Y %H:%M:%S GMT";
346 static const char Content_length[] = "Content-length:";
350 scan_ip (const char **ep, unsigned int *ip, unsigned char endc)
357 for (j = 0; j < 4; j++) {
360 if ((*p < '0' || *p > '9') && (*p != '/' || j == 0) && *p != 0)
363 while (*p >= '0' && *p <= '9') {
372 if (*p != '/' && *p != 0)
374 *ip = ((*ip) << 8) | octet;
388 scan_ip_mask (const char *ipm, unsigned int *ip, unsigned int *mask)
393 i = scan_ip(&ipm, ip, '/');
401 if (*p < '0' || *p > '9') {
403 i = scan_ip (&ipm, mask, 0);
425 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
426 static void free_config_lines(Htaccess **pprev)
428 Htaccess *prev = *pprev;
431 Htaccess *cur = prev;
441 #define FIRST_PARSE 0
442 #define SUBDIR_PARSE 1
443 #define SIGNALED_PARSE 2
444 #define FIND_FROM_HTTPD_ROOT 3
445 /****************************************************************************
447 > $Function: parse_conf()
449 * $Description: parse configuration file into in-memory linked list.
451 * The first non-white character is examined to determine if the config line
452 * is one of the following:
453 * .ext:mime/type # new mime type not compiled into httpd
454 * [adAD]:from # ip address allow/deny, * for wildcard
455 * /path:user:pass # username/password
457 * Any previous IP rules are discarded.
458 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
459 * are also discarded. That is, previous settings are retained if flag is
463 * (const char *) path . . null for ip address checks, path for password
465 * (int) flag . . . . . . the source of the parse request.
469 ****************************************************************************/
470 static void parse_conf(const char *path, int flag)
473 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
474 Htaccess *prev, *cur;
475 #elif CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
479 const char *cf = config->configFile;
484 /* free previous ip setup if present */
485 Htaccess_IP *pip = config->ip_a_d;
488 Htaccess_IP *cur_ipl = pip;
493 config->ip_a_d = NULL;
495 config->flg_deny_all = 0;
497 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
498 /* retain previous auth and mime config only for subdir parse */
499 if(flag != SUBDIR_PARSE) {
500 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
501 free_config_lines(&config->auth);
503 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
504 free_config_lines(&config->mime_a);
509 if(flag == SUBDIR_PARSE || cf == NULL) {
510 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
512 if(flag == FIRST_PARSE)
513 bb_error_msg_and_die(bb_msg_memory_exhausted);
516 sprintf((char *)cf, "%s/%s", path, httpd_conf);
519 while((f = fopen(cf, "r")) == NULL) {
520 if(flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
521 /* config file not found, no changes to config */
524 if(config->configFile && flag == FIRST_PARSE) /* if -c option given */
525 bb_perror_msg_and_die("%s", cf);
526 flag = FIND_FROM_HTTPD_ROOT;
530 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
533 /* This could stand some work */
534 while ( (p0 = fgets(buf, sizeof(buf), f)) != NULL) {
536 for(p = p0; *p0 != 0 && *p0 != '#'; p0++) {
539 if(*p0 == ':' && c == NULL)
545 /* test for empty or strange line */
546 if (c == NULL || *c == 0)
553 /* memorize deny all */
554 config->flg_deny_all++;
556 /* skip default other "word:*" config lines */
562 else if(*p0 != 'D' && *p0 != 'A'
563 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
566 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
571 if(*p0 == 'A' || *p0 == 'D') {
572 /* storing current config IP line */
573 pip = calloc(1, sizeof(Htaccess_IP));
575 if(scan_ip_mask (c, &(pip->ip), &(pip->mask))) {
576 /* syntax IP{/mask} error detected, protect all */
580 pip->allow_deny = *p0;
582 /* Deny:form_IP move top */
583 pip->next = config->ip_a_d;
584 config->ip_a_d = pip;
586 /* add to bottom A:form_IP config line */
587 Htaccess_IP *prev_IP = config->ip_a_d;
589 if(prev_IP == NULL) {
590 config->ip_a_d = pip;
593 prev_IP = prev_IP->next;
600 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
602 /* make full path from httpd root / curent_path / config_line_path */
603 cf = flag == SUBDIR_PARSE ? path : "";
604 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
608 sprintf(p0, "/%s%s", cf, buf);
610 /* another call bb_simplify_path */
615 if (*cf == '/') { /* skip duplicate (or initial) slash */
617 } else if (*cf == '.') {
618 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
620 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
623 while (*--p != '/'); /* omit previous dir */
632 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
633 ++p; /* so keep last character */
636 sprintf(p0, "%s:%s", p0, c);
640 #if defined(CONFIG_FEATURE_HTTPD_BASIC_AUTH) || defined(CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES)
641 /* storing current config line */
642 cur = calloc(1, sizeof(Htaccess) + strlen(p0));
644 cf = strcpy(cur->before_colon, p0);
647 cur->after_colon = c;
648 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
650 /* config .mime line move top for overwrite previous */
651 cur->next = config->mime_a;
652 config->mime_a = cur;
656 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
660 config->auth = prev = cur;
662 /* sort path, if current lenght eq or bigger then move up */
663 Htaccess *prev_hti = config->auth;
667 for(hti = prev_hti; hti; hti = hti->next) {
668 if(l >= strlen(hti->before_colon)) {
669 /* insert before hti */
671 if(prev_hti != hti) {
672 prev_hti->next = cur;
680 prev_hti = prev_hti->next;
682 if(!hti) { /* not inserted, add to bottom */
694 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
695 /****************************************************************************
697 > $Function: encodeString()
699 * $Description: Given a string, html encode special characters.
700 * This is used for the -e command line option to provide an easy way
701 * for scripts to encode result data without confusing browsers. The
702 * returned string pointer is memory allocated by malloc().
705 * (const char *) string . . The first string to encode.
707 * $Return: (char *) . . . .. . . A pointer to the encoded string.
709 * $Errors: Returns a null string ("") if memory is not available.
711 ****************************************************************************/
712 static char *encodeString(const char *string)
714 /* take the simple route and encode everything */
715 /* could possibly scan once to get length. */
716 int len = strlen(string);
717 char *out = malloc(len*5 +1);
722 while ((ch = *string++)) {
723 // very simple check for what to encode
724 if (isalnum(ch)) *p++ = ch;
725 else p += sprintf(p, "&#%d", (unsigned char) ch);
730 #endif /* CONFIG_FEATURE_HTTPD_ENCODE_URL_STR */
732 /****************************************************************************
734 > $Function: decodeString()
736 * $Description: Given a URL encoded string, convert it to plain ascii.
737 * Since decoding always makes strings smaller, the decode is done in-place.
738 * Thus, callers should strdup() the argument if they do not want the
739 * argument modified. The return is the original pointer, allowing this
740 * function to be easily used as arguments to other functions.
743 * (char *) string . . . The first string to decode.
744 * (int) flag . . . 1 if require decode '+' as ' ' for CGI
746 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
750 ****************************************************************************/
751 static char *decodeString(char *orig, int flag_plus_to_space)
753 /* note that decoded string is always shorter than original */
759 if (*ptr == '+' && flag_plus_to_space) { *string++ = ' '; ptr++; }
760 else if (*ptr != '%') *string++ = *ptr++;
763 sscanf(ptr+1, "%2X", &value);
773 #ifdef CONFIG_FEATURE_HTTPD_CGI
774 /****************************************************************************
776 > $Function: addEnv()
778 * $Description: Add an enviornment variable setting to the global list.
779 * A NAME=VALUE string is allocated, filled, and added to the list of
780 * environment settings passed to the cgi execution script.
783 * (char *) name_before_underline - The first part environment variable name.
784 * (char *) name_after_underline - The second part environment variable name.
785 * (char *) value . . The value to which the env variable is set.
789 * $Errors: Silently returns if the env runs out of space to hold the new item
791 ****************************************************************************/
792 static void addEnv(const char *name_before_underline,
793 const char *name_after_underline, const char *value)
796 const char *underline;
800 underline = *name_after_underline ? "_" : "";
801 asprintf(&s, "%s%s%s=%s", name_before_underline, underline,
802 name_after_underline, value);
808 #if defined(CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV) || !defined(CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY)
809 /* set environs SERVER_PORT and REMOTE_PORT */
810 static void addEnvPort(const char *port_name)
814 sprintf(buf, "%u", config->port);
815 addEnv(port_name, "PORT", buf);
818 #endif /* CONFIG_FEATURE_HTTPD_CGI */
821 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
822 /****************************************************************************
824 > $Function: decodeBase64()
826 > $Description: Decode a base 64 data stream as per rfc1521.
827 * Note that the rfc states that none base64 chars are to be ignored.
828 * Since the decode always results in a shorter size than the input, it is
829 * OK to pass the input arg as an output arg.
832 * (char *) Data . . . . A pointer to a base64 encoded string.
833 * Where to place the decoded data.
839 ****************************************************************************/
840 static void decodeBase64(char *Data)
843 const unsigned char *in = Data;
844 // The decoded size will be at most 3/4 the size of the encoded
845 unsigned long ch = 0;
851 if(t >= '0' && t <= '9')
853 else if(t >= 'A' && t <= 'Z')
855 else if(t >= 'a' && t <= 'z')
869 *Data++ = (char) (ch >> 16);
870 *Data++ = (char) (ch >> 8);
880 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
881 /****************************************************************************
883 > $Function: openServer()
885 * $Description: create a listen server socket on the designated port.
887 * $Return: (int) . . . A connection socket. -1 for errors.
891 ****************************************************************************/
892 static int openServer(void)
894 struct sockaddr_in lsocket;
897 /* create the socket right now */
898 /* inet_addr() returns a value that is already in network order */
899 memset(&lsocket, 0, sizeof(lsocket));
900 lsocket.sin_family = AF_INET;
901 lsocket.sin_addr.s_addr = INADDR_ANY;
902 lsocket.sin_port = htons(config->port) ;
903 fd = socket(AF_INET, SOCK_STREAM, 0);
905 /* tell the OS it's OK to reuse a previous address even though */
906 /* it may still be in a close down state. Allows bind to succeed. */
909 setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on)) ;
911 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)) ;
913 if (bind(fd, (struct sockaddr *)&lsocket, sizeof(lsocket)) == 0) {
915 signal(SIGCHLD, SIG_IGN); /* prevent zombie (defunct) processes */
917 bb_perror_msg_and_die("bind");
920 bb_perror_msg_and_die("create socket");
924 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
926 /****************************************************************************
928 > $Function: sendHeaders()
930 * $Description: Create and send HTTP response headers.
931 * The arguments are combined and sent as one write operation. Note that
932 * IE will puke big-time if the headers are not sent in one packet and the
933 * second packet is delayed for any reason.
936 * (HttpResponseNum) responseNum . . . The result code to send.
938 * $Return: (int) . . . . writing errors
940 ****************************************************************************/
941 static int sendHeaders(HttpResponseNum responseNum)
943 char *buf = config->buf;
944 const char *responseString = "";
945 const char *infoString = 0;
947 time_t timer = time(0);
952 i < (sizeof(httpResponseNames)/sizeof(httpResponseNames[0])); i++) {
953 if (httpResponseNames[i].type == responseNum) {
954 responseString = httpResponseNames[i].name;
955 infoString = httpResponseNames[i].info;
959 if (responseNum != HTTP_OK) {
960 config->found_mime_type = "text/html"; // error message is HTML
963 /* emit the current date */
964 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&timer));
966 "HTTP/1.0 %d %s\nContent-type: %s\r\n"
967 "Date: %s\r\nConnection: close\r\n",
968 responseNum, responseString, config->found_mime_type, timeStr);
970 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
971 if (responseNum == HTTP_UNAUTHORIZED) {
972 len += sprintf(buf+len, "WWW-Authenticate: Basic realm=\"%s\"\r\n",
976 if (config->ContentLength != -1) { /* file */
977 strftime(timeStr, sizeof(timeStr), RFC1123FMT, gmtime(&config->last_mod));
978 len += sprintf(buf+len, "Last-Modified: %s\r\n%s " cont_l_fmt "\r\n",
979 timeStr, Content_length, config->ContentLength);
984 len += sprintf(buf+len,
985 "<HEAD><TITLE>%d %s</TITLE></HEAD>\n"
986 "<BODY><H1>%d %s</H1>\n%s\n</BODY>\n",
987 responseNum, responseString,
988 responseNum, responseString, infoString);
991 if (config->debugHttpd) fprintf(stderr, "Headers: '%s'", buf);
993 return bb_full_write(a_c_w, buf, len);
996 /****************************************************************************
998 > $Function: getLine()
1000 * $Description: Read from the socket until an end of line char found.
1002 * Characters are read one at a time until an eol sequence is found.
1004 * $Return: (int) . . . . number of characters read. -1 if error.
1006 ****************************************************************************/
1007 static int getLine(void)
1010 char *buf = config->buf;
1012 while (read(a_c_r, buf + count, 1) == 1) {
1013 if (buf[count] == '\r') continue;
1014 if (buf[count] == '\n') {
1018 if(count < (MAX_MEMORY_BUFF-1)) /* check owerflow */
1021 if (count) return count;
1025 #ifdef CONFIG_FEATURE_HTTPD_CGI
1026 /****************************************************************************
1028 > $Function: sendCgi()
1030 * $Description: Execute a CGI script and send it's stdout back
1032 * Environment variables are set up and the script is invoked with pipes
1033 * for stdin/stdout. If a post is being done the script is fed the POST
1034 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
1037 * (const char *) url . . . . . . The requested URL (with leading /).
1038 * (const char *urlArgs). . . . . Any URL arguments.
1039 * (int bodyLen) . . . . . . . . Length of the post body.
1040 * (const char *cookie) . . . . . For set HTTP_COOKIE.
1041 * (const char *content_type) . . For set CONTENT_TYPE.
1044 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
1048 ****************************************************************************/
1049 static int sendCgi(const char *url,
1050 const char *request, const char *urlArgs,
1051 int bodyLen, const char *cookie,
1052 const char *content_type)
1054 int fromCgi[2]; /* pipe for reading data from CGI */
1055 int toCgi[2]; /* pipe for sending data to CGI */
1057 static char * argp[] = { 0, 0 };
1064 if (pipe(fromCgi) != 0) {
1067 if (pipe(toCgi) != 0) {
1080 char *purl = strdup( url );
1081 char realpath_buff[MAXPATHLEN];
1089 dup2(inFd, 0); // replace stdin with the pipe
1090 dup2(outFd, 1); // replace stdout with the pipe
1092 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1093 if (!config->debugHttpd)
1095 dup2(outFd, 2); // replace stderr with the pipe
1106 while((script = strchr( script + 1, '/' )) != NULL) {
1107 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1111 if(is_directory(purl + 1, 1, &sb) == 0) {
1112 /* not directory, found script.cgi/PATH_INFO */
1116 *script = '/'; /* is directory, find next '/' */
1118 addEnv("PATH", "INFO", script); /* set /PATH_INFO or NULL */
1119 addEnv("PATH", "", getenv("PATH"));
1120 addEnv("REQUEST", "METHOD", request);
1122 char *uri = alloca(strlen(purl) + 2 + strlen(urlArgs));
1124 sprintf(uri, "%s?%s", purl, urlArgs);
1125 addEnv("REQUEST", "URI", uri);
1127 addEnv("REQUEST", "URI", purl);
1130 *script = '\0'; /* reduce /PATH_INFO */
1131 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1132 addEnv("SCRIPT_NAME", "", purl);
1133 addEnv("QUERY_STRING", "", urlArgs);
1134 addEnv("SERVER", "SOFTWARE", httpdVersion);
1135 addEnv("SERVER", "PROTOCOL", "HTTP/1.0");
1136 addEnv("GATEWAY_INTERFACE", "", "CGI/1.1");
1137 addEnv("REMOTE", "ADDR", config->rmt_ip_str);
1138 #ifdef CONFIG_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1139 addEnvPort("REMOTE");
1144 sprintf(sbl, "%d", bodyLen);
1145 addEnv("CONTENT", "LENGTH", sbl);
1148 addEnv("HTTP", "COOKIE", cookie);
1150 addEnv("CONTENT", "TYPE", content_type);
1151 if(config->remoteuser) {
1152 addEnv("REMOTE", "USER", config->remoteuser);
1153 addEnv("AUTH_TYPE", "", "Basic");
1156 addEnv("HTTP", "REFERER", config->referer);
1158 /* set execve argp[0] without path */
1159 argp[0] = strrchr( purl, '/' ) + 1;
1160 /* but script argp[0] must have absolute path and chdiring to this */
1161 if(realpath(purl + 1, realpath_buff) != NULL) {
1162 script = strrchr(realpath_buff, '/');
1165 if(chdir(realpath_buff) == 0) {
1167 // now run the program. If it fails,
1168 // use _exit() so no destructors
1169 // get called and make a mess.
1170 execv(realpath_buff, argp);
1174 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1175 config->accepted_socket = 1; /* send to stdout */
1177 sendHeaders(HTTP_NOT_FOUND);
1184 /* parent process */
1186 size_t post_readed_size = 0, post_readed_idx = 0;
1192 signal(SIGPIPE, SIG_IGN);
1203 FD_SET(inFd, &readSet);
1204 if(bodyLen > 0 || post_readed_size > 0) {
1205 FD_SET(outFd, &writeSet);
1206 nfound = outFd > inFd ? outFd : inFd;
1207 if(post_readed_size == 0) {
1208 FD_SET(a_c_r, &readSet);
1212 /* Now wait on the set of sockets! */
1213 nfound = select(nfound + 1, &readSet, &writeSet, 0, NULL);
1219 nfound = select(inFd + 1, &readSet, 0, 0, NULL);
1223 if (waitpid(pid, &status, WNOHANG) > 0) {
1226 if (config->debugHttpd) {
1227 if (WIFEXITED(status))
1228 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1229 if (WIFSIGNALED(status))
1230 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1235 } else if(post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1236 count = bb_full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1238 post_readed_size -= count;
1239 post_readed_idx += count;
1240 if(post_readed_size == 0)
1241 post_readed_idx = 0;
1243 } else if(bodyLen > 0 && post_readed_size == 0 && FD_ISSET(a_c_r, &readSet)) {
1244 count = bodyLen > sizeof(wbuf) ? sizeof(wbuf) : bodyLen;
1245 count = bb_full_read(a_c_r, wbuf, count);
1247 post_readed_size += count;
1250 bodyLen = 0; /* closed */
1252 } else if(FD_ISSET(inFd, &readSet)) {
1254 char *rbuf = config->buf;
1256 // There is something to read
1257 count = bb_full_read(inFd, rbuf, MAX_MEMORY_BUFF-1);
1263 /* check to see if the user script added headers */
1264 if(strncmp(rbuf, "HTTP/1.0 200 OK\n", 4) != 0) {
1265 bb_full_write(s, "HTTP/1.0 200 OK\n", 16);
1267 if (strstr(rbuf, "ontent-") == 0) {
1268 bb_full_write(s, "Content-type: text/plain\n\n", 26);
1272 bb_full_write(s, rbuf, count);
1274 if (config->debugHttpd)
1275 fprintf(stderr, "cgi read %d bytes\n", count);
1283 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1285 /****************************************************************************
1287 > $Function: sendFile()
1289 * $Description: Send a file response to an HTTP request
1292 * (const char *) url . . The URL requested.
1294 * $Return: (int) . . . . . . Always 0.
1296 ****************************************************************************/
1297 static int sendFile(const char *url)
1301 const char * const * table;
1302 const char * try_suffix;
1304 suffix = strrchr(url, '.');
1306 for (table = suffixTable; *table; table += 2)
1307 if(suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1308 try_suffix += strlen(suffix);
1309 if(*try_suffix == 0 || *try_suffix == '.')
1312 /* also, if not found, set default as "application/octet-stream"; */
1313 config->found_mime_type = *(table+1);
1314 #ifdef CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1318 for (cur = config->mime_a; cur; cur = cur->next) {
1319 if(strcmp(cur->before_colon, suffix) == 0) {
1320 config->found_mime_type = cur->after_colon;
1325 #endif /* CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1328 if (config->debugHttpd)
1329 fprintf(stderr, "Sending file '%s' Content-type: %s\n",
1330 url, config->found_mime_type);
1333 f = open(url, O_RDONLY);
1336 char *buf = config->buf;
1338 sendHeaders(HTTP_OK);
1339 while ((count = bb_full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1340 if (bb_full_write(a_c_w, buf, count) != count)
1346 if (config->debugHttpd)
1347 bb_perror_msg("Unable to open '%s'", url);
1349 sendHeaders(HTTP_NOT_FOUND);
1355 static int checkPermIP(void)
1359 /* This could stand some work */
1360 for (cur = config->ip_a_d; cur; cur = cur->next) {
1362 if (config->debugHttpd) {
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),
1375 if((config->rmt_ip & cur->mask) == cur->ip)
1376 return cur->allow_deny == 'A'; /* Allow/Deny */
1379 /* if uncofigured, return 1 - access from all */
1380 return !config->flg_deny_all;
1383 /****************************************************************************
1385 > $Function: checkPerm()
1387 * $Description: Check the permission file for access password protected.
1389 * If config file isn't present, everything is allowed.
1390 * Entries are of the form you can see example from header source
1393 * (const char *) path . . . . The file path.
1394 * (const char *) request . . . User information to validate.
1396 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1398 ****************************************************************************/
1400 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1401 static int checkPerm(const char *path, const char *request)
1407 const char *prev = NULL;
1409 /* This could stand some work */
1410 for (cur = config->auth; cur; cur = cur->next) {
1411 p0 = cur->before_colon;
1412 if(prev != NULL && strcmp(prev, p0) != 0)
1413 continue; /* find next identical */
1414 p = cur->after_colon;
1416 if (config->debugHttpd)
1417 fprintf(stderr,"checkPerm: '%s' ? '%s'\n", p0, request);
1422 if(strncmp(p0, path, l) == 0 &&
1423 (l == 1 || path[l] == '/' || path[l] == 0)) {
1425 /* path match found. Check request */
1426 /* for check next /path:user:password */
1428 u = strchr(request, ':');
1430 /* bad request, ':' required */
1434 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1439 if(strncmp(p, request, u-request) != 0) {
1440 /* user uncompared */
1443 pp = strchr(p, ':');
1444 if(pp && pp[1] == '$' && pp[2] == '1' &&
1445 pp[3] == '$' && pp[4]) {
1447 cipher = pw_encrypt(u+1, pp);
1448 if (strcmp(cipher, pp) == 0)
1449 goto set_remoteuser_var; /* Ok */
1455 if (strcmp(p, request) == 0) {
1456 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1459 config->remoteuser = strdup(request);
1460 if(config->remoteuser)
1461 config->remoteuser[(u - request)] = 0;
1469 return prev == NULL;
1472 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1475 /****************************************************************************
1477 > $Function: handleIncoming()
1479 * $Description: Handle an incoming http request.
1481 ****************************************************************************/
1482 static void handleIncoming(void)
1484 char *buf = config->buf;
1489 #ifdef CONFIG_FEATURE_HTTPD_CGI
1490 const char *prequest = request_GET;
1493 char *content_type = 0;
1499 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1500 int credentials = -1; /* if not requred this is Ok */
1509 purl = strpbrk(buf, " \t");
1512 sendHeaders(HTTP_BAD_REQUEST);
1516 #ifdef CONFIG_FEATURE_HTTPD_CGI
1517 if(strcasecmp(buf, prequest) != 0) {
1519 if(strcasecmp(buf, prequest) != 0) {
1520 sendHeaders(HTTP_NOT_IMPLEMENTED);
1525 if(strcasecmp(buf, request_GET) != 0) {
1526 sendHeaders(HTTP_NOT_IMPLEMENTED);
1531 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1533 decodeString(buf, 0);
1534 if (count < 1 || buf[0] != '/') {
1535 /* Garbled request/URL */
1538 url = alloca(strlen(buf) + 12); /* + sizeof("/index.html\0") */
1540 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1544 /* extract url args if present */
1545 urlArgs = strchr(url, '?');
1549 /* algorithm stolen from libbb bb_simplify_path(),
1550 but don`t strdup and reducing trailing slash and protect out root */
1555 if (*test == '/') { /* skip duplicate (or initial) slash */
1557 } else if (*test == '.') {
1558 if (test[1] == '/' || test[1] == 0) { /* skip extra '.' */
1560 } else if ((test[1] == '.') && (test[2] == '/' || test[2] == 0)) {
1563 /* protect out root */
1566 while (*--purl != '/'); /* omit previous dir */
1574 *++purl = 0; /* so keep last character */
1575 test = purl; /* end ptr */
1577 /* If URL is directory, adding '/' */
1578 if(test[-1] != '/') {
1579 if ( is_directory(url + 1, 1, &sb) ) {
1582 purl = test; /* end ptr */
1586 if (config->debugHttpd)
1587 fprintf(stderr, "url='%s', args=%s\n", url, urlArgs);
1591 ip_allowed = checkPermIP();
1592 while(ip_allowed && (test = strchr( test + 1, '/' )) != NULL) {
1593 /* have path1/path2 */
1595 if( is_directory(url + 1, 1, &sb) ) {
1596 /* may be having subdir config */
1597 parse_conf(url + 1, SUBDIR_PARSE);
1598 ip_allowed = checkPermIP();
1603 // read until blank line for HTTP version specified, else parse immediate
1604 while (blank >= 0 && (count = getLine()) > 0) {
1607 if (config->debugHttpd) fprintf(stderr, "Header: '%s'\n", buf);
1610 #ifdef CONFIG_FEATURE_HTTPD_CGI
1611 /* try and do our best to parse more lines */
1612 if ((strncasecmp(buf, Content_length, 15) == 0)) {
1613 if(prequest != request_GET)
1614 length = strtol(buf + 15, 0, 0); // extra read only for POST
1615 } else if ((strncasecmp(buf, "Cookie:", 7) == 0)) {
1616 for(test = buf + 7; isspace(*test); test++)
1618 cookie = strdup(test);
1619 } else if ((strncasecmp(buf, "Content-Type:", 13) == 0)) {
1620 for(test = buf + 13; isspace(*test); test++)
1622 content_type = strdup(test);
1623 } else if ((strncasecmp(buf, "Referer:", 8) == 0)) {
1624 for(test = buf + 8; isspace(*test); test++)
1626 config->referer = strdup(test);
1630 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1631 if (strncasecmp(buf, "Authorization:", 14) == 0) {
1632 /* We only allow Basic credentials.
1633 * It shows up as "Authorization: Basic <userid:password>" where
1634 * the userid:password is base64 encoded.
1636 for(test = buf + 14; isspace(*test); test++)
1638 if (strncasecmp(test, "Basic", 5) != 0)
1641 test += 5; /* decodeBase64() skiping space self */
1643 credentials = checkPerm(url, test);
1645 #endif /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1647 } /* while extra header reading */
1650 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1651 /* protect listing [/path]/httpd_conf or IP deny */
1652 #ifdef CONFIG_FEATURE_HTTPD_CGI
1653 FORBIDDEN: /* protect listing /cgi-bin */
1655 sendHeaders(HTTP_FORBIDDEN);
1659 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1660 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1661 sendHeaders(HTTP_UNAUTHORIZED);
1666 test = url + 1; /* skip first '/' */
1668 #ifdef CONFIG_FEATURE_HTTPD_CGI
1669 /* if strange Content-Length */
1673 if (strncmp(test, "cgi-bin", 7) == 0) {
1674 if(test[7] == '/' && test[8] == 0)
1675 goto FORBIDDEN; // protect listing cgi-bin/
1676 sendCgi(url, prequest, urlArgs, length, cookie, content_type);
1678 if (prequest != request_GET)
1679 sendHeaders(HTTP_NOT_IMPLEMENTED);
1681 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1683 strcpy(purl, "index.html");
1684 if ( stat(test, &sb ) == 0 ) {
1685 config->ContentLength = sb.st_size;
1686 config->last_mod = sb.st_mtime;
1689 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1690 /* unset if non inetd looped */
1691 config->ContentLength = -1;
1694 #ifdef CONFIG_FEATURE_HTTPD_CGI
1702 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1703 /* from inetd don`t looping: freeing, closing automatic from exit always */
1705 if (config->debugHttpd) fprintf(stderr, "closing socket\n");
1707 # ifdef CONFIG_FEATURE_HTTPD_CGI
1710 free(config->remoteuser);
1711 free(config->referer);
1713 shutdown(a_c_w, SHUT_WR);
1714 shutdown(a_c_r, SHUT_RD);
1715 close(config->accepted_socket);
1716 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1719 /****************************************************************************
1721 > $Function: miniHttpd()
1723 * $Description: The main http server function.
1725 * Given an open socket fildes, listen for new connections and farm out
1726 * the processing as a forked process.
1729 * (int) server. . . The server socket fildes.
1731 * $Return: (int) . . . . Always 0.
1733 ****************************************************************************/
1734 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1735 static int miniHttpd(int server)
1737 fd_set readfd, portfd;
1740 FD_SET(server, &portfd);
1742 /* copy the ports we are watching to the readfd set */
1746 /* Now wait INDEFINATELY on the set of sockets! */
1747 if (select(server + 1, &readfd, 0, 0, 0) > 0) {
1748 if (FD_ISSET(server, &readfd)) {
1750 struct sockaddr_in fromAddr;
1752 socklen_t fromAddrLen = sizeof(fromAddr);
1753 int s = accept(server,
1754 (struct sockaddr *)&fromAddr, &fromAddrLen);
1759 config->accepted_socket = s;
1760 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1761 #if defined(CONFIG_FEATURE_HTTPD_CGI) || defined(DEBUG)
1762 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1763 (unsigned char)(config->rmt_ip >> 24),
1764 (unsigned char)(config->rmt_ip >> 16),
1765 (unsigned char)(config->rmt_ip >> 8),
1766 config->rmt_ip & 0xff);
1767 config->port = ntohs(fromAddr.sin_port);
1769 if (config->debugHttpd) {
1770 bb_error_msg("connection from IP=%s, port %u\n",
1771 config->rmt_ip_str, config->port);
1774 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1776 /* set the KEEPALIVE option to cull dead connections */
1778 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof (on));
1780 if (config->debugHttpd || fork() == 0) {
1781 /* This is the spawned thread */
1782 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1783 /* protect reload config, may be confuse checking */
1784 signal(SIGHUP, SIG_IGN);
1787 if(!config->debugHttpd)
1800 static int miniHttpd(void)
1802 struct sockaddr_in fromAddrLen;
1803 socklen_t sinlen = sizeof (struct sockaddr_in);
1805 getpeername (0, (struct sockaddr *)&fromAddrLen, &sinlen);
1806 config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1807 #if defined(CONFIG_FEATURE_HTTPD_CGI) || defined(DEBUG)
1808 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1809 (unsigned char)(config->rmt_ip >> 24),
1810 (unsigned char)(config->rmt_ip >> 16),
1811 (unsigned char)(config->rmt_ip >> 8),
1812 config->rmt_ip & 0xff);
1814 config->port = ntohs(fromAddrLen.sin_port);
1818 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1820 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1821 static void sighup_handler(int sig)
1824 struct sigaction sa;
1826 parse_conf(default_path_httpd_conf,
1827 sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1828 sa.sa_handler = sighup_handler;
1829 sigemptyset(&sa.sa_mask);
1830 sa.sa_flags = SA_RESTART;
1831 sigaction(SIGHUP, &sa, NULL);
1836 static const char httpd_opts[]="c:d:h:"
1837 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1843 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1845 # ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1847 # define OPT_INC_2 2
1849 # define OPT_INC_2 1
1854 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1856 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1859 #endif /* CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY */
1862 #define OPT_CONFIG_FILE (1<<0)
1863 #define OPT_DECODE_URL (1<<1)
1864 #define OPT_HOME_HTTPD (1<<2)
1865 #define OPT_ENCODE_URL (1<<(2+OPT_INC_1))
1866 #define OPT_REALM (1<<(3+OPT_INC_1))
1867 #define OPT_MD5 (1<<(4+OPT_INC_1))
1868 #define OPT_PORT (1<<(3+OPT_INC_1+OPT_INC_2))
1869 #define OPT_DEBUG (1<<(4+OPT_INC_1+OPT_INC_2))
1870 #define OPT_SETUID (1<<(5+OPT_INC_1+OPT_INC_2))
1873 #ifdef HTTPD_STANDALONE
1874 int main(int argc, char *argv[])
1876 int httpd_main(int argc, char *argv[])
1880 const char *home_httpd = home;
1881 char *url_for_decode;
1882 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1883 const char *url_for_encode;
1885 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1889 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1893 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1898 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1902 config = xcalloc(1, sizeof(*config));
1903 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1904 config->realm = "Web Server Authentication";
1907 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1911 config->ContentLength = -1;
1913 opt = bb_getopt_ulflags(argc, argv, httpd_opts,
1914 &(config->configFile), &url_for_decode, &home_httpd
1915 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1918 #ifdef CONFIG_FEATURE_HTTPD_BASIC_AUTH
1920 # ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1924 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1926 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1932 if(opt & OPT_DECODE_URL) {
1933 printf("%s", decodeString(url_for_decode, 1));
1936 #ifdef CONFIG_FEATURE_HTTPD_ENCODE_URL_STR
1937 if(opt & OPT_ENCODE_URL) {
1938 printf("%s", encodeString(url_for_encode));
1942 #ifdef CONFIG_FEATURE_HTTPD_AUTH_MD5
1944 printf("%s\n", pw_encrypt(pass, "$1$"));
1948 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1950 config->port = bb_xgetlarg(s_port, 10, 1, 0xffff);
1951 config->debugHttpd = opt & OPT_DEBUG;
1952 #ifdef CONFIG_FEATURE_HTTPD_SETUID
1953 if(opt & OPT_SETUID) {
1956 uid = strtol(s_uid, &e, 0);
1959 uid = my_getpwnam(s_uid);
1965 if(chdir(home_httpd)) {
1966 bb_perror_msg_and_die("can`t chdir to %s", home_httpd);
1968 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1969 server = openServer();
1970 # ifdef CONFIG_FEATURE_HTTPD_SETUID
1971 /* drop privilegies */
1977 #ifdef CONFIG_FEATURE_HTTPD_CGI
1979 char *p = getenv("PATH");
1985 setenv("PATH", p, 1);
1986 # ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1987 addEnvPort("SERVER");
1992 #ifdef CONFIG_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1995 parse_conf(default_path_httpd_conf, FIRST_PARSE);
1998 #ifndef CONFIG_FEATURE_HTTPD_USAGE_FROM_INETD_ONLY
1999 if (!config->debugHttpd) {
2000 if (daemon(1, 0) < 0) /* don`t change curent directory */
2001 bb_perror_msg_and_die("daemon");
2003 return miniHttpd(server);