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.
28 * "CGI Environment Variables": http://hoohoo.ncsa.uiuc.edu/cgi/env.html
30 * The server can also be invoked as a url arg decoder and html text encoder
32 * foo=`httpd -d $foo` # decode "Hello%20World" as "Hello World"
33 * bar=`httpd -e "<Hello World>"` # encode as "<Hello World>"
34 * Note that url encoding for arguments is not the same as html encoding for
35 * presentation. -d decodes a url-encoded argument while -e encodes in html
38 * httpd.conf has the following format:
40 * A:172.20. # Allow address from 172.20.0.0/16
41 * A:10.0.0.0/25 # Allow any address from 10.0.0.0-10.0.0.127
42 * A:10.0.0.0/255.255.255.128 # Allow any address that previous set
43 * A:127.0.0.1 # Allow local loopback connections
44 * D:* # Deny from other IP connections
45 * /cgi-bin:foo:bar # Require user foo, pwd bar on urls starting with /cgi-bin/
46 * /adm:admin:setup # Require user admin, pwd setup on urls starting with /adm/
47 * /adm:toor:PaSsWd # or user toor, pwd PaSsWd on urls starting with /adm/
48 * .au:audio/basic # additional mime type for audio.au files
49 * *.php:/path/php # running cgi.php scripts through an interpreter
51 * A/D may be as a/d or allow/deny - first char case insensitive
52 * Deny IP rules take precedence over allow rules.
55 * The Deny/Allow IP logic:
57 * - Default is to allow all. No addresses are denied unless
58 * denied with a D: rule.
59 * - Order of Deny/Allow rules is significant
60 * - Deny rules take precedence over allow rules.
61 * - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
63 * - Specification of Allow all (A:*) is a no-op
66 * 1. Allow only specified addresses
67 * A:172.20 # Allow any address that begins with 172.20.
68 * A:10.10. # Allow any address that begins with 10.10.
69 * A:127.0.0.1 # Allow local loopback connections
70 * D:* # Deny from other IP connections
72 * 2. Only deny specified addresses
73 * D:1.2.3. # deny from 1.2.3.0 - 1.2.3.255
74 * D:2.3.4. # deny from 2.3.4.0 - 2.3.4.255
75 * A:* # (optional line added for clarity)
77 * If a sub directory contains a config file it is parsed and merged with
78 * any existing settings as if it was appended to the original configuration.
80 * subdir paths are relative to the containing subdir and thus cannot
81 * affect the parent rules.
83 * Note that since the sub dir is parsed in the forked thread servicing the
84 * subdir http request, any merge is discarded when the process exits. As a
85 * result, the subdir settings only have a lifetime of a single request.
88 * If -c is not set, an attempt will be made to open the default
89 * root configuration file. If -c is set and the file is not found, the
90 * server exits with an error.
95 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
96 #include <sys/sendfile.h>
99 /* amount of buffering in a pipe */
101 # define PIPE_BUF 4096
104 static const char default_path_httpd_conf[] ALIGN1 = "/etc";
105 static const char httpd_conf[] ALIGN1 = "httpd.conf";
109 // Note: busybox xfuncs are not used because we want the server to keep running
110 // if something bad happens due to a malformed user request.
111 // As a result, all memory allocation after daemonize
112 // is checked rigorously
117 #define MAX_MEMORY_BUF 8192 /* IO buffer */
119 typedef struct Htaccess {
121 struct Htaccess *next;
122 char before_colon[1]; /* really bigger, must be last */
125 typedef struct Htaccess_IP {
129 struct Htaccess_IP *next;
136 volatile smallint alarm_signaled;
137 smallint flg_deny_all;
140 unsigned tcp_port; /* for set env REMOTE_PORT */
141 const char *bind_addr_or_port;
144 const char *configFile;
145 const char *home_httpd;
147 const char *found_mime_type;
148 const char *found_moved_temporarily;
150 off_t ContentLength; /* -1 - unknown */
151 Htaccess_IP *ip_a_d; /* config allow/deny lines */
153 USE_FEATURE_HTTPD_BASIC_AUTH(const char *g_realm;)
154 USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
155 USE_FEATURE_HTTPD_CGI(char *referer;)
156 USE_FEATURE_HTTPD_CGI(char *user_agent;)
158 char *rmt_ip_str; /* for set env REMOTE_ADDR */
160 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
161 Htaccess *g_auth; /* config user:password lines */
163 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
164 Htaccess *mime_a; /* config mime types */
166 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
167 Htaccess *script_i; /* config script interpreters */
169 char iobuf[MAX_MEMORY_BUF];
171 #define G (*ptr_to_globals)
172 #define server_socket (G.server_socket )
173 #define accepted_socket (G.accepted_socket )
174 #define verbose (G.verbose )
175 #define alarm_signaled (G.alarm_signaled )
176 #define flg_deny_all (G.flg_deny_all )
177 #define rmt_ip (G.rmt_ip )
178 #define tcp_port (G.tcp_port )
179 #define bind_addr_or_port (G.bind_addr_or_port)
180 #define g_query (G.g_query )
181 #define configFile (G.configFile )
182 #define home_httpd (G.home_httpd )
183 #define found_mime_type (G.found_mime_type )
184 #define found_moved_temporarily (G.found_moved_temporarily)
185 #define ContentLength (G.ContentLength )
186 #define last_mod (G.last_mod )
187 #define ip_a_d (G.ip_a_d )
188 #define g_realm (G.g_realm )
189 #define remoteuser (G.remoteuser )
190 #define referer (G.referer )
191 #define user_agent (G.user_agent )
192 #define rmt_ip_str (G.rmt_ip_str )
193 #define g_auth (G.g_auth )
194 #define mime_a (G.mime_a )
195 #define script_i (G.script_i )
196 #define iobuf (G.iobuf )
197 #define INIT_G() do { \
198 PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
199 USE_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
200 bind_addr_or_port = "80"; \
201 ContentLength = -1; \
204 static const char request_GET[] ALIGN1 = "GET"; /* size algorithmic optimize */
206 static const char *const suffixTable[] = {
207 /* Warning: shorter equivalent suffix in one line must be first */
208 ".htm.html", "text/html",
209 ".jpg.jpeg", "image/jpeg",
212 ".txt.h.c.cc.cpp", "text/plain",
215 ".avi", "video/x-msvideo",
216 ".qt.mov", "video/quicktime",
217 ".mpe.mpeg", "video/mpeg",
218 ".mid.midi", "audio/midi",
219 ".mp3", "audio/mpeg",
220 #if 0 /* unpopular */
221 ".au", "audio/basic",
222 ".pac", "application/x-ns-proxy-autoconfig",
223 ".vrml.wrl", "model/vrml",
225 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
256 HttpResponseNum type;
261 static const HttpEnumString httpResponseNames[] = {
262 { HTTP_OK, "OK", NULL },
263 { HTTP_MOVED_TEMPORARILY, "Found", "Directories must end with a slash." },
264 { HTTP_REQUEST_TIMEOUT, "Request Timeout",
265 "No request appeared within a reasonable time period." },
266 { HTTP_NOT_IMPLEMENTED, "Not Implemented",
267 "The requested method is not recognized by this server." },
268 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
269 { HTTP_UNAUTHORIZED, "Unauthorized", "" },
271 { HTTP_NOT_FOUND, "Not Found",
272 "The requested URL was not found on this server." },
273 { HTTP_BAD_REQUEST, "Bad Request", "Unsupported method." },
274 { HTTP_FORBIDDEN, "Forbidden", "" },
275 { HTTP_INTERNAL_SERVER_ERROR, "Internal Server Error",
276 "Internal Server Error" },
277 #if 0 /* not implemented */
278 { HTTP_CREATED, "Created" },
279 { HTTP_ACCEPTED, "Accepted" },
280 { HTTP_NO_CONTENT, "No Content" },
281 { HTTP_MULTIPLE_CHOICES, "Multiple Choices" },
282 { HTTP_MOVED_PERMANENTLY, "Moved Permanently" },
283 { HTTP_NOT_MODIFIED, "Not Modified" },
284 { HTTP_BAD_GATEWAY, "Bad Gateway", "" },
285 { HTTP_SERVICE_UNAVAILABLE, "Service Unavailable", "" },
290 static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
293 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
296 static int scan_ip(const char **ep, unsigned *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;
333 static int scan_ip_mask(const char *ipm, unsigned *ip, unsigned *mask)
338 i = scan_ip(&ipm, ip, '/');
346 if (*p < '0' || *p > '9') {
348 i = scan_ip(&ipm, mask, 0);
370 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
371 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
372 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
373 static void free_config_lines(Htaccess **pprev)
375 Htaccess *prev = *pprev;
378 Htaccess *cur = prev;
388 #define FIRST_PARSE 0
389 #define SUBDIR_PARSE 1
390 #define SIGNALED_PARSE 2
391 #define FIND_FROM_HTTPD_ROOT 3
392 /****************************************************************************
394 > $Function: parse_conf()
396 * $Description: parse configuration file into in-memory linked list.
398 * The first non-white character is examined to determine if the config line
399 * is one of the following:
400 * .ext:mime/type # new mime type not compiled into httpd
401 * [adAD]:from # ip address allow/deny, * for wildcard
402 * /path:user:pass # username/password
404 * Any previous IP rules are discarded.
405 * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
406 * are also discarded. That is, previous settings are retained if flag is
410 * (const char *) path . . null for ip address checks, path for password
412 * (int) flag . . . . . . the source of the parse request.
416 ****************************************************************************/
417 static void parse_conf(const char *path, int flag)
420 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
423 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
424 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
425 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
429 const char *cf = configFile;
434 /* free previous ip setup if present */
435 Htaccess_IP *pip = ip_a_d;
438 Htaccess_IP *cur_ipl = pip;
447 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
448 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
449 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
450 /* retain previous auth and mime config only for subdir parse */
451 if (flag != SUBDIR_PARSE) {
452 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
453 free_config_lines(&g_auth);
455 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
456 free_config_lines(&mime_a);
458 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
459 free_config_lines(&script_i);
464 if (flag == SUBDIR_PARSE || cf == NULL) {
465 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
467 if (flag == FIRST_PARSE)
468 bb_error_msg_and_die(bb_msg_memory_exhausted);
471 sprintf((char *)cf, "%s/%s", path, httpd_conf);
474 while ((f = fopen(cf, "r")) == NULL) {
475 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
476 /* config file not found, no changes to config */
479 if (configFile && flag == FIRST_PARSE) /* if -c option given */
480 bb_perror_msg_and_die("%s", cf);
481 flag = FIND_FROM_HTTPD_ROOT;
485 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
488 /* This could stand some work */
489 while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
491 for (p = p0; *p0 != 0 && *p0 != '#'; p0++) {
494 if (*p0 == ':' && c == NULL)
500 /* test for empty or strange line */
501 if (c == NULL || *c == 0)
508 /* memorize deny all */
511 /* skip default other "word:*" config lines */
517 else if (*p0 != 'D' && *p0 != 'A'
518 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
521 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
524 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
529 if (*p0 == 'A' || *p0 == 'D') {
530 /* storing current config IP line */
531 pip = xzalloc(sizeof(Htaccess_IP));
533 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
534 /* syntax IP{/mask} error detected, protect all */
538 pip->allow_deny = *p0;
540 /* Deny:form_IP move top */
544 /* add to bottom A:form_IP config line */
545 Htaccess_IP *prev_IP = ip_a_d;
547 if (prev_IP == NULL) {
550 while (prev_IP->next)
551 prev_IP = prev_IP->next;
558 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
560 /* make full path from httpd root / curent_path / config_line_path */
561 cf = flag == SUBDIR_PARSE ? path : "";
562 p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
566 sprintf(p0, "/%s%s", cf, buf);
568 /* another call bb_simplify_path */
573 if (*cf == '/') { /* skip duplicate (or initial) slash */
575 } else if (*cf == '.') {
576 if (cf[1] == '/' || cf[1] == 0) { /* remove extra '.' */
578 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == 0)) {
581 while (*--p != '/') /* omit previous dir */;
590 if ((p == p0) || (*p != '/')) { /* not a trailing slash */
591 ++p; /* so keep last character */
594 sprintf(p0, "%s:%s", p0, c);
598 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
599 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
600 || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
601 /* storing current config line */
602 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
604 cf = strcpy(cur->before_colon, p0);
607 cur->after_colon = c;
608 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
610 /* config .mime line move top for overwrite previous */
616 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
617 if (*cf == '*' && cf[1] == '.') {
618 /* config script interpreter line move top for overwrite previous */
619 cur->next = script_i;
624 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
630 /* sort path, if current lenght eq or bigger then move up */
631 Htaccess *prev_hti = g_auth;
632 size_t l = strlen(cf);
635 for (hti = prev_hti; hti; hti = hti->next) {
636 if (l >= strlen(hti->before_colon)) {
637 /* insert before hti */
639 if (prev_hti != hti) {
640 prev_hti->next = cur;
648 prev_hti = prev_hti->next;
650 if (!hti) { /* not inserted, add to bottom */
662 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
663 /****************************************************************************
665 > $Function: encodeString()
667 * $Description: Given a string, html encode special characters.
668 * This is used for the -e command line option to provide an easy way
669 * for scripts to encode result data without confusing browsers. The
670 * returned string pointer is memory allocated by malloc().
673 * (const char *) string . . The first string to encode.
675 * $Return: (char *) . . . .. . . A pointer to the encoded string.
677 * $Errors: Returns a null string ("") if memory is not available.
679 ****************************************************************************/
680 static char *encodeString(const char *string)
682 /* take the simple route and encode everything */
683 /* could possibly scan once to get length. */
684 int len = strlen(string);
685 char *out = xmalloc(len * 6 + 1);
689 while ((ch = *string++)) {
690 // very simple check for what to encode
691 if (isalnum(ch)) *p++ = ch;
692 else p += sprintf(p, "&#%d;", (unsigned char) ch);
697 #endif /* FEATURE_HTTPD_ENCODE_URL_STR */
699 /****************************************************************************
701 > $Function: decodeString()
703 * $Description: Given a URL encoded string, convert it to plain ascii.
704 * Since decoding always makes strings smaller, the decode is done in-place.
705 * Thus, callers should strdup() the argument if they do not want the
706 * argument modified. The return is the original pointer, allowing this
707 * function to be easily used as arguments to other functions.
710 * (char *) string . . . The first string to decode.
711 * (int) option_d . . 1 if called for httpd -d
713 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
717 ****************************************************************************/
718 static char *decodeString(char *orig, int option_d)
720 /* note that decoded string is always shorter than original */
725 while ((c = *ptr++) != '\0') {
726 unsigned value1, value2;
728 if (option_d && c == '+') {
736 if (sscanf(ptr, "%1X", &value1) != 1
737 || sscanf(ptr+1, "%1X", &value2) != 1
744 value1 = value1 * 16 + value2;
745 if (!option_d && (value1 == '/' || value1 == '\0')) {
746 /* caller takes it as indication of invalid
747 * (dangerous wrt exploits) chars */
758 #if ENABLE_FEATURE_HTTPD_CGI
759 /****************************************************************************
761 ****************************************************************************/
762 static void setenv1(const char *name, const char *value)
766 setenv(name, value, 1);
768 static void setenv_long(const char *name, long value)
770 char buf[sizeof(value)*3 + 2];
771 sprintf(buf, "%ld", value);
772 setenv(name, buf, 1);
776 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
778 * Decode a base 64 data stream as per rfc1521.
779 * Note that the rfc states that non base64 chars are to be ignored.
780 * Since the decode always results in a shorter size than the input, it is
781 * OK to pass the input arg as an output arg.
782 * Parameter: a pointer to a base64 encoded string.
783 * Decoded data is stored in-place.
785 static void decodeBase64(char *Data)
787 const unsigned char *in = (const unsigned char *)Data;
788 // The decoded size will be at most 3/4 the size of the encoded
795 if (t >= '0' && t <= '9')
797 else if (t >= 'A' && t <= 'Z')
799 else if (t >= 'a' && t <= 'z')
813 *Data++ = (char) (ch >> 16);
814 *Data++ = (char) (ch >> 8);
824 /****************************************************************************
826 > $Function: openServer()
828 * $Description: create a listen server socket on the designated port.
830 * $Return: (int) . . . A connection socket. -1 for errors.
834 ****************************************************************************/
836 static int openServer(void)
838 int n = bb_strtou(bind_addr_or_port, NULL, 10);
839 if (!errno && n && n <= 0xffff)
840 n = create_and_bind_stream_or_die(NULL, n);
842 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
849 * Create and send HTTP response headers.
850 * The arguments are combined and sent as one write operation. Note that
851 * IE will puke big-time if the headers are not sent in one packet and the
852 * second packet is delayed for any reason.
853 * responseNum - the result code to send.
854 * Return result of write().
856 static int sendHeaders(HttpResponseNum responseNum)
858 const char *responseString = "";
859 const char *infoString = NULL;
860 const char *mime_type;
862 time_t timer = time(0);
866 for (i = 0; i < ARRAY_SIZE(httpResponseNames); i++) {
867 if (httpResponseNames[i].type == responseNum) {
868 responseString = httpResponseNames[i].name;
869 infoString = httpResponseNames[i].info;
873 /* error message is HTML */
874 mime_type = responseNum == HTTP_OK ?
875 found_mime_type : "text/html";
878 write(2, iobuf, sprintf(iobuf, "%s response:%u\n", rmt_ip_str, responseNum));
880 /* emit the current date */
881 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
883 "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
884 "Date: %s\r\nConnection: close\r\n",
885 responseNum, responseString, mime_type, tmp_str);
887 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
888 if (responseNum == HTTP_UNAUTHORIZED) {
889 len += sprintf(iobuf + len,
890 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
894 if (responseNum == HTTP_MOVED_TEMPORARILY) {
895 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
896 found_moved_temporarily,
897 (g_query ? "?" : ""),
898 (g_query ? g_query : ""));
901 if (ContentLength != -1) { /* file */
902 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
903 len += sprintf(iobuf + len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
904 tmp_str, "Content-length:", ContentLength);
906 strcat(iobuf, "\r\n");
909 len += sprintf(iobuf + len,
910 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
911 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
912 responseNum, responseString,
913 responseNum, responseString, infoString);
916 fprintf(stderr, "headers: '%s'\n", iobuf);
919 i++; /* write to fd #1 in inetd mode */
920 return full_write(i, iobuf, len);
924 * Read from the socket until '\n' or EOF. '\r' chars are removed.
925 * '\n' is replaced with NUL.
926 * Return number of characters read or 0 if nothing is read
927 * ('\r' and '\n' are not counted).
928 * Data is returned in iobuf.
930 static int get_line(void)
934 /* We must not read extra chars. Reading byte-by-byte... */
935 while (read(accepted_socket, iobuf + count, 1) == 1) {
936 if (iobuf[count] == '\r')
938 if (iobuf[count] == '\n') {
942 if (count < (MAX_MEMORY_BUF - 1)) /* check overflow */
948 #if ENABLE_FEATURE_HTTPD_CGI
949 /****************************************************************************
951 > $Function: sendCgi()
953 * $Description: Execute a CGI script and send it's stdout back
955 * Environment variables are set up and the script is invoked with pipes
956 * for stdin/stdout. If a post is being done the script is fed the POST
957 * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
960 * (const char *) url . . . . . . The requested URL (with leading /).
961 * (int bodyLen) . . . . . . . . Length of the post body.
962 * (const char *cookie) . . . . . For set HTTP_COOKIE.
963 * (const char *content_type) . . For set CONTENT_TYPE.
965 * $Return: (char *) . . . . A pointer to the decoded string (same as input).
969 ****************************************************************************/
970 static int sendCgi(const char *url,
971 const char *request, int bodyLen, const char *cookie,
972 const char *content_type)
974 struct { int rd; int wr; } fromCgi; /* CGI -> httpd pipe */
975 struct { int rd; int wr; } toCgi; /* httpd -> CGI pipe */
977 char *argp[] = { NULL, NULL };
983 size_t post_read_size, post_read_idx;
985 if (pipe(&fromCgi.rd) != 0)
987 if (pipe(&toCgi.rd) != 0)
991 * Note: We can use vfork() here in the no-mmu case, although
992 * the child modifies the parent's variables, due to:
993 * 1) The parent does not use the child-modified variables.
994 * 2) The allocated memory (in the child) is freed when the process
995 * exits. This happens instantly after the child finishes,
996 * since httpd is run from inetd (and it can't run standalone
1000 // FIXME: setenv leaks memory! (old values of env vars are leaked)
1001 // Thus we have a bug on NOMMU.
1002 // Need to use this instead:
1003 // [malloc +] putenv + (in child: exec) + (in parent: unsetenv [+ free])
1019 if (accepted_socket > 1)
1020 close(accepted_socket);
1021 if (server_socket > 1)
1022 close(server_socket);
1024 xmove_fd(toCgi.rd, 0); /* replace stdin with the pipe */
1025 xmove_fd(fromCgi.wr, 1); /* replace stdout with the pipe */
1028 /* Huh? User seeing stderr can be a security problem.
1029 * If CGI really wants that, it can always dup2(1,2). */
1035 xfunc_error_retval = 242;
1036 purl = xstrdup(url);
1038 while ((script = strchr(script + 1, '/')) != NULL) {
1039 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1043 if (is_directory(purl + 1, 1, &sb) == 0) {
1044 /* not directory, found script.cgi/PATH_INFO */
1048 *script = '/'; /* is directory, find next '/' */
1050 setenv1("PATH_INFO", script); /* set /PATH_INFO or "" */
1051 setenv1("REQUEST_METHOD", request);
1053 char *uri = alloca(strlen(purl) + 2 + strlen(g_query));
1055 sprintf(uri, "%s?%s", purl, g_query);
1056 setenv1("REQUEST_URI", uri);
1058 setenv1("REQUEST_URI", purl);
1061 *script = '\0'; /* cut off /PATH_INFO */
1063 /* SCRIPT_FILENAME required by PHP in CGI mode */
1064 fullpath = concat_path_file(home_httpd, purl);
1065 setenv1("SCRIPT_FILENAME", fullpath);
1066 /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1067 setenv1("SCRIPT_NAME", purl);
1068 /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1069 * QUERY_STRING: The information which follows the ? in the URL
1070 * which referenced this script. This is the query information.
1071 * It should not be decoded in any fashion. This variable
1072 * should always be set when there is query information,
1073 * regardless of command line decoding. */
1074 /* (Older versions of bbox seem to do some decoding) */
1075 setenv1("QUERY_STRING", g_query);
1076 putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1077 putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1078 putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1079 /* Having _separate_ variables for IP and port defeats
1080 * the purpose of having socket abstraction. Which "port"
1081 * are you using on Unix domain socket?
1082 * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1085 char *p = rmt_ip_str ? : (char*)"";
1086 char *cp = strrchr(p, ':');
1087 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1089 if (cp) *cp = '\0'; /* delete :PORT */
1090 setenv1("REMOTE_ADDR", p);
1093 setenv1("HTTP_USER_AGENT", user_agent);
1094 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1095 setenv_long("REMOTE_PORT", tcp_port);
1098 setenv_long("CONTENT_LENGTH", bodyLen);
1100 setenv1("HTTP_COOKIE", cookie);
1102 setenv1("CONTENT_TYPE", content_type);
1103 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1105 setenv1("REMOTE_USER", remoteuser);
1106 putenv((char*)"AUTH_TYPE=Basic");
1110 setenv1("HTTP_REFERER", referer);
1112 /* set execve argp[0] without path */
1113 argp[0] = (char*)bb_basename(purl);
1114 /* but script argp[0] must have absolute path and chdiring to this */
1115 script = strrchr(fullpath, '/');
1117 goto error_execing_cgi;
1119 if (chdir(fullpath) == 0) {
1120 // Now run the program. If it fails,
1121 // use _exit() so no destructors
1122 // get called and make a mess.
1123 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1124 char *interpr = NULL;
1125 char *suffix = strrchr(purl, '.');
1129 for (cur = script_i; cur; cur = cur->next) {
1130 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1131 interpr = cur->after_colon;
1138 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1140 execv(interpr, argp);
1143 execv(fullpath, argp);
1146 /* send to stdout (even if we are not from inetd) */
1147 accepted_socket = 1;
1148 sendHeaders(HTTP_NOT_FOUND);
1152 /* parent process */
1159 post_read_idx = 0; /* for gcc */
1164 signal(SIGPIPE, SIG_IGN);
1175 FD_SET(inFd, &readSet);
1176 if (bodyLen > 0 || post_read_size > 0) {
1177 FD_SET(outFd, &writeSet);
1178 nfound = outFd > inFd ? outFd : inFd;
1179 if (post_read_size == 0) {
1180 FD_SET(accepted_socket, &readSet);
1181 if (nfound < accepted_socket)
1182 nfound = accepted_socket;
1184 /* Now wait on the set of sockets! */
1185 nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1188 close(outFd); /* no more POST data to CGI */
1191 nfound = select(inFd + 1, &readSet, NULL, NULL, NULL);
1195 if (waitpid(pid, &status, WNOHANG) <= 0) {
1196 /* Weird. CGI didn't exit and no fd's
1197 * are ready, yet select returned?! */
1201 if (DEBUG && WIFEXITED(status))
1202 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1203 if (DEBUG && WIFSIGNALED(status))
1204 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1208 if (post_read_size > 0 && FD_ISSET(outFd, &writeSet)) {
1209 /* Have data from peer and can write to CGI */
1210 // huh? why full_write? what if we will block?
1211 // (imagine that CGI does not read its stdin...)
1212 count = full_write(outFd, wbuf + post_read_idx, post_read_size);
1214 post_read_idx += count;
1215 post_read_size -= count;
1217 post_read_size = bodyLen = 0; /* broken pipe to CGI */
1219 } else if (bodyLen > 0 && post_read_size == 0
1220 && FD_ISSET(accepted_socket, &readSet)
1222 /* We expect data, prev data portion is eaten by CGI
1223 * and there *is* data to read from the peer
1225 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1226 count = safe_read(accepted_socket, wbuf, count);
1228 post_read_size = count;
1232 bodyLen = 0; /* closed */
1236 #define PIPESIZE PIPE_BUF
1237 #if PIPESIZE >= MAX_MEMORY_BUF
1238 # error "PIPESIZE >= MAX_MEMORY_BUF"
1240 if (FD_ISSET(inFd, &readSet)) {
1241 /* There is something to read from CGI */
1242 int s = accepted_socket;
1245 /* Are we still buffering CGI output? */
1246 if (buf_count >= 0) {
1247 /* According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1248 * CGI scripts MUST send their own header terminated by
1249 * empty line, then data. That's why we have only one
1250 * <cr><lf> pair here. We will output "200 OK" line
1251 * if needed, but CGI still has to provide blank line
1252 * between header and body */
1253 static const char HTTP_200[] ALIGN1 = "HTTP/1.0 200 OK\r\n";
1255 /* Must use safe_read, not full_read, because
1256 * CGI may output a few first bytes and then wait
1257 * for POSTDATA without closing stdout.
1258 * With full_read we may wait here forever. */
1259 count = safe_read(inFd, rbuf + buf_count, PIPESIZE - 8);
1261 /* eof (or error) and there was no "HTTP",
1262 * so write it, then write received data */
1264 full_write(s, HTTP_200, sizeof(HTTP_200)-1);
1265 full_write(s, rbuf, buf_count);
1271 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1272 if (buf_count >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1273 /* send "HTTP/1.0 " */
1274 if (full_write(s, HTTP_200, 9) != 9)
1276 rbuf += 8; /* skip "Status: " */
1277 count = buf_count - 8;
1278 buf_count = -1; /* buffering off */
1279 } else if (buf_count >= 4) {
1280 /* Did CGI add "HTTP"? */
1281 if (memcmp(rbuf, HTTP_200, 4) != 0) {
1282 /* there is no "HTTP", do it ourself */
1283 if (full_write(s, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1287 if (!strstr(rbuf, "ontent-")) {
1288 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1290 * Counter-example of valid CGI without Content-type:
1291 * echo -en "HTTP/1.0 302 Found\r\n"
1292 * echo -en "Location: http://www.busybox.net\r\n"
1296 buf_count = -1; /* buffering off */
1299 count = safe_read(inFd, rbuf, PIPESIZE);
1301 break; /* eof (or error) */
1303 if (full_write(s, rbuf, count) != count)
1306 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1307 } /* if (FD_ISSET(inFd)) */
1311 #endif /* FEATURE_HTTPD_CGI */
1313 /****************************************************************************
1315 > $Function: sendFile()
1317 * $Description: Send a file response to a HTTP request
1320 * (const char *) url . . The URL requested.
1322 * $Return: (int) . . . . . . Always 0.
1324 ****************************************************************************/
1325 static int sendFile(const char *url)
1330 const char *const *table;
1331 const char *try_suffix;
1333 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1337 suffix = strrchr(url, '.');
1339 for (table = suffixTable; *table; table += 2)
1340 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1341 try_suffix += strlen(suffix);
1342 if (*try_suffix == 0 || *try_suffix == '.')
1345 /* also, if not found, set default as "application/octet-stream"; */
1346 found_mime_type = table[1];
1347 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1350 for (cur = mime_a; cur; cur = cur->next) {
1351 if (strcmp(cur->before_colon, suffix) == 0) {
1352 found_mime_type = cur->after_colon;
1357 #endif /* FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1360 fprintf(stderr, "sending file '%s' content-type: %s\n",
1361 url, found_mime_type);
1363 f = open(url, O_RDONLY);
1366 bb_perror_msg("cannot open '%s'", url);
1367 sendHeaders(HTTP_NOT_FOUND);
1371 sendHeaders(HTTP_OK);
1372 fd = accepted_socket;
1374 fd++; /* write to fd #1 in inetd mode */
1375 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1377 /* byte count is rounded down to 64k */
1378 count = sendfile(fd, f, &offset, MAXINT(ssize_t) - 0xffff);
1382 bb_perror_msg("sendfile '%s'", url);
1384 } while (count > 0);
1390 while ((count = full_read(f, iobuf, MAX_MEMORY_BUF)) > 0) {
1391 if (full_write(fd, iobuf, count) != count)
1398 static int checkPermIP(void)
1402 /* This could stand some work */
1403 for (cur = ip_a_d; cur; cur = cur->next) {
1406 "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1408 (unsigned char)(cur->ip >> 24),
1409 (unsigned char)(cur->ip >> 16),
1410 (unsigned char)(cur->ip >> 8),
1411 (unsigned char)(cur->ip),
1412 (unsigned char)(cur->mask >> 24),
1413 (unsigned char)(cur->mask >> 16),
1414 (unsigned char)(cur->mask >> 8),
1415 (unsigned char)(cur->mask)
1418 if ((rmt_ip & cur->mask) == cur->ip)
1419 return cur->allow_deny == 'A'; /* Allow/Deny */
1422 /* if unconfigured, return 1 - access from all */
1423 return !flg_deny_all;
1426 /****************************************************************************
1428 > $Function: checkPerm()
1430 * $Description: Check the permission file for access password protected.
1432 * If config file isn't present, everything is allowed.
1433 * Entries are of the form you can see example from header source
1436 * (const char *) path . . . . The file path.
1437 * (const char *) request . . . User information to validate.
1439 * $Return: (int) . . . . . . . . . 1 if request OK, 0 otherwise.
1441 ****************************************************************************/
1443 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1444 static int checkPerm(const char *path, const char *request)
1450 const char *prev = NULL;
1452 /* This could stand some work */
1453 for (cur = g_auth; cur; cur = cur->next) {
1456 p0 = cur->before_colon;
1457 if (prev != NULL && strcmp(prev, p0) != 0)
1458 continue; /* find next identical */
1459 p = cur->after_colon;
1461 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1464 if (strncmp(p0, path, l) == 0
1465 && (l == 1 || path[l] == '/' || path[l] == '\0')
1468 /* path match found. Check request */
1469 /* for check next /path:user:password */
1471 u = strchr(request, ':');
1473 /* bad request, ':' required */
1477 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1481 if (strncmp(p, request, u-request) != 0) {
1482 /* user uncompared */
1485 pp = strchr(p, ':');
1486 if (pp && pp[1] == '$' && pp[2] == '1' &&
1487 pp[3] == '$' && pp[4]) {
1489 cipher = pw_encrypt(u+1, pp);
1490 if (strcmp(cipher, pp) == 0)
1491 goto set_remoteuser_var; /* Ok */
1497 if (strcmp(p, request) == 0) {
1499 remoteuser = strdup(request);
1501 remoteuser[(u - request)] = 0;
1508 return prev == NULL;
1511 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1516 static void handle_sigalrm(int sig)
1518 sendHeaders(HTTP_REQUEST_TIMEOUT);
1523 * Handle an incoming http request and exit.
1525 static void handle_incoming_and_exit(void) ATTRIBUTE_NORETURN;
1526 static void handle_incoming_and_exit(void)
1534 #if ENABLE_FEATURE_HTTPD_CGI
1535 const char *prequest = request_GET;
1536 unsigned long length = 0;
1538 char *content_type = 0;
1540 struct sigaction sa;
1542 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1543 int credentials = -1; /* if not required this is Ok */
1546 sa.sa_handler = handle_sigalrm;
1547 sigemptyset(&sa.sa_mask);
1548 sa.sa_flags = 0; /* no SA_RESTART */
1549 sigaction(SIGALRM, &sa, NULL);
1551 /* It's not a real loop (it ends with while(0)).
1552 * Break from this "loop" jumps to exit(0) */
1558 break; /* EOF or error or empty line */
1560 purl = strpbrk(iobuf, " \t");
1563 sendHeaders(HTTP_BAD_REQUEST);
1567 #if ENABLE_FEATURE_HTTPD_CGI
1568 if (strcasecmp(iobuf, prequest) != 0) {
1570 if (strcasecmp(iobuf, prequest) != 0) {
1571 sendHeaders(HTTP_NOT_IMPLEMENTED);
1576 if (strcasecmp(iobuf, request_GET) != 0) {
1577 sendHeaders(HTTP_NOT_IMPLEMENTED);
1582 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", iobuf, &blank);
1584 if (count < 1 || iobuf[0] != '/') {
1585 /* Garbled request/URL */
1588 url = alloca(strlen(iobuf) + sizeof("/index.html"));
1590 sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1594 /* extract url args if present */
1595 test = strchr(url, '?');
1602 test = decodeString(url, 0);
1605 if (test == url+1) {
1606 /* '/' or NUL is encoded */
1607 sendHeaders(HTTP_NOT_FOUND);
1611 /* algorithm stolen from libbb bb_simplify_path(),
1612 * but don't strdup and reducing trailing slash and protect out root */
1616 /* skip duplicate (or initial) slash */
1621 /* skip extra '.' */
1622 if (test[1] == '/' || !test[1]) {
1625 /* '..': be careful */
1626 if (test[1] == '.' && (test[2] == '/' || !test[2])) {
1632 while (*--purl != '/') /* omit previous dir */;
1639 *++purl = '\0'; /* so keep last character */
1640 test = purl; /* end ptr */
1642 /* If URL is directory, adding '/' */
1643 if (test[-1] != '/') {
1644 if (is_directory(url + 1, 1, &sb)) {
1645 found_moved_temporarily = url;
1649 /* Hopefully does it with single write[v] */
1650 /* (uclibc does, glibc: ?) */
1651 fdprintf(2, "%s url:%s\n", rmt_ip_str, url);
1655 ip_allowed = checkPermIP();
1656 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1657 /* have path1/path2 */
1659 if (is_directory(url + 1, 1, &sb)) {
1660 /* may be having subdir config */
1661 parse_conf(url + 1, SUBDIR_PARSE);
1662 ip_allowed = checkPermIP();
1667 /* read until blank line for HTTP version specified, else parse immediate */
1671 break; /* EOF or error or empty line */
1674 fprintf(stderr, "header: '%s'\n", iobuf);
1676 #if ENABLE_FEATURE_HTTPD_CGI
1677 /* try and do our best to parse more lines */
1678 if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
1679 /* extra read only for POST */
1680 if (prequest != request_GET) {
1681 test = iobuf + sizeof("Content-length:") - 1;
1685 /* not using strtoul: it ignores leading minus! */
1686 length = strtol(test, &test, 10);
1687 /* length is "ulong", but we need to pass it to int later */
1688 /* so we check for negative or too large values in one go: */
1689 /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1690 if (test[0] || errno || length > INT_MAX)
1693 } else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
1694 cookie = strdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
1695 } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
1696 content_type = strdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
1697 } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
1698 referer = strdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
1699 } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
1700 user_agent = strdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
1704 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1705 if (STRNCASECMP(iobuf, "Authorization:") == 0) {
1706 /* We only allow Basic credentials.
1707 * It shows up as "Authorization: Basic <userid:password>" where
1708 * the userid:password is base64 encoded.
1710 test = skip_whitespace(iobuf + sizeof("Authorization:")-1);
1711 if (STRNCASECMP(test, "Basic") != 0)
1713 test += sizeof("Basic")-1;
1714 /* decodeBase64() skips whitespace itself */
1716 credentials = checkPerm(url, test);
1718 #endif /* FEATURE_HTTPD_BASIC_AUTH */
1720 } /* while extra header reading */
1726 if (strcmp(bb_basename(url), httpd_conf) == 0 || ip_allowed == 0) {
1727 /* protect listing [/path]/httpd_conf or IP deny */
1728 #if ENABLE_FEATURE_HTTPD_CGI
1729 FORBIDDEN: /* protect listing /cgi-bin */
1731 sendHeaders(HTTP_FORBIDDEN);
1735 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1736 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1737 sendHeaders(HTTP_UNAUTHORIZED);
1742 if (found_moved_temporarily) {
1743 sendHeaders(HTTP_MOVED_TEMPORARILY);
1744 /* clear unforked memory flag */
1745 found_moved_temporarily = NULL;
1749 test = url + 1; /* skip first '/' */
1751 #if ENABLE_FEATURE_HTTPD_CGI
1752 if (strncmp(test, "cgi-bin", 7) == 0) {
1753 if (test[7] == '/' && test[8] == '\0')
1754 goto FORBIDDEN; /* protect listing cgi-bin/ */
1755 sendCgi(url, prequest, length, cookie, content_type);
1758 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1760 char *suffix = strrchr(test, '.');
1763 for (cur = script_i; cur; cur = cur->next) {
1764 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1765 sendCgi(url, prequest, length, cookie, content_type);
1772 if (prequest != request_GET) {
1773 sendHeaders(HTTP_NOT_IMPLEMENTED);
1776 #endif /* FEATURE_HTTPD_CGI */
1777 if (purl[-1] == '/')
1778 strcpy(purl, "index.html");
1779 if (stat(test, &sb) == 0) {
1780 /* It's a dir URL and there is index.html */
1781 ContentLength = sb.st_size;
1782 last_mod = sb.st_mtime;
1784 #if ENABLE_FEATURE_HTTPD_CGI
1785 else if (purl[-1] == '/') {
1786 /* It's a dir URL and there is no index.html
1787 * Try cgi-bin/index.cgi */
1788 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1791 sendCgi("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1795 #endif /* FEATURE_HTTPD_CGI */
1800 #if ENABLE_FEATURE_HTTPD_CGI
1806 #if 0 /* Is this needed? Why? */
1808 fprintf(stderr, "closing socket\n");
1809 #if ENABLE_FEATURE_HTTPD_CGI
1814 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1819 /* Properly wait for remote to closed */
1821 shutdown(accepted_socket, SHUT_WR);
1826 FD_SET(accepted_socket, &s_fd);
1829 retval = select(accepted_socket + 1, &s_fd, NULL, NULL, &tv);
1830 } while (retval > 0 && read(accepted_socket, iobuf, sizeof(iobuf) > 0));
1831 shutdown(accepted_socket, SHUT_RD);
1832 close(accepted_socket);
1839 * The main http server function.
1840 * Given an open socket, listen for new connections and farm out
1841 * the processing as a forked process.
1844 static void mini_httpd(int server) ATTRIBUTE_NORETURN;
1845 static void mini_httpd(int server)
1847 fd_set readfd, portfd;
1850 FD_SET(server, &portfd);
1852 /* copy the ports we are watching to the readfd set */
1857 struct sockaddr_in sin;
1858 USE_FEATURE_IPV6(struct sockaddr_in6 sin6;)
1860 socklen_t fromAddrLen = sizeof(fromAddr);
1862 /* Now wait INDEFINITELY on the set of sockets! */
1864 if (select(server + 1, &readfd, 0, 0, 0) <= 0)
1866 if (!FD_ISSET(server, &readfd))
1868 s = accept(server, &fromAddr.sa, &fromAddrLen);
1871 accepted_socket = s;
1874 if (verbose || ENABLE_FEATURE_HTTPD_CGI || DEBUG) {
1876 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddrLen);
1878 bb_error_msg("connection from '%s'", rmt_ip_str);
1880 if (fromAddr.sa.sa_family == AF_INET) {
1881 rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1882 tcp_port = ntohs(fromAddr.sin.sin_port);
1884 #if ENABLE_FEATURE_IPV6
1885 if (fromAddr.sa.sa_family == AF_INET6) {
1886 //rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1887 tcp_port = ntohs(fromAddr.sin6.sin6_port);
1891 /* set the KEEPALIVE option to cull dead connections */
1892 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1896 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1897 /* Do not reload config on HUP */
1898 signal(SIGHUP, SIG_IGN);
1900 handle_incoming_and_exit();
1904 /* return 0; - never reached */
1909 static void mini_httpd_inetd(void) ATTRIBUTE_NORETURN;
1910 static void mini_httpd_inetd(void)
1914 struct sockaddr_in sin;
1915 USE_FEATURE_IPV6(struct sockaddr_in6 sin6;)
1917 socklen_t fromAddrLen = sizeof(fromAddr);
1919 getpeername(0, &fromAddr.sa, &fromAddrLen);
1922 if (verbose || ENABLE_FEATURE_HTTPD_CGI || DEBUG) {
1924 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr.sa, fromAddrLen);
1926 if (fromAddr.sa.sa_family == AF_INET) {
1927 rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1928 tcp_port = ntohs(fromAddr.sin.sin_port);
1930 #if ENABLE_FEATURE_IPV6
1931 if (fromAddr.sa.sa_family == AF_INET6) {
1932 //rmt_ip = ntohl(fromAddr.sin.sin_addr.s_addr);
1933 tcp_port = ntohs(fromAddr.sin6.sin6_port);
1936 handle_incoming_and_exit();
1939 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1940 static void sighup_handler(int sig)
1943 struct sigaction sa;
1945 parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1946 sa.sa_handler = sighup_handler;
1947 sigemptyset(&sa.sa_mask);
1948 sa.sa_flags = SA_RESTART;
1949 sigaction(SIGHUP, &sa, NULL);
1954 c_opt_config_file = 0,
1957 USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1958 USE_FEATURE_HTTPD_BASIC_AUTH( r_opt_realm ,)
1959 USE_FEATURE_HTTPD_AUTH_MD5( m_opt_md5 ,)
1960 USE_FEATURE_HTTPD_SETUID( u_opt_setuid ,)
1965 OPT_CONFIG_FILE = 1 << c_opt_config_file,
1966 OPT_DECODE_URL = 1 << d_opt_decode_url,
1967 OPT_HOME_HTTPD = 1 << h_opt_home_httpd,
1968 OPT_ENCODE_URL = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1969 OPT_REALM = USE_FEATURE_HTTPD_BASIC_AUTH( (1 << r_opt_realm )) + 0,
1970 OPT_MD5 = USE_FEATURE_HTTPD_AUTH_MD5( (1 << m_opt_md5 )) + 0,
1971 OPT_SETUID = USE_FEATURE_HTTPD_SETUID( (1 << u_opt_setuid )) + 0,
1972 OPT_PORT = 1 << p_opt_port,
1973 OPT_INETD = 1 << p_opt_inetd,
1974 OPT_FOREGROUND = 1 << p_opt_foreground,
1975 OPT_VERBOSE = 1 << p_opt_verbose,
1979 int httpd_main(int argc, char **argv);
1980 int httpd_main(int argc, char **argv)
1983 char *url_for_decode;
1984 USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1985 USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1986 USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1987 USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1989 #if ENABLE_LOCALE_SUPPORT
1990 /* Undo busybox.c: we want to speak English in http (dates etc) */
1991 setlocale(LC_TIME, "C");
1995 home_httpd = xrealloc_getcwd_or_warn(NULL);
1996 opt_complementary = "vv"; /* counter */
1997 /* We do not "absolutize" path given by -h (home) opt.
1998 * If user gives relative path in -h, $SCRIPT_FILENAME can end up
2000 opt = getopt32(argc, argv, "c:d:h:"
2001 USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
2002 USE_FEATURE_HTTPD_BASIC_AUTH("r:")
2003 USE_FEATURE_HTTPD_AUTH_MD5("m:")
2004 USE_FEATURE_HTTPD_SETUID("u:")
2006 &configFile, &url_for_decode, &home_httpd
2007 USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
2008 USE_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
2009 USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
2010 USE_FEATURE_HTTPD_SETUID(, &s_ugid)
2011 , &bind_addr_or_port
2014 if (opt & OPT_DECODE_URL) {
2015 printf("%s", decodeString(url_for_decode, 1));
2018 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
2019 if (opt & OPT_ENCODE_URL) {
2020 printf("%s", encodeString(url_for_encode));
2024 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
2025 if (opt & OPT_MD5) {
2026 puts(pw_encrypt(pass, "$1$"));
2030 #if ENABLE_FEATURE_HTTPD_SETUID
2031 if (opt & OPT_SETUID) {
2032 if (!get_uidgid(&ugid, s_ugid, 1))
2033 bb_error_msg_and_die("unrecognized user[:group] "
2034 "name '%s'", s_ugid);
2039 if (!(opt & OPT_INETD)) {
2041 signal(SIGCHLD, SIG_IGN);
2042 server_socket = openServer();
2043 #if ENABLE_FEATURE_HTTPD_SETUID
2044 /* drop privileges */
2045 if (opt & OPT_SETUID) {
2046 if (ugid.gid != (gid_t)-1) {
2047 if (setgroups(1, &ugid.gid) == -1)
2048 bb_perror_msg_and_die("setgroups");
2055 bb_error_msg_and_die("-i is required");
2059 #if ENABLE_FEATURE_HTTPD_CGI
2061 char *p = getenv("PATH");
2062 /* env strings themself are not freed, no need to strdup(p): */
2066 if (!(opt & OPT_INETD))
2067 setenv_long("SERVER_PORT", tcp_port);
2071 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2074 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2078 if (opt & OPT_INETD)
2080 if (!(opt & OPT_FOREGROUND))
2081 bb_daemonize(0); /* don't change current directory */
2082 mini_httpd(server_socket); /* never returns */
2084 mini_httpd_inetd(); /* never returns */