http: document index.cgi usage. no code changes
[oweals/busybox.git] / networking / httpd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * httpd implementation for busybox
4  *
5  * Copyright (C) 2002,2003 Glenn Engel <glenne@engel.org>
6  * Copyright (C) 2003-2006 Vladimir Oleynik <dzo@simtreas.ru>
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9  *
10  *****************************************************************************
11  *
12  * Typical usage:
13  * For non root user:
14  *      httpd -p 8080 -h $HOME/public_html
15  * For daemon start from rc script with uid=0:
16  *      httpd -u www
17  * which is equivalent to (assuming user www has uid 80):
18  *      httpd -p 80 -u 80 -h $PWD -c /etc/httpd.conf -r "Web Server Authentication"
19  *
20  * When an url starts with "/cgi-bin/" it is assumed to be a cgi script.
21  * The server changes directory to the location of the script and executes it
22  * after setting QUERY_STRING and other environment variables.
23  *
24  * If directory URL is given, no index.html is found and CGI support is enabled,
25  * cgi-bin/index.cgi will be run. Directory to list is ../$QUERY_STRING.
26  * See httpd_indexcgi.c for an example GCI code.
27  *
28  * Doc:
29  * "CGI Environment Variables": http://hoohoo.ncsa.uiuc.edu/cgi/env.html
30  *
31  * The applet can also be invoked as an url arg decoder and html text encoder
32  * as follows:
33  *      foo=`httpd -d $foo`             # decode "Hello%20World" as "Hello World"
34  *      bar=`httpd -e "<Hello World>"`  # encode as "&#60Hello&#32World&#62"
35  * Note that url encoding for arguments is not the same as html encoding for
36  * presentation.  -d decodes an url-encoded argument while -e encodes in html
37  * for page display.
38  *
39  * httpd.conf has the following format:
40  *
41  * H:/serverroot     # define the server root. It will override -h
42  * A:172.20.         # Allow address from 172.20.0.0/16
43  * A:10.0.0.0/25     # Allow any address from 10.0.0.0-10.0.0.127
44  * A:10.0.0.0/255.255.255.128  # Allow any address that previous set
45  * A:127.0.0.1       # Allow local loopback connections
46  * D:*               # Deny from other IP connections
47  * E404:/path/e404.html # /path/e404.html is the 404 (not found) error page
48  * I:index.html      # Show index.html when a directory is requested
49  *
50  * P:/url:[http://]hostname[:port]/new/path
51  *                   # When /urlXXXXXX is requested, reverse proxy
52  *                   # it to http://hostname[:port]/new/pathXXXXXX
53  *
54  * /cgi-bin:foo:bar  # Require user foo, pwd bar on urls starting with /cgi-bin/
55  * /adm:admin:setup  # Require user admin, pwd setup on urls starting with /adm/
56  * /adm:toor:PaSsWd  # or user toor, pwd PaSsWd on urls starting with /adm/
57  * .au:audio/basic   # additional mime type for audio.au files
58  * *.php:/path/php   # run xxx.php through an interpreter
59  *
60  * A/D may be as a/d or allow/deny - only first char matters.
61  * Deny/Allow IP logic:
62  *  - Default is to allow all (Allow all (A:*) is a no-op).
63  *  - Deny rules take precedence over allow rules.
64  *  - "Deny all" rule (D:*) is applied last.
65  *
66  * Example:
67  *   1. Allow only specified addresses
68  *     A:172.20          # Allow any address that begins with 172.20.
69  *     A:10.10.          # Allow any address that begins with 10.10.
70  *     A:127.0.0.1       # Allow local loopback connections
71  *     D:*               # Deny from other IP connections
72  *
73  *   2. Only deny specified addresses
74  *     D:1.2.3.        # deny from 1.2.3.0 - 1.2.3.255
75  *     D:2.3.4.        # deny from 2.3.4.0 - 2.3.4.255
76  *     A:*             # (optional line added for clarity)
77  *
78  * If a sub directory contains config file, it is parsed and merged with
79  * any existing settings as if it was appended to the original configuration.
80  *
81  * subdir paths are relative to the containing subdir and thus cannot
82  * affect the parent rules.
83  *
84  * Note that since the sub dir is parsed in the forked thread servicing the
85  * subdir http request, any merge is discarded when the process exits.  As a
86  * result, the subdir settings only have a lifetime of a single request.
87  *
88  * Custom error pages can contain an absolute path or be relative to
89  * 'home_httpd'. Error pages are to be static files (no CGI or script). Error
90  * page can only be defined in the root configuration file and are not taken
91  * into account in local (directories) config files.
92  *
93  * If -c is not set, an attempt will be made to open the default
94  * root configuration file.  If -c is set and the file is not found, the
95  * server exits with an error.
96  *
97  */
98  /* TODO: use TCP_CORK, parse_config() */
99
100 #include "libbb.h"
101 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
102 # include <sys/sendfile.h>
103 #endif
104 /* amount of buffering in a pipe */
105 #ifndef PIPE_BUF
106 # define PIPE_BUF 4096
107 #endif
108
109 #define DEBUG 0
110
111 #define IOBUF_SIZE 8192
112 #if PIPE_BUF >= IOBUF_SIZE
113 # error "PIPE_BUF >= IOBUF_SIZE"
114 #endif
115
116 #define HEADER_READ_TIMEOUT 60
117
118 static const char DEFAULT_PATH_HTTPD_CONF[] ALIGN1 = "/etc";
119 static const char HTTPD_CONF[] ALIGN1 = "httpd.conf";
120 static const char HTTP_200[] ALIGN1 = "HTTP/1.0 200 OK\r\n";
121 static const char index_html[] ALIGN1 = "index.html";
122
123 typedef struct has_next_ptr {
124         struct has_next_ptr *next;
125 } has_next_ptr;
126
127 /* Must have "next" as a first member */
128 typedef struct Htaccess {
129         struct Htaccess *next;
130         char *after_colon;
131         char before_colon[1];  /* really bigger, must be last */
132 } Htaccess;
133
134 /* Must have "next" as a first member */
135 typedef struct Htaccess_IP {
136         struct Htaccess_IP *next;
137         unsigned ip;
138         unsigned mask;
139         int allow_deny;
140 } Htaccess_IP;
141
142 /* Must have "next" as a first member */
143 typedef struct Htaccess_Proxy {
144         struct Htaccess_Proxy *next;
145         char *url_from;
146         char *host_port;
147         char *url_to;
148 } Htaccess_Proxy;
149
150 enum {
151         HTTP_OK = 200,
152         HTTP_PARTIAL_CONTENT = 206,
153         HTTP_MOVED_TEMPORARILY = 302,
154         HTTP_BAD_REQUEST = 400,       /* malformed syntax */
155         HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
156         HTTP_NOT_FOUND = 404,
157         HTTP_FORBIDDEN = 403,
158         HTTP_REQUEST_TIMEOUT = 408,
159         HTTP_NOT_IMPLEMENTED = 501,   /* used for unrecognized requests */
160         HTTP_INTERNAL_SERVER_ERROR = 500,
161         HTTP_CONTINUE = 100,
162 #if 0   /* future use */
163         HTTP_SWITCHING_PROTOCOLS = 101,
164         HTTP_CREATED = 201,
165         HTTP_ACCEPTED = 202,
166         HTTP_NON_AUTHORITATIVE_INFO = 203,
167         HTTP_NO_CONTENT = 204,
168         HTTP_MULTIPLE_CHOICES = 300,
169         HTTP_MOVED_PERMANENTLY = 301,
170         HTTP_NOT_MODIFIED = 304,
171         HTTP_PAYMENT_REQUIRED = 402,
172         HTTP_BAD_GATEWAY = 502,
173         HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
174 #endif
175 };
176
177 static const uint16_t http_response_type[] ALIGN2 = {
178         HTTP_OK,
179 #if ENABLE_FEATURE_HTTPD_RANGES
180         HTTP_PARTIAL_CONTENT,
181 #endif
182         HTTP_MOVED_TEMPORARILY,
183         HTTP_REQUEST_TIMEOUT,
184         HTTP_NOT_IMPLEMENTED,
185 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
186         HTTP_UNAUTHORIZED,
187 #endif
188         HTTP_NOT_FOUND,
189         HTTP_BAD_REQUEST,
190         HTTP_FORBIDDEN,
191         HTTP_INTERNAL_SERVER_ERROR,
192 #if 0   /* not implemented */
193         HTTP_CREATED,
194         HTTP_ACCEPTED,
195         HTTP_NO_CONTENT,
196         HTTP_MULTIPLE_CHOICES,
197         HTTP_MOVED_PERMANENTLY,
198         HTTP_NOT_MODIFIED,
199         HTTP_BAD_GATEWAY,
200         HTTP_SERVICE_UNAVAILABLE,
201 #endif
202 };
203
204 static const struct {
205         const char *name;
206         const char *info;
207 } http_response[ARRAY_SIZE(http_response_type)] = {
208         { "OK", NULL },
209 #if ENABLE_FEATURE_HTTPD_RANGES
210         { "Partial Content", NULL },
211 #endif
212         { "Found", NULL },
213         { "Request Timeout", "No request appeared within 60 seconds" },
214         { "Not Implemented", "The requested method is not recognized" },
215 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
216         { "Unauthorized", "" },
217 #endif
218         { "Not Found", "The requested URL was not found" },
219         { "Bad Request", "Unsupported method" },
220         { "Forbidden", ""  },
221         { "Internal Server Error", "Internal Server Error" },
222 #if 0   /* not implemented */
223         { "Created" },
224         { "Accepted" },
225         { "No Content" },
226         { "Multiple Choices" },
227         { "Moved Permanently" },
228         { "Not Modified" },
229         { "Bad Gateway", "" },
230         { "Service Unavailable", "" },
231 #endif
232 };
233
234 struct globals {
235         int verbose;            /* must be int (used by getopt32) */
236         smallint flg_deny_all;
237
238         unsigned rmt_ip;        /* used for IP-based allow/deny rules */
239         time_t last_mod;
240         char *rmt_ip_str;       /* for $REMOTE_ADDR and $REMOTE_PORT */
241         const char *bind_addr_or_port;
242
243         const char *g_query;
244         const char *opt_c_configFile;
245         const char *home_httpd;
246         const char *index_page;
247
248         const char *found_mime_type;
249         const char *found_moved_temporarily;
250         Htaccess_IP *ip_a_d;    /* config allow/deny lines */
251
252         IF_FEATURE_HTTPD_BASIC_AUTH(const char *g_realm;)
253         IF_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
254         IF_FEATURE_HTTPD_CGI(char *referer;)
255         IF_FEATURE_HTTPD_CGI(char *user_agent;)
256         IF_FEATURE_HTTPD_CGI(char *host;)
257         IF_FEATURE_HTTPD_CGI(char *http_accept;)
258         IF_FEATURE_HTTPD_CGI(char *http_accept_language;)
259
260         off_t file_size;        /* -1 - unknown */
261 #if ENABLE_FEATURE_HTTPD_RANGES
262         off_t range_start;
263         off_t range_end;
264         off_t range_len;
265 #endif
266
267 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
268         Htaccess *g_auth;       /* config user:password lines */
269 #endif
270         Htaccess *mime_a;       /* config mime types */
271 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
272         Htaccess *script_i;     /* config script interpreters */
273 #endif
274         char *iobuf;            /* [IOBUF_SIZE] */
275 #define hdr_buf bb_common_bufsiz1
276         char *hdr_ptr;
277         int hdr_cnt;
278 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
279         const char *http_error_page[ARRAY_SIZE(http_response_type)];
280 #endif
281 #if ENABLE_FEATURE_HTTPD_PROXY
282         Htaccess_Proxy *proxy;
283 #endif
284 #if ENABLE_FEATURE_HTTPD_GZIP
285         /* client can handle gzip / we are going to send gzip */
286         smallint content_gzip;
287 #endif
288 };
289 #define G (*ptr_to_globals)
290 #define verbose           (G.verbose          )
291 #define flg_deny_all      (G.flg_deny_all     )
292 #define rmt_ip            (G.rmt_ip           )
293 #define bind_addr_or_port (G.bind_addr_or_port)
294 #define g_query           (G.g_query          )
295 #define opt_c_configFile  (G.opt_c_configFile )
296 #define home_httpd        (G.home_httpd       )
297 #define index_page        (G.index_page       )
298 #define found_mime_type   (G.found_mime_type  )
299 #define found_moved_temporarily (G.found_moved_temporarily)
300 #define last_mod          (G.last_mod         )
301 #define ip_a_d            (G.ip_a_d           )
302 #define g_realm           (G.g_realm          )
303 #define remoteuser        (G.remoteuser       )
304 #define referer           (G.referer          )
305 #define user_agent        (G.user_agent       )
306 #define host              (G.host             )
307 #define http_accept       (G.http_accept      )
308 #define http_accept_language (G.http_accept_language)
309 #define file_size         (G.file_size        )
310 #if ENABLE_FEATURE_HTTPD_RANGES
311 #define range_start       (G.range_start      )
312 #define range_end         (G.range_end        )
313 #define range_len         (G.range_len        )
314 #else
315 enum {
316         range_start = 0,
317         range_end = MAXINT(off_t) - 1,
318         range_len = MAXINT(off_t),
319 };
320 #endif
321 #define rmt_ip_str        (G.rmt_ip_str       )
322 #define g_auth            (G.g_auth           )
323 #define mime_a            (G.mime_a           )
324 #define script_i          (G.script_i         )
325 #define iobuf             (G.iobuf            )
326 #define hdr_ptr           (G.hdr_ptr          )
327 #define hdr_cnt           (G.hdr_cnt          )
328 #define http_error_page   (G.http_error_page  )
329 #define proxy             (G.proxy            )
330 #if ENABLE_FEATURE_HTTPD_GZIP
331 # define content_gzip     (G.content_gzip     )
332 #else
333 # define content_gzip     0
334 #endif
335 #define INIT_G() do { \
336         SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
337         IF_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
338         bind_addr_or_port = "80"; \
339         index_page = index_html; \
340         file_size = -1; \
341 } while (0)
342
343
344 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
345
346 /* Prototypes */
347 enum {
348         SEND_HEADERS     = (1 << 0),
349         SEND_BODY        = (1 << 1),
350         SEND_HEADERS_AND_BODY = SEND_HEADERS + SEND_BODY,
351 };
352 static void send_file_and_exit(const char *url, int what) NORETURN;
353
354 static void free_llist(has_next_ptr **pptr)
355 {
356         has_next_ptr *cur = *pptr;
357         while (cur) {
358                 has_next_ptr *t = cur;
359                 cur = cur->next;
360                 free(t);
361         }
362         *pptr = NULL;
363 }
364
365 static ALWAYS_INLINE void free_Htaccess_list(Htaccess **pptr)
366 {
367         free_llist((has_next_ptr**)pptr);
368 }
369
370 static ALWAYS_INLINE void free_Htaccess_IP_list(Htaccess_IP **pptr)
371 {
372         free_llist((has_next_ptr**)pptr);
373 }
374
375 /* Returns presumed mask width in bits or < 0 on error.
376  * Updates strp, stores IP at provided pointer */
377 static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
378 {
379         const char *p = *strp;
380         int auto_mask = 8;
381         unsigned ip = 0;
382         int j;
383
384         if (*p == '/')
385                 return -auto_mask;
386
387         for (j = 0; j < 4; j++) {
388                 unsigned octet;
389
390                 if ((*p < '0' || *p > '9') && *p != '/' && *p)
391                         return -auto_mask;
392                 octet = 0;
393                 while (*p >= '0' && *p <= '9') {
394                         octet *= 10;
395                         octet += *p - '0';
396                         if (octet > 255)
397                                 return -auto_mask;
398                         p++;
399                 }
400                 if (*p == '.')
401                         p++;
402                 if (*p != '/' && *p)
403                         auto_mask += 8;
404                 ip = (ip << 8) | octet;
405         }
406         if (*p) {
407                 if (*p != endc)
408                         return -auto_mask;
409                 p++;
410                 if (*p == '\0')
411                         return -auto_mask;
412         }
413         *ipp = ip;
414         *strp = p;
415         return auto_mask;
416 }
417
418 /* Returns 0 on success. Stores IP and mask at provided pointers */
419 static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
420 {
421         int i;
422         unsigned mask;
423         char *p;
424
425         i = scan_ip(&str, ipp, '/');
426         if (i < 0)
427                 return i;
428
429         if (*str) {
430                 /* there is /xxx after dotted-IP address */
431                 i = bb_strtou(str, &p, 10);
432                 if (*p == '.') {
433                         /* 'xxx' itself is dotted-IP mask, parse it */
434                         /* (return 0 (success) only if it has N.N.N.N form) */
435                         return scan_ip(&str, maskp, '\0') - 32;
436                 }
437                 if (*p)
438                         return -1;
439         }
440
441         if (i > 32)
442                 return -1;
443
444         if (sizeof(unsigned) == 4 && i == 32) {
445                 /* mask >>= 32 below may not work */
446                 mask = 0;
447         } else {
448                 mask = 0xffffffff;
449                 mask >>= i;
450         }
451         /* i == 0 -> *maskp = 0x00000000
452          * i == 1 -> *maskp = 0x80000000
453          * i == 4 -> *maskp = 0xf0000000
454          * i == 31 -> *maskp = 0xfffffffe
455          * i == 32 -> *maskp = 0xffffffff */
456         *maskp = (uint32_t)(~mask);
457         return 0;
458 }
459
460 /*
461  * Parse configuration file into in-memory linked list.
462  *
463  * Any previous IP rules are discarded.
464  * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
465  * are also discarded.  That is, previous settings are retained if flag is
466  * SUBDIR_PARSE.
467  * Error pages are only parsed on the main config file.
468  *
469  * path   Path where to look for httpd.conf (without filename).
470  * flag   Type of the parse request.
471  */
472 /* flag param: */
473 enum {
474         FIRST_PARSE    = 0, /* path will be "/etc" */
475         SIGNALED_PARSE = 1, /* path will be "/etc" */
476         SUBDIR_PARSE   = 2, /* path will be derived from URL */
477 };
478 static void parse_conf(const char *path, int flag)
479 {
480         /* internally used extra flag state */
481         enum { TRY_CURDIR_PARSE = 3 };
482
483         FILE *f;
484         const char *filename;
485         char buf[160];
486
487         /* discard old rules */
488         free_Htaccess_IP_list(&ip_a_d);
489         flg_deny_all = 0;
490         /* retain previous auth and mime config only for subdir parse */
491         if (flag != SUBDIR_PARSE) {
492                 free_Htaccess_list(&mime_a);
493 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
494                 free_Htaccess_list(&g_auth);
495 #endif
496 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
497                 free_Htaccess_list(&script_i);
498 #endif
499         }
500
501         filename = opt_c_configFile;
502         if (flag == SUBDIR_PARSE || filename == NULL) {
503                 filename = alloca(strlen(path) + sizeof(HTTPD_CONF) + 2);
504                 sprintf((char *)filename, "%s/%s", path, HTTPD_CONF);
505         }
506
507         while ((f = fopen_for_read(filename)) == NULL) {
508                 if (flag >= SUBDIR_PARSE) { /* SUBDIR or TRY_CURDIR */
509                         /* config file not found, no changes to config */
510                         return;
511                 }
512                 if (flag == FIRST_PARSE) {
513                         /* -c CONFFILE given, but CONFFILE doesn't exist? */
514                         if (opt_c_configFile)
515                                 bb_simple_perror_msg_and_die(opt_c_configFile);
516                         /* else: no -c, thus we looked at /etc/httpd.conf,
517                          * and it's not there. try ./httpd.conf: */
518                 }
519                 flag = TRY_CURDIR_PARSE;
520                 filename = HTTPD_CONF;
521         }
522
523 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
524         /* in "/file:user:pass" lines, we prepend path in subdirs */
525         if (flag != SUBDIR_PARSE)
526                 path = "";
527 #endif
528         /* The lines can be:
529          *
530          * I:default_index_file
531          * H:http_home
532          * [AD]:IP[/mask]   # allow/deny, * for wildcard
533          * Ennn:error.html  # error page for status nnn
534          * P:/url:[http://]hostname[:port]/new/path # reverse proxy
535          * .ext:mime/type   # mime type
536          * *.php:/path/php  # run xxx.php through an interpreter
537          * /file:user:pass  # username and password
538          */
539         while (fgets(buf, sizeof(buf), f) != NULL) {
540                 unsigned strlen_buf;
541                 unsigned char ch;
542                 char *after_colon;
543
544                 { /* remove all whitespace, and # comments */
545                         char *p, *p0;
546
547                         p0 = buf;
548                         /* skip non-whitespace beginning. Often the whole line
549                          * is non-whitespace. We want this case to work fast,
550                          * without needless copying, therefore we don't merge
551                          * this operation into next while loop. */
552                         while ((ch = *p0) != '\0' && ch != '\n' && ch != '#'
553                          && ch != ' ' && ch != '\t'
554                         ) {
555                                 p0++;
556                         }
557                         p = p0;
558                         /* if we enter this loop, we have some whitespace.
559                          * discard it */
560                         while (ch != '\0' && ch != '\n' && ch != '#') {
561                                 if (ch != ' ' && ch != '\t') {
562                                         *p++ = ch;
563                                 }
564                                 ch = *++p0;
565                         }
566                         *p = '\0';
567                         strlen_buf = p - buf;
568                         if (strlen_buf == 0)
569                                 continue; /* empty line */
570                 }
571
572                 after_colon = strchr(buf, ':');
573                 /* strange line? */
574                 if (after_colon == NULL || *++after_colon == '\0')
575                         goto config_error;
576
577                 ch = (buf[0] & ~0x20); /* toupper if it's a letter */
578
579                 if (ch == 'I') {
580                         if (index_page != index_html)
581                                 free((char*)index_page);
582                         index_page = xstrdup(after_colon);
583                         continue;
584                 }
585
586                 /* do not allow jumping around using H in subdir's configs */
587                 if (flag == FIRST_PARSE && ch == 'H') {
588                         home_httpd = xstrdup(after_colon);
589                         xchdir(home_httpd);
590                         continue;
591                 }
592
593                 if (ch == 'A' || ch == 'D') {
594                         Htaccess_IP *pip;
595
596                         if (*after_colon == '*') {
597                                 if (ch == 'D') {
598                                         /* memorize "deny all" */
599                                         flg_deny_all = 1;
600                                 }
601                                 /* skip assumed "A:*", it is a default anyway */
602                                 continue;
603                         }
604                         /* store "allow/deny IP/mask" line */
605                         pip = xzalloc(sizeof(*pip));
606                         if (scan_ip_mask(after_colon, &pip->ip, &pip->mask)) {
607                                 /* IP{/mask} syntax error detected, protect all */
608                                 ch = 'D';
609                                 pip->mask = 0;
610                         }
611                         pip->allow_deny = ch;
612                         if (ch == 'D') {
613                                 /* Deny:from_IP - prepend */
614                                 pip->next = ip_a_d;
615                                 ip_a_d = pip;
616                         } else {
617                                 /* A:from_IP - append (thus all D's precedes A's) */
618                                 Htaccess_IP *prev_IP = ip_a_d;
619                                 if (prev_IP == NULL) {
620                                         ip_a_d = pip;
621                                 } else {
622                                         while (prev_IP->next)
623                                                 prev_IP = prev_IP->next;
624                                         prev_IP->next = pip;
625                                 }
626                         }
627                         continue;
628                 }
629
630 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
631                 if (flag == FIRST_PARSE && ch == 'E') {
632                         unsigned i;
633                         int status = atoi(buf + 1); /* error status code */
634
635                         if (status < HTTP_CONTINUE) {
636                                 goto config_error;
637                         }
638                         /* then error page; find matching status */
639                         for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
640                                 if (http_response_type[i] == status) {
641                                         /* We chdir to home_httpd, thus no need to
642                                          * concat_path_file(home_httpd, after_colon)
643                                          * here */
644                                         http_error_page[i] = xstrdup(after_colon);
645                                         break;
646                                 }
647                         }
648                         continue;
649                 }
650 #endif
651
652 #if ENABLE_FEATURE_HTTPD_PROXY
653                 if (flag == FIRST_PARSE && ch == 'P') {
654                         /* P:/url:[http://]hostname[:port]/new/path */
655                         char *url_from, *host_port, *url_to;
656                         Htaccess_Proxy *proxy_entry;
657
658                         url_from = after_colon;
659                         host_port = strchr(after_colon, ':');
660                         if (host_port == NULL) {
661                                 goto config_error;
662                         }
663                         *host_port++ = '\0';
664                         if (strncmp(host_port, "http://", 7) == 0)
665                                 host_port += 7;
666                         if (*host_port == '\0') {
667                                 goto config_error;
668                         }
669                         url_to = strchr(host_port, '/');
670                         if (url_to == NULL) {
671                                 goto config_error;
672                         }
673                         *url_to = '\0';
674                         proxy_entry = xzalloc(sizeof(*proxy_entry));
675                         proxy_entry->url_from = xstrdup(url_from);
676                         proxy_entry->host_port = xstrdup(host_port);
677                         *url_to = '/';
678                         proxy_entry->url_to = xstrdup(url_to);
679                         proxy_entry->next = proxy;
680                         proxy = proxy_entry;
681                         continue;
682                 }
683 #endif
684                 /* the rest of directives are non-alphabetic,
685                  * must avoid using "toupper'ed" ch */
686                 ch = buf[0];
687
688                 if (ch == '.' /* ".ext:mime/type" */
689 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
690                  || (ch == '*' && buf[1] == '.') /* "*.php:/path/php" */
691 #endif
692                 ) {
693                         char *p;
694                         Htaccess *cur;
695
696                         cur = xzalloc(sizeof(*cur) /* includes space for NUL */ + strlen_buf);
697                         strcpy(cur->before_colon, buf);
698                         p = cur->before_colon + (after_colon - buf);
699                         p[-1] = '\0';
700                         cur->after_colon = p;
701                         if (ch == '.') {
702                                 /* .mime line: prepend to mime_a list */
703                                 cur->next = mime_a;
704                                 mime_a = cur;
705                         }
706 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
707                         else {
708                                 /* script interpreter line: prepend to script_i list */
709                                 cur->next = script_i;
710                                 script_i = cur;
711                         }
712 #endif
713                         continue;
714                 }
715
716 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
717                 if (ch == '/') { /* "/file:user:pass" */
718                         char *p;
719                         Htaccess *cur;
720                         unsigned file_len;
721
722                         /* note: path is "" unless we are in SUBDIR parse,
723                          * otherwise it does NOT start with "/" */
724                         cur = xzalloc(sizeof(*cur) /* includes space for NUL */
725                                 + 1 + strlen(path)
726                                 + strlen_buf
727                                 );
728                         /* form "/path/file" */
729                         sprintf(cur->before_colon, "/%s%.*s",
730                                 path,
731                                 (int) (after_colon - buf - 1), /* includes "/", but not ":" */
732                                 buf);
733                         /* canonicalize it */
734                         p = bb_simplify_abs_path_inplace(cur->before_colon);
735                         file_len = p - cur->before_colon;
736                         /* add "user:pass" after NUL */
737                         strcpy(++p, after_colon);
738                         cur->after_colon = p;
739
740                         /* insert cur into g_auth */
741                         /* g_auth is sorted by decreased filename length */
742                         {
743                                 Htaccess *auth, **authp;
744
745                                 authp = &g_auth;
746                                 while ((auth = *authp) != NULL) {
747                                         if (file_len >= strlen(auth->before_colon)) {
748                                                 /* insert cur before auth */
749                                                 cur->next = auth;
750                                                 break;
751                                         }
752                                         authp = &auth->next;
753                                 }
754                                 *authp = cur;
755                         }
756                         continue;
757                 }
758 #endif /* BASIC_AUTH */
759
760                 /* the line is not recognized */
761  config_error:
762                 bb_error_msg("config error '%s' in '%s'", buf, filename);
763          } /* while (fgets) */
764
765          fclose(f);
766 }
767
768 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
769 /*
770  * Given a string, html-encode special characters.
771  * This is used for the -e command line option to provide an easy way
772  * for scripts to encode result data without confusing browsers.  The
773  * returned string pointer is memory allocated by malloc().
774  *
775  * Returns a pointer to the encoded string (malloced).
776  */
777 static char *encodeString(const char *string)
778 {
779         /* take the simple route and encode everything */
780         /* could possibly scan once to get length.     */
781         int len = strlen(string);
782         char *out = xmalloc(len * 6 + 1);
783         char *p = out;
784         char ch;
785
786         while ((ch = *string++) != '\0') {
787                 /* very simple check for what to encode */
788                 if (isalnum(ch))
789                         *p++ = ch;
790                 else
791                         p += sprintf(p, "&#%d;", (unsigned char) ch);
792         }
793         *p = '\0';
794         return out;
795 }
796 #endif
797
798 /*
799  * Given a URL encoded string, convert it to plain ascii.
800  * Since decoding always makes strings smaller, the decode is done in-place.
801  * Thus, callers should xstrdup() the argument if they do not want the
802  * argument modified.  The return is the original pointer, allowing this
803  * function to be easily used as arguments to other functions.
804  *
805  * string    The first string to decode.
806  * option_d  1 if called for httpd -d
807  *
808  * Returns a pointer to the decoded string (same as input).
809  */
810 static unsigned hex_to_bin(unsigned char c)
811 {
812         unsigned v;
813
814         v = c - '0';
815         if (v <= 9)
816                 return v;
817         /* c | 0x20: letters to lower case, non-letters
818          * to (potentially different) non-letters */
819         v = (unsigned)(c | 0x20) - 'a';
820         if (v <= 5)
821                 return v + 10;
822         return ~0;
823 /* For testing:
824 void t(char c) { printf("'%c'(%u) %u\n", c, c, hex_to_bin(c)); }
825 int main() { t(0x10); t(0x20); t('0'); t('9'); t('A'); t('F'); t('a'); t('f');
826 t('0'-1); t('9'+1); t('A'-1); t('F'+1); t('a'-1); t('f'+1); return 0; }
827 */
828 }
829 static char *decodeString(char *orig, int option_d)
830 {
831         /* note that decoded string is always shorter than original */
832         char *string = orig;
833         char *ptr = string;
834         char c;
835
836         while ((c = *ptr++) != '\0') {
837                 unsigned v;
838
839                 if (option_d && c == '+') {
840                         *string++ = ' ';
841                         continue;
842                 }
843                 if (c != '%') {
844                         *string++ = c;
845                         continue;
846                 }
847                 v = hex_to_bin(ptr[0]);
848                 if (v > 15) {
849  bad_hex:
850                         if (!option_d)
851                                 return NULL;
852                         *string++ = '%';
853                         continue;
854                 }
855                 v = (v * 16) | hex_to_bin(ptr[1]);
856                 if (v > 255)
857                         goto bad_hex;
858                 if (!option_d && (v == '/' || v == '\0')) {
859                         /* caller takes it as indication of invalid
860                          * (dangerous wrt exploits) chars */
861                         return orig + 1;
862                 }
863                 *string++ = v;
864                 ptr += 2;
865         }
866         *string = '\0';
867         return orig;
868 }
869
870 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
871 /*
872  * Decode a base64 data stream as per rfc1521.
873  * Note that the rfc states that non base64 chars are to be ignored.
874  * Since the decode always results in a shorter size than the input,
875  * it is OK to pass the input arg as an output arg.
876  * Parameter: a pointer to a base64 encoded string.
877  * Decoded data is stored in-place.
878  */
879 static void decodeBase64(char *Data)
880 {
881         const unsigned char *in = (const unsigned char *)Data;
882         /* The decoded size will be at most 3/4 the size of the encoded */
883         unsigned ch = 0;
884         int i = 0;
885
886         while (*in) {
887                 int t = *in++;
888
889                 if (t >= '0' && t <= '9')
890                         t = t - '0' + 52;
891                 else if (t >= 'A' && t <= 'Z')
892                         t = t - 'A';
893                 else if (t >= 'a' && t <= 'z')
894                         t = t - 'a' + 26;
895                 else if (t == '+')
896                         t = 62;
897                 else if (t == '/')
898                         t = 63;
899                 else if (t == '=')
900                         t = 0;
901                 else
902                         continue;
903
904                 ch = (ch << 6) | t;
905                 i++;
906                 if (i == 4) {
907                         *Data++ = (char) (ch >> 16);
908                         *Data++ = (char) (ch >> 8);
909                         *Data++ = (char) ch;
910                         i = 0;
911                 }
912         }
913         *Data = '\0';
914 }
915 #endif
916
917 /*
918  * Create a listen server socket on the designated port.
919  */
920 static int openServer(void)
921 {
922         unsigned n = bb_strtou(bind_addr_or_port, NULL, 10);
923         if (!errno && n && n <= 0xffff)
924                 n = create_and_bind_stream_or_die(NULL, n);
925         else
926                 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
927         xlisten(n, 9);
928         return n;
929 }
930
931 /*
932  * Log the connection closure and exit.
933  */
934 static void log_and_exit(void) NORETURN;
935 static void log_and_exit(void)
936 {
937         /* Paranoia. IE said to be buggy. It may send some extra data
938          * or be confused by us just exiting without SHUT_WR. Oh well. */
939         shutdown(1, SHUT_WR);
940         /* Why??
941         (this also messes up stdin when user runs httpd -i from terminal)
942         ndelay_on(0);
943         while (read(STDIN_FILENO, iobuf, IOBUF_SIZE) > 0)
944                 continue;
945         */
946
947         if (verbose > 2)
948                 bb_error_msg("closed");
949         _exit(xfunc_error_retval);
950 }
951
952 /*
953  * Create and send HTTP response headers.
954  * The arguments are combined and sent as one write operation.  Note that
955  * IE will puke big-time if the headers are not sent in one packet and the
956  * second packet is delayed for any reason.
957  * responseNum - the result code to send.
958  */
959 static void send_headers(int responseNum)
960 {
961         static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
962
963         const char *responseString = "";
964         const char *infoString = NULL;
965         const char *mime_type;
966 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
967         const char *error_page = NULL;
968 #endif
969         unsigned i;
970         time_t timer = time(NULL);
971         char tmp_str[80];
972         int len;
973
974         for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
975                 if (http_response_type[i] == responseNum) {
976                         responseString = http_response[i].name;
977                         infoString = http_response[i].info;
978 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
979                         error_page = http_error_page[i];
980 #endif
981                         break;
982                 }
983         }
984         /* error message is HTML */
985         mime_type = responseNum == HTTP_OK ?
986                                 found_mime_type : "text/html";
987
988         if (verbose)
989                 bb_error_msg("response:%u", responseNum);
990
991         /* emit the current date */
992         strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
993         len = sprintf(iobuf,
994                         "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
995                         "Date: %s\r\nConnection: close\r\n",
996                         responseNum, responseString, mime_type, tmp_str);
997
998 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
999         if (responseNum == HTTP_UNAUTHORIZED) {
1000                 len += sprintf(iobuf + len,
1001                                 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
1002                                 g_realm);
1003         }
1004 #endif
1005         if (responseNum == HTTP_MOVED_TEMPORARILY) {
1006                 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
1007                                 found_moved_temporarily,
1008                                 (g_query ? "?" : ""),
1009                                 (g_query ? g_query : ""));
1010         }
1011
1012 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
1013         if (error_page && access(error_page, R_OK) == 0) {
1014                 strcat(iobuf, "\r\n");
1015                 len += 2;
1016
1017                 if (DEBUG)
1018                         fprintf(stderr, "headers: '%s'\n", iobuf);
1019                 full_write(STDOUT_FILENO, iobuf, len);
1020                 if (DEBUG)
1021                         fprintf(stderr, "writing error page: '%s'\n", error_page);
1022                 return send_file_and_exit(error_page, SEND_BODY);
1023         }
1024 #endif
1025
1026         if (file_size != -1) {    /* file */
1027                 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
1028 #if ENABLE_FEATURE_HTTPD_RANGES
1029                 if (responseNum == HTTP_PARTIAL_CONTENT) {
1030                         len += sprintf(iobuf + len, "Content-Range: bytes %"OFF_FMT"u-%"OFF_FMT"u/%"OFF_FMT"u\r\n",
1031                                         range_start,
1032                                         range_end,
1033                                         file_size);
1034                         file_size = range_end - range_start + 1;
1035                 }
1036 #endif
1037                 len += sprintf(iobuf + len,
1038 #if ENABLE_FEATURE_HTTPD_RANGES
1039                         "Accept-Ranges: bytes\r\n"
1040 #endif
1041                         "Last-Modified: %s\r\n%s %"OFF_FMT"u\r\n",
1042                                 tmp_str,
1043                                 content_gzip ? "Transfer-length:" : "Content-length:",
1044                                 file_size
1045                 );
1046         }
1047
1048         if (content_gzip)
1049                 len += sprintf(iobuf + len, "Content-Encoding: gzip\r\n");
1050
1051         iobuf[len++] = '\r';
1052         iobuf[len++] = '\n';
1053         if (infoString) {
1054                 len += sprintf(iobuf + len,
1055                                 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
1056                                 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
1057                                 responseNum, responseString,
1058                                 responseNum, responseString, infoString);
1059         }
1060         if (DEBUG)
1061                 fprintf(stderr, "headers: '%s'\n", iobuf);
1062         if (full_write(STDOUT_FILENO, iobuf, len) != len) {
1063                 if (verbose > 1)
1064                         bb_perror_msg("error");
1065                 log_and_exit();
1066         }
1067 }
1068
1069 static void send_headers_and_exit(int responseNum) NORETURN;
1070 static void send_headers_and_exit(int responseNum)
1071 {
1072         IF_FEATURE_HTTPD_GZIP(content_gzip = 0;)
1073         send_headers(responseNum);
1074         log_and_exit();
1075 }
1076
1077 /*
1078  * Read from the socket until '\n' or EOF. '\r' chars are removed.
1079  * '\n' is replaced with NUL.
1080  * Return number of characters read or 0 if nothing is read
1081  * ('\r' and '\n' are not counted).
1082  * Data is returned in iobuf.
1083  */
1084 static int get_line(void)
1085 {
1086         int count = 0;
1087         char c;
1088
1089         alarm(HEADER_READ_TIMEOUT);
1090         while (1) {
1091                 if (hdr_cnt <= 0) {
1092                         hdr_cnt = safe_read(STDIN_FILENO, hdr_buf, sizeof(hdr_buf));
1093                         if (hdr_cnt <= 0)
1094                                 break;
1095                         hdr_ptr = hdr_buf;
1096                 }
1097                 iobuf[count] = c = *hdr_ptr++;
1098                 hdr_cnt--;
1099
1100                 if (c == '\r')
1101                         continue;
1102                 if (c == '\n') {
1103                         iobuf[count] = '\0';
1104                         break;
1105                 }
1106                 if (count < (IOBUF_SIZE - 1))      /* check overflow */
1107                         count++;
1108         }
1109         return count;
1110 }
1111
1112 #if ENABLE_FEATURE_HTTPD_CGI || ENABLE_FEATURE_HTTPD_PROXY
1113
1114 /* gcc 4.2.1 fares better with NOINLINE */
1115 static NOINLINE void cgi_io_loop_and_exit(int fromCgi_rd, int toCgi_wr, int post_len) NORETURN;
1116 static NOINLINE void cgi_io_loop_and_exit(int fromCgi_rd, int toCgi_wr, int post_len)
1117 {
1118         enum { FROM_CGI = 1, TO_CGI = 2 }; /* indexes in pfd[] */
1119         struct pollfd pfd[3];
1120         int out_cnt; /* we buffer a bit of initial CGI output */
1121         int count;
1122
1123         /* iobuf is used for CGI -> network data,
1124          * hdr_buf is for network -> CGI data (POSTDATA) */
1125
1126         /* If CGI dies, we still want to correctly finish reading its output
1127          * and send it to the peer. So please no SIGPIPEs! */
1128         signal(SIGPIPE, SIG_IGN);
1129
1130         // We inconsistently handle a case when more POSTDATA from network
1131         // is coming than we expected. We may give *some part* of that
1132         // extra data to CGI.
1133
1134         //if (hdr_cnt > post_len) {
1135         //      /* We got more POSTDATA from network than we expected */
1136         //      hdr_cnt = post_len;
1137         //}
1138         post_len -= hdr_cnt;
1139         /* post_len - number of POST bytes not yet read from network */
1140
1141         /* NB: breaking out of this loop jumps to log_and_exit() */
1142         out_cnt = 0;
1143         while (1) {
1144                 memset(pfd, 0, sizeof(pfd));
1145
1146                 pfd[FROM_CGI].fd = fromCgi_rd;
1147                 pfd[FROM_CGI].events = POLLIN;
1148
1149                 if (toCgi_wr) {
1150                         pfd[TO_CGI].fd = toCgi_wr;
1151                         if (hdr_cnt > 0) {
1152                                 pfd[TO_CGI].events = POLLOUT;
1153                         } else if (post_len > 0) {
1154                                 pfd[0].events = POLLIN;
1155                         } else {
1156                                 /* post_len <= 0 && hdr_cnt <= 0:
1157                                  * no more POST data to CGI,
1158                                  * let CGI see EOF on CGI's stdin */
1159                                 if (toCgi_wr != fromCgi_rd)
1160                                         close(toCgi_wr);
1161                                 toCgi_wr = 0;
1162                         }
1163                 }
1164
1165                 /* Now wait on the set of sockets */
1166                 count = safe_poll(pfd, toCgi_wr ? TO_CGI+1 : FROM_CGI+1, -1);
1167                 if (count <= 0) {
1168 #if 0
1169                         if (safe_waitpid(pid, &status, WNOHANG) <= 0) {
1170                                 /* Weird. CGI didn't exit and no fd's
1171                                  * are ready, yet poll returned?! */
1172                                 continue;
1173                         }
1174                         if (DEBUG && WIFEXITED(status))
1175                                 bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
1176                         if (DEBUG && WIFSIGNALED(status))
1177                                 bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
1178 #endif
1179                         break;
1180                 }
1181
1182                 if (pfd[TO_CGI].revents) {
1183                         /* hdr_cnt > 0 here due to the way pfd[TO_CGI].events set */
1184                         /* Have data from peer and can write to CGI */
1185                         count = safe_write(toCgi_wr, hdr_ptr, hdr_cnt);
1186                         /* Doesn't happen, we dont use nonblocking IO here
1187                          *if (count < 0 && errno == EAGAIN) {
1188                          *      ...
1189                          *} else */
1190                         if (count > 0) {
1191                                 hdr_ptr += count;
1192                                 hdr_cnt -= count;
1193                         } else {
1194                                 /* EOF/broken pipe to CGI, stop piping POST data */
1195                                 hdr_cnt = post_len = 0;
1196                         }
1197                 }
1198
1199                 if (pfd[0].revents) {
1200                         /* post_len > 0 && hdr_cnt == 0 here */
1201                         /* We expect data, prev data portion is eaten by CGI
1202                          * and there *is* data to read from the peer
1203                          * (POSTDATA) */
1204                         //count = post_len > (int)sizeof(hdr_buf) ? (int)sizeof(hdr_buf) : post_len;
1205                         //count = safe_read(STDIN_FILENO, hdr_buf, count);
1206                         count = safe_read(STDIN_FILENO, hdr_buf, sizeof(hdr_buf));
1207                         if (count > 0) {
1208                                 hdr_cnt = count;
1209                                 hdr_ptr = hdr_buf;
1210                                 post_len -= count;
1211                         } else {
1212                                 /* no more POST data can be read */
1213                                 post_len = 0;
1214                         }
1215                 }
1216
1217                 if (pfd[FROM_CGI].revents) {
1218                         /* There is something to read from CGI */
1219                         char *rbuf = iobuf;
1220
1221                         /* Are we still buffering CGI output? */
1222                         if (out_cnt >= 0) {
1223                                 /* HTTP_200[] has single "\r\n" at the end.
1224                                  * According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1225                                  * CGI scripts MUST send their own header terminated by
1226                                  * empty line, then data. That's why we have only one
1227                                  * <cr><lf> pair here. We will output "200 OK" line
1228                                  * if needed, but CGI still has to provide blank line
1229                                  * between header and body */
1230
1231                                 /* Must use safe_read, not full_read, because
1232                                  * CGI may output a few first bytes and then wait
1233                                  * for POSTDATA without closing stdout.
1234                                  * With full_read we may wait here forever. */
1235                                 count = safe_read(fromCgi_rd, rbuf + out_cnt, PIPE_BUF - 8);
1236                                 if (count <= 0) {
1237                                         /* eof (or error) and there was no "HTTP",
1238                                          * so write it, then write received data */
1239                                         if (out_cnt) {
1240                                                 full_write(STDOUT_FILENO, HTTP_200, sizeof(HTTP_200)-1);
1241                                                 full_write(STDOUT_FILENO, rbuf, out_cnt);
1242                                         }
1243                                         break; /* CGI stdout is closed, exiting */
1244                                 }
1245                                 out_cnt += count;
1246                                 count = 0;
1247                                 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1248                                 if (out_cnt >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1249                                         /* send "HTTP/1.0 " */
1250                                         if (full_write(STDOUT_FILENO, HTTP_200, 9) != 9)
1251                                                 break;
1252                                         rbuf += 8; /* skip "Status: " */
1253                                         count = out_cnt - 8;
1254                                         out_cnt = -1; /* buffering off */
1255                                 } else if (out_cnt >= 4) {
1256                                         /* Did CGI add "HTTP"? */
1257                                         if (memcmp(rbuf, HTTP_200, 4) != 0) {
1258                                                 /* there is no "HTTP", do it ourself */
1259                                                 if (full_write(STDOUT_FILENO, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1260                                                         break;
1261                                         }
1262                                         /* Commented out:
1263                                         if (!strstr(rbuf, "ontent-")) {
1264                                                 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1265                                         }
1266                                          * Counter-example of valid CGI without Content-type:
1267                                          * echo -en "HTTP/1.0 302 Found\r\n"
1268                                          * echo -en "Location: http://www.busybox.net\r\n"
1269                                          * echo -en "\r\n"
1270                                          */
1271                                         count = out_cnt;
1272                                         out_cnt = -1; /* buffering off */
1273                                 }
1274                         } else {
1275                                 count = safe_read(fromCgi_rd, rbuf, PIPE_BUF);
1276                                 if (count <= 0)
1277                                         break;  /* eof (or error) */
1278                         }
1279                         if (full_write(STDOUT_FILENO, rbuf, count) != count)
1280                                 break;
1281                         if (DEBUG)
1282                                 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1283                 } /* if (pfd[FROM_CGI].revents) */
1284         } /* while (1) */
1285         log_and_exit();
1286 }
1287 #endif
1288
1289 #if ENABLE_FEATURE_HTTPD_CGI
1290
1291 static void setenv1(const char *name, const char *value)
1292 {
1293         setenv(name, value ? value : "", 1);
1294 }
1295
1296 /*
1297  * Spawn CGI script, forward CGI's stdin/out <=> network
1298  *
1299  * Environment variables are set up and the script is invoked with pipes
1300  * for stdin/stdout.  If a POST is being done the script is fed the POST
1301  * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
1302  *
1303  * Parameters:
1304  * const char *url              The requested URL (with leading /).
1305  * int post_len                 Length of the POST body.
1306  * const char *cookie           For set HTTP_COOKIE.
1307  * const char *content_type     For set CONTENT_TYPE.
1308  */
1309 static void send_cgi_and_exit(
1310                 const char *url,
1311                 const char *request,
1312                 int post_len,
1313                 const char *cookie,
1314                 const char *content_type) NORETURN;
1315 static void send_cgi_and_exit(
1316                 const char *url,
1317                 const char *request,
1318                 int post_len,
1319                 const char *cookie,
1320                 const char *content_type)
1321 {
1322         struct fd_pair fromCgi;  /* CGI -> httpd pipe */
1323         struct fd_pair toCgi;    /* httpd -> CGI pipe */
1324         char *script;
1325         int pid;
1326
1327         /* Make a copy. NB: caller guarantees:
1328          * url[0] == '/', url[1] != '/' */
1329         url = xstrdup(url);
1330
1331         /*
1332          * We are mucking with environment _first_ and then vfork/exec,
1333          * this allows us to use vfork safely. Parent doesn't care about
1334          * these environment changes anyway.
1335          */
1336
1337         /* Check for [dirs/]script.cgi/PATH_INFO */
1338         script = (char*)url;
1339         while ((script = strchr(script + 1, '/')) != NULL) {
1340                 *script = '\0';
1341                 if (!is_directory(url + 1, 1, NULL)) {
1342                         /* not directory, found script.cgi/PATH_INFO */
1343                         *script = '/';
1344                         break;
1345                 }
1346                 *script = '/'; /* is directory, find next '/' */
1347         }
1348         setenv1("PATH_INFO", script);   /* set to /PATH_INFO or "" */
1349         setenv1("REQUEST_METHOD", request);
1350         if (g_query) {
1351                 putenv(xasprintf("%s=%s?%s", "REQUEST_URI", url, g_query));
1352         } else {
1353                 setenv1("REQUEST_URI", url);
1354         }
1355         if (script != NULL)
1356                 *script = '\0';         /* cut off /PATH_INFO */
1357
1358         /* SCRIPT_FILENAME is required by PHP in CGI mode */
1359         if (home_httpd[0] == '/') {
1360                 char *fullpath = concat_path_file(home_httpd, url);
1361                 setenv1("SCRIPT_FILENAME", fullpath);
1362         }
1363         /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1364         setenv1("SCRIPT_NAME", url);
1365         /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1366          * QUERY_STRING: The information which follows the ? in the URL
1367          * which referenced this script. This is the query information.
1368          * It should not be decoded in any fashion. This variable
1369          * should always be set when there is query information,
1370          * regardless of command line decoding. */
1371         /* (Older versions of bbox seem to do some decoding) */
1372         setenv1("QUERY_STRING", g_query);
1373         putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1374         putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1375         putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1376         /* Having _separate_ variables for IP and port defeats
1377          * the purpose of having socket abstraction. Which "port"
1378          * are you using on Unix domain socket?
1379          * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1380          * Oh well... */
1381         {
1382                 char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
1383                 char *cp = strrchr(p, ':');
1384                 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1385                         cp = NULL;
1386                 if (cp) *cp = '\0'; /* delete :PORT */
1387                 setenv1("REMOTE_ADDR", p);
1388                 if (cp) {
1389                         *cp = ':';
1390 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1391                         setenv1("REMOTE_PORT", cp + 1);
1392 #endif
1393                 }
1394         }
1395         setenv1("HTTP_USER_AGENT", user_agent);
1396         if (http_accept)
1397                 setenv1("HTTP_ACCEPT", http_accept);
1398         if (http_accept_language)
1399                 setenv1("HTTP_ACCEPT_LANGUAGE", http_accept_language);
1400         if (post_len)
1401                 putenv(xasprintf("CONTENT_LENGTH=%d", post_len));
1402         if (cookie)
1403                 setenv1("HTTP_COOKIE", cookie);
1404         if (content_type)
1405                 setenv1("CONTENT_TYPE", content_type);
1406 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1407         if (remoteuser) {
1408                 setenv1("REMOTE_USER", remoteuser);
1409                 putenv((char*)"AUTH_TYPE=Basic");
1410         }
1411 #endif
1412         if (referer)
1413                 setenv1("HTTP_REFERER", referer);
1414         setenv1("HTTP_HOST", host); /* set to "" if NULL */
1415         /* setenv1("SERVER_NAME", safe_gethostname()); - don't do this,
1416          * just run "env SERVER_NAME=xyz httpd ..." instead */
1417
1418         xpiped_pair(fromCgi);
1419         xpiped_pair(toCgi);
1420
1421         pid = vfork();
1422         if (pid < 0) {
1423                 /* TODO: log perror? */
1424                 log_and_exit();
1425         }
1426
1427         if (!pid) {
1428                 /* Child process */
1429                 char *argv[3];
1430
1431                 xfunc_error_retval = 242;
1432
1433                 /* NB: close _first_, then move fds! */
1434                 close(toCgi.wr);
1435                 close(fromCgi.rd);
1436                 xmove_fd(toCgi.rd, 0);  /* replace stdin with the pipe */
1437                 xmove_fd(fromCgi.wr, 1);  /* replace stdout with the pipe */
1438                 /* User seeing stderr output can be a security problem.
1439                  * If CGI really wants that, it can always do dup itself. */
1440                 /* dup2(1, 2); */
1441
1442                 /* Chdiring to script's dir */
1443                 script = strrchr(url, '/');
1444                 if (script != url) { /* paranoia */
1445                         *script = '\0';
1446                         if (chdir(url + 1) != 0) {
1447                                 bb_perror_msg("chdir(%s)", url + 1);
1448                                 goto error_execing_cgi;
1449                         }
1450                         // not needed: *script = '/';
1451                 }
1452                 script++;
1453
1454                 /* set argv[0] to name without path */
1455                 argv[0] = script;
1456                 argv[1] = NULL;
1457
1458 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1459                 {
1460                         char *suffix = strrchr(script, '.');
1461
1462                         if (suffix) {
1463                                 Htaccess *cur;
1464                                 for (cur = script_i; cur; cur = cur->next) {
1465                                         if (strcmp(cur->before_colon + 1, suffix) == 0) {
1466                                                 /* found interpreter name */
1467                                                 argv[0] = cur->after_colon;
1468                                                 argv[1] = script;
1469                                                 argv[2] = NULL;
1470                                                 break;
1471                                         }
1472                                 }
1473                         }
1474                 }
1475 #endif
1476                 /* restore default signal dispositions for CGI process */
1477                 bb_signals(0
1478                         | (1 << SIGCHLD)
1479                         | (1 << SIGPIPE)
1480                         | (1 << SIGHUP)
1481                         , SIG_DFL);
1482
1483                 /* _NOT_ execvp. We do not search PATH. argv[0] is a filename
1484                  * without any dir components and will only match a file
1485                  * in the current directory */
1486                 execv(argv[0], argv);
1487                 if (verbose)
1488                         bb_perror_msg("can't execute '%s'", argv[0]);
1489  error_execing_cgi:
1490                 /* send to stdout
1491                  * (we are CGI here, our stdout is pumped to the net) */
1492                 send_headers_and_exit(HTTP_NOT_FOUND);
1493         } /* end child */
1494
1495         /* Parent process */
1496
1497         /* Restore variables possibly changed by child */
1498         xfunc_error_retval = 0;
1499
1500         /* Pump data */
1501         close(fromCgi.wr);
1502         close(toCgi.rd);
1503         cgi_io_loop_and_exit(fromCgi.rd, toCgi.wr, post_len);
1504 }
1505
1506 #endif          /* FEATURE_HTTPD_CGI */
1507
1508 /*
1509  * Send a file response to a HTTP request, and exit
1510  *
1511  * Parameters:
1512  * const char *url  The requested URL (with leading /).
1513  * what             What to send (headers/body/both).
1514  */
1515 static NOINLINE void send_file_and_exit(const char *url, int what)
1516 {
1517         char *suffix;
1518         int fd;
1519         ssize_t count;
1520
1521         if (content_gzip) {
1522                 /* does <url>.gz exist? Then use it instead */
1523                 char *gzurl = xasprintf("%s.gz", url);
1524                 fd = open(gzurl, O_RDONLY);
1525                 free(gzurl);
1526                 if (fd != -1) {
1527                         struct stat sb;
1528                         fstat(fd, &sb);
1529                         file_size = sb.st_size;
1530                         last_mod = sb.st_mtime;
1531                 } else {
1532                         IF_FEATURE_HTTPD_GZIP(content_gzip = 0;)
1533                         fd = open(url, O_RDONLY);
1534                 }
1535         } else {
1536                 fd = open(url, O_RDONLY);
1537         }
1538         if (fd < 0) {
1539                 if (DEBUG)
1540                         bb_perror_msg("can't open '%s'", url);
1541                 /* Error pages are sent by using send_file_and_exit(SEND_BODY).
1542                  * IOW: it is unsafe to call send_headers_and_exit
1543                  * if what is SEND_BODY! Can recurse! */
1544                 if (what != SEND_BODY)
1545                         send_headers_and_exit(HTTP_NOT_FOUND);
1546                 log_and_exit();
1547         }
1548         /* If you want to know about EPIPE below
1549          * (happens if you abort downloads from local httpd): */
1550         signal(SIGPIPE, SIG_IGN);
1551
1552         /* If not found, default is "application/octet-stream" */
1553         found_mime_type = "application/octet-stream";
1554         suffix = strrchr(url, '.');
1555         if (suffix) {
1556                 static const char suffixTable[] ALIGN1 =
1557                         /* Shorter suffix must be first:
1558                          * ".html.htm" will fail for ".htm"
1559                          */
1560                         ".txt.h.c.cc.cpp\0" "text/plain\0"
1561                         /* .htm line must be after .h line */
1562                         ".htm.html\0" "text/html\0"
1563                         ".jpg.jpeg\0" "image/jpeg\0"
1564                         ".gif\0"      "image/gif\0"
1565                         ".png\0"      "image/png\0"
1566                         /* .css line must be after .c line */
1567                         ".css\0"      "text/css\0"
1568                         ".wav\0"      "audio/wav\0"
1569                         ".avi\0"      "video/x-msvideo\0"
1570                         ".qt.mov\0"   "video/quicktime\0"
1571                         ".mpe.mpeg\0" "video/mpeg\0"
1572                         ".mid.midi\0" "audio/midi\0"
1573                         ".mp3\0"      "audio/mpeg\0"
1574 #if 0  /* unpopular */
1575                         ".au\0"       "audio/basic\0"
1576                         ".pac\0"      "application/x-ns-proxy-autoconfig\0"
1577                         ".vrml.wrl\0" "model/vrml\0"
1578 #endif
1579                         /* compiler adds another "\0" here */
1580                 ;
1581                 Htaccess *cur;
1582
1583                 /* Examine built-in table */
1584                 const char *table = suffixTable;
1585                 const char *table_next;
1586                 for (; *table; table = table_next) {
1587                         const char *try_suffix;
1588                         const char *mime_type;
1589                         mime_type  = table + strlen(table) + 1;
1590                         table_next = mime_type + strlen(mime_type) + 1;
1591                         try_suffix = strstr(table, suffix);
1592                         if (!try_suffix)
1593                                 continue;
1594                         try_suffix += strlen(suffix);
1595                         if (*try_suffix == '\0' || *try_suffix == '.') {
1596                                 found_mime_type = mime_type;
1597                                 break;
1598                         }
1599                         /* Example: strstr(table, ".av") != NULL, but it
1600                          * does not match ".avi" after all and we end up here.
1601                          * The table is arranged so that in this case we know
1602                          * that it can't match anything in the following lines,
1603                          * and we stop the search: */
1604                         break;
1605                 }
1606                 /* ...then user's table */
1607                 for (cur = mime_a; cur; cur = cur->next) {
1608                         if (strcmp(cur->before_colon, suffix) == 0) {
1609                                 found_mime_type = cur->after_colon;
1610                                 break;
1611                         }
1612                 }
1613         }
1614
1615         if (DEBUG)
1616                 bb_error_msg("sending file '%s' content-type: %s",
1617                         url, found_mime_type);
1618
1619 #if ENABLE_FEATURE_HTTPD_RANGES
1620         if (what == SEND_BODY /* err pages and ranges don't mix */
1621          || content_gzip /* we are sending compressed page: can't do ranges */  ///why?
1622         ) {
1623                 range_start = 0;
1624         }
1625         range_len = MAXINT(off_t);
1626         if (range_start) {
1627                 if (!range_end) {
1628                         range_end = file_size - 1;
1629                 }
1630                 if (range_end < range_start
1631                  || lseek(fd, range_start, SEEK_SET) != range_start
1632                 ) {
1633                         lseek(fd, 0, SEEK_SET);
1634                         range_start = 0;
1635                 } else {
1636                         range_len = range_end - range_start + 1;
1637                         send_headers(HTTP_PARTIAL_CONTENT);
1638                         what = SEND_BODY;
1639                 }
1640         }
1641 #endif
1642         if (what & SEND_HEADERS)
1643                 send_headers(HTTP_OK);
1644 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1645         {
1646                 off_t offset = range_start;
1647                 while (1) {
1648                         /* sz is rounded down to 64k */
1649                         ssize_t sz = MAXINT(ssize_t) - 0xffff;
1650                         IF_FEATURE_HTTPD_RANGES(if (sz > range_len) sz = range_len;)
1651                         count = sendfile(STDOUT_FILENO, fd, &offset, sz);
1652                         if (count < 0) {
1653                                 if (offset == range_start)
1654                                         break; /* fall back to read/write loop */
1655                                 goto fin;
1656                         }
1657                         IF_FEATURE_HTTPD_RANGES(range_len -= sz;)
1658                         if (count == 0 || range_len == 0)
1659                                 log_and_exit();
1660                 }
1661         }
1662 #endif
1663         while ((count = safe_read(fd, iobuf, IOBUF_SIZE)) > 0) {
1664                 ssize_t n;
1665                 IF_FEATURE_HTTPD_RANGES(if (count > range_len) count = range_len;)
1666                 n = full_write(STDOUT_FILENO, iobuf, count);
1667                 if (count != n)
1668                         break;
1669                 IF_FEATURE_HTTPD_RANGES(range_len -= count;)
1670                 if (range_len == 0)
1671                         break;
1672         }
1673         if (count < 0) {
1674  IF_FEATURE_HTTPD_USE_SENDFILE(fin:)
1675                 if (verbose > 1)
1676                         bb_perror_msg("error");
1677         }
1678         log_and_exit();
1679 }
1680
1681 static int checkPermIP(void)
1682 {
1683         Htaccess_IP *cur;
1684
1685         for (cur = ip_a_d; cur; cur = cur->next) {
1686 #if DEBUG
1687                 fprintf(stderr,
1688                         "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1689                         rmt_ip_str,
1690                         (unsigned char)(cur->ip >> 24),
1691                         (unsigned char)(cur->ip >> 16),
1692                         (unsigned char)(cur->ip >> 8),
1693                         (unsigned char)(cur->ip),
1694                         (unsigned char)(cur->mask >> 24),
1695                         (unsigned char)(cur->mask >> 16),
1696                         (unsigned char)(cur->mask >> 8),
1697                         (unsigned char)(cur->mask)
1698                 );
1699 #endif
1700                 if ((rmt_ip & cur->mask) == cur->ip)
1701                         return (cur->allow_deny == 'A'); /* A -> 1 */
1702         }
1703
1704         return !flg_deny_all; /* depends on whether we saw "D:*" */
1705 }
1706
1707 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1708 /*
1709  * Config file entries are of the form "/<path>:<user>:<passwd>".
1710  * If config file has no prefix match for path, access is allowed.
1711  *
1712  * path                 The file path
1713  * user_and_passwd      "user:passwd" to validate
1714  *
1715  * Returns 1 if user_and_passwd is OK.
1716  */
1717 static int check_user_passwd(const char *path, const char *user_and_passwd)
1718 {
1719         Htaccess *cur;
1720         const char *prev = NULL;
1721
1722         for (cur = g_auth; cur; cur = cur->next) {
1723                 const char *dir_prefix;
1724                 size_t len;
1725
1726                 dir_prefix = cur->before_colon;
1727
1728                 /* WHY? */
1729                 /* If already saw a match, don't accept other different matches */
1730                 if (prev && strcmp(prev, dir_prefix) != 0)
1731                         continue;
1732
1733                 if (DEBUG)
1734                         fprintf(stderr, "checkPerm: '%s' ? '%s'\n", dir_prefix, user_and_passwd);
1735
1736                 /* If it's not a prefix match, continue searching */
1737                 len = strlen(dir_prefix);
1738                 if (len != 1 /* dir_prefix "/" matches all, don't need to check */
1739                  && (strncmp(dir_prefix, path, len) != 0
1740                     || (path[len] != '/' && path[len] != '\0'))
1741                 ) {
1742                         continue;
1743                 }
1744
1745                 /* Path match found */
1746                 prev = dir_prefix;
1747
1748                 if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1749                         char *md5_passwd;
1750
1751                         md5_passwd = strchr(cur->after_colon, ':');
1752                         if (md5_passwd && md5_passwd[1] == '$' && md5_passwd[2] == '1'
1753                          && md5_passwd[3] == '$' && md5_passwd[4]
1754                         ) {
1755                                 char *encrypted;
1756                                 int r, user_len_p1;
1757
1758                                 md5_passwd++;
1759                                 user_len_p1 = md5_passwd - cur->after_colon;
1760                                 /* comparing "user:" */
1761                                 if (strncmp(cur->after_colon, user_and_passwd, user_len_p1) != 0) {
1762                                         continue;
1763                                 }
1764
1765                                 encrypted = pw_encrypt(
1766                                         user_and_passwd + user_len_p1 /* cleartext pwd from user */,
1767                                         md5_passwd /*salt */, 1 /* cleanup */);
1768                                 r = strcmp(encrypted, md5_passwd);
1769                                 free(encrypted);
1770                                 if (r == 0)
1771                                         goto set_remoteuser_var; /* Ok */
1772                                 continue;
1773                         }
1774                 }
1775
1776                 /* Comparing plaintext "user:pass" in one go */
1777                 if (strcmp(cur->after_colon, user_and_passwd) == 0) {
1778  set_remoteuser_var:
1779                         remoteuser = xstrndup(user_and_passwd,
1780                                         strchrnul(user_and_passwd, ':') - user_and_passwd);
1781                         return 1; /* Ok */
1782                 }
1783         } /* for */
1784
1785         /* 0(bad) if prev is set: matches were found but passwd was wrong */
1786         return (prev == NULL);
1787 }
1788 #endif  /* FEATURE_HTTPD_BASIC_AUTH */
1789
1790 #if ENABLE_FEATURE_HTTPD_PROXY
1791 static Htaccess_Proxy *find_proxy_entry(const char *url)
1792 {
1793         Htaccess_Proxy *p;
1794         for (p = proxy; p; p = p->next) {
1795                 if (strncmp(url, p->url_from, strlen(p->url_from)) == 0)
1796                         return p;
1797         }
1798         return NULL;
1799 }
1800 #endif
1801
1802 /*
1803  * Handle timeouts
1804  */
1805 static void send_REQUEST_TIMEOUT_and_exit(int sig) NORETURN;
1806 static void send_REQUEST_TIMEOUT_and_exit(int sig UNUSED_PARAM)
1807 {
1808         send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
1809 }
1810
1811 /*
1812  * Handle an incoming http request and exit.
1813  */
1814 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr) NORETURN;
1815 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
1816 {
1817         static const char request_GET[] ALIGN1 = "GET";
1818         struct stat sb;
1819         char *urlcopy;
1820         char *urlp;
1821         char *tptr;
1822 #if ENABLE_FEATURE_HTTPD_CGI
1823         static const char request_HEAD[] ALIGN1 = "HEAD";
1824         const char *prequest;
1825         char *cookie = NULL;
1826         char *content_type = NULL;
1827         unsigned long length = 0;
1828 #elif ENABLE_FEATURE_HTTPD_PROXY
1829 #define prequest request_GET
1830         unsigned long length = 0;
1831 #endif
1832 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1833         smallint authorized = -1;
1834 #endif
1835         smallint ip_allowed;
1836         char http_major_version;
1837 #if ENABLE_FEATURE_HTTPD_PROXY
1838         char http_minor_version;
1839         char *header_buf = header_buf; /* for gcc */
1840         char *header_ptr = header_ptr;
1841         Htaccess_Proxy *proxy_entry;
1842 #endif
1843
1844         /* Allocation of iobuf is postponed until now
1845          * (IOW, server process doesn't need to waste 8k) */
1846         iobuf = xmalloc(IOBUF_SIZE);
1847
1848         rmt_ip = 0;
1849         if (fromAddr->u.sa.sa_family == AF_INET) {
1850                 rmt_ip = ntohl(fromAddr->u.sin.sin_addr.s_addr);
1851         }
1852 #if ENABLE_FEATURE_IPV6
1853         if (fromAddr->u.sa.sa_family == AF_INET6
1854          && fromAddr->u.sin6.sin6_addr.s6_addr32[0] == 0
1855          && fromAddr->u.sin6.sin6_addr.s6_addr32[1] == 0
1856          && ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[2]) == 0xffff)
1857                 rmt_ip = ntohl(fromAddr->u.sin6.sin6_addr.s6_addr32[3]);
1858 #endif
1859         if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1860                 /* NB: can be NULL (user runs httpd -i by hand?) */
1861                 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr->u.sa);
1862         }
1863         if (verbose) {
1864                 /* this trick makes -v logging much simpler */
1865                 if (rmt_ip_str)
1866                         applet_name = rmt_ip_str;
1867                 if (verbose > 2)
1868                         bb_error_msg("connected");
1869         }
1870
1871         /* Install timeout handler. get_line() needs it. */
1872         signal(SIGALRM, send_REQUEST_TIMEOUT_and_exit);
1873
1874         if (!get_line()) /* EOF or error or empty line */
1875                 send_headers_and_exit(HTTP_BAD_REQUEST);
1876
1877         /* Determine type of request (GET/POST) */
1878         urlp = strpbrk(iobuf, " \t");
1879         if (urlp == NULL)
1880                 send_headers_and_exit(HTTP_BAD_REQUEST);
1881         *urlp++ = '\0';
1882 #if ENABLE_FEATURE_HTTPD_CGI
1883         prequest = request_GET;
1884         if (strcasecmp(iobuf, prequest) != 0) {
1885                 prequest = request_HEAD;
1886                 if (strcasecmp(iobuf, prequest) != 0) {
1887                         prequest = "POST";
1888                         if (strcasecmp(iobuf, prequest) != 0)
1889                                 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1890                 }
1891         }
1892 #else
1893         if (strcasecmp(iobuf, request_GET) != 0)
1894                 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1895 #endif
1896         urlp = skip_whitespace(urlp);
1897         if (urlp[0] != '/')
1898                 send_headers_and_exit(HTTP_BAD_REQUEST);
1899
1900         /* Find end of URL and parse HTTP version, if any */
1901         http_major_version = '0';
1902         IF_FEATURE_HTTPD_PROXY(http_minor_version = '0';)
1903         tptr = strchrnul(urlp, ' ');
1904         /* Is it " HTTP/"? */
1905         if (tptr[0] && strncmp(tptr + 1, HTTP_200, 5) == 0) {
1906                 http_major_version = tptr[6];
1907                 IF_FEATURE_HTTPD_PROXY(http_minor_version = tptr[8];)
1908         }
1909         *tptr = '\0';
1910
1911         /* Copy URL from after "GET "/"POST " to stack-allocated char[] */
1912         urlcopy = alloca((tptr - urlp) + 2 + strlen(index_page));
1913         /*if (urlcopy == NULL)
1914          *      send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);*/
1915         strcpy(urlcopy, urlp);
1916         /* NB: urlcopy ptr is never changed after this */
1917
1918         /* Extract url args if present */
1919         g_query = NULL;
1920         tptr = strchr(urlcopy, '?');
1921         if (tptr) {
1922                 *tptr++ = '\0';
1923                 g_query = tptr;
1924         }
1925
1926         /* Decode URL escape sequences */
1927         tptr = decodeString(urlcopy, 0);
1928         if (tptr == NULL)
1929                 send_headers_and_exit(HTTP_BAD_REQUEST);
1930         if (tptr == urlcopy + 1) {
1931                 /* '/' or NUL is encoded */
1932                 send_headers_and_exit(HTTP_NOT_FOUND);
1933         }
1934
1935         /* Canonicalize path */
1936         /* Algorithm stolen from libbb bb_simplify_path(),
1937          * but don't strdup, retain trailing slash, protect root */
1938         urlp = tptr = urlcopy;
1939         do {
1940                 if (*urlp == '/') {
1941                         /* skip duplicate (or initial) slash */
1942                         if (*tptr == '/') {
1943                                 continue;
1944                         }
1945                         if (*tptr == '.') {
1946                                 /* skip extra "/./" */
1947                                 if (tptr[1] == '/' || !tptr[1]) {
1948                                         continue;
1949                                 }
1950                                 /* "..": be careful */
1951                                 if (tptr[1] == '.' && (tptr[2] == '/' || !tptr[2])) {
1952                                         ++tptr;
1953                                         if (urlp == urlcopy) /* protect root */
1954                                                 send_headers_and_exit(HTTP_BAD_REQUEST);
1955                                         while (*--urlp != '/') /* omit previous dir */;
1956                                                 continue;
1957                                 }
1958                         }
1959                 }
1960                 *++urlp = *tptr;
1961         } while (*++tptr);
1962         *++urlp = '\0';       /* terminate after last character */
1963
1964         /* If URL is a directory, add '/' */
1965         if (urlp[-1] != '/') {
1966                 if (is_directory(urlcopy + 1, 1, NULL)) {
1967                         found_moved_temporarily = urlcopy;
1968                 }
1969         }
1970
1971         /* Log it */
1972         if (verbose > 1)
1973                 bb_error_msg("url:%s", urlcopy);
1974
1975         tptr = urlcopy;
1976         ip_allowed = checkPermIP();
1977         while (ip_allowed && (tptr = strchr(tptr + 1, '/')) != NULL) {
1978                 /* have path1/path2 */
1979                 *tptr = '\0';
1980                 if (is_directory(urlcopy + 1, 1, NULL)) {
1981                         /* may have subdir config */
1982                         parse_conf(urlcopy + 1, SUBDIR_PARSE);
1983                         ip_allowed = checkPermIP();
1984                 }
1985                 *tptr = '/';
1986         }
1987
1988 #if ENABLE_FEATURE_HTTPD_PROXY
1989         proxy_entry = find_proxy_entry(urlcopy);
1990         if (proxy_entry)
1991                 header_buf = header_ptr = xmalloc(IOBUF_SIZE);
1992 #endif
1993
1994         if (http_major_version >= '0') {
1995                 /* Request was with "... HTTP/nXXX", and n >= 0 */
1996
1997                 /* Read until blank line */
1998                 while (1) {
1999                         if (!get_line())
2000                                 break; /* EOF or error or empty line */
2001                         if (DEBUG)
2002                                 bb_error_msg("header: '%s'", iobuf);
2003
2004 #if ENABLE_FEATURE_HTTPD_PROXY
2005                         /* We need 2 more bytes for yet another "\r\n" -
2006                          * see near fdprintf(proxy_fd...) further below */
2007                         if (proxy_entry && (header_ptr - header_buf) < IOBUF_SIZE - 2) {
2008                                 int len = strlen(iobuf);
2009                                 if (len > IOBUF_SIZE - (header_ptr - header_buf) - 4)
2010                                         len = IOBUF_SIZE - (header_ptr - header_buf) - 4;
2011                                 memcpy(header_ptr, iobuf, len);
2012                                 header_ptr += len;
2013                                 header_ptr[0] = '\r';
2014                                 header_ptr[1] = '\n';
2015                                 header_ptr += 2;
2016                         }
2017 #endif
2018
2019 #if ENABLE_FEATURE_HTTPD_CGI || ENABLE_FEATURE_HTTPD_PROXY
2020                         /* Try and do our best to parse more lines */
2021                         if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
2022                                 /* extra read only for POST */
2023                                 if (prequest != request_GET
2024 # if ENABLE_FEATURE_HTTPD_CGI
2025                                  && prequest != request_HEAD
2026 # endif
2027                                 ) {
2028                                         tptr = skip_whitespace(iobuf + sizeof("Content-length:") - 1);
2029                                         if (!tptr[0])
2030                                                 send_headers_and_exit(HTTP_BAD_REQUEST);
2031                                         /* not using strtoul: it ignores leading minus! */
2032                                         length = bb_strtou(tptr, NULL, 10);
2033                                         /* length is "ulong", but we need to pass it to int later */
2034                                         if (errno || length > INT_MAX)
2035                                                 send_headers_and_exit(HTTP_BAD_REQUEST);
2036                                 }
2037                         }
2038 #endif
2039 #if ENABLE_FEATURE_HTTPD_CGI
2040                         else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
2041                                 cookie = xstrdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
2042                         } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
2043                                 content_type = xstrdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
2044                         } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
2045                                 referer = xstrdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
2046                         } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
2047                                 user_agent = xstrdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
2048                         } else if (STRNCASECMP(iobuf, "Host:") == 0) {
2049                                 host = xstrdup(skip_whitespace(iobuf + sizeof("Host:")-1));
2050                         } else if (STRNCASECMP(iobuf, "Accept:") == 0) {
2051                                 http_accept = xstrdup(skip_whitespace(iobuf + sizeof("Accept:")-1));
2052                         } else if (STRNCASECMP(iobuf, "Accept-Language:") == 0) {
2053                                 http_accept_language = xstrdup(skip_whitespace(iobuf + sizeof("Accept-Language:")-1));
2054                         }
2055 #endif
2056 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
2057                         if (STRNCASECMP(iobuf, "Authorization:") == 0) {
2058                                 /* We only allow Basic credentials.
2059                                  * It shows up as "Authorization: Basic <user>:<passwd>" where
2060                                  * "<user>:<passwd>" is base64 encoded.
2061                                  */
2062                                 tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
2063                                 if (STRNCASECMP(tptr, "Basic") != 0)
2064                                         continue;
2065                                 tptr += sizeof("Basic")-1;
2066                                 /* decodeBase64() skips whitespace itself */
2067                                 decodeBase64(tptr);
2068                                 authorized = check_user_passwd(urlcopy, tptr);
2069                         }
2070 #endif
2071 #if ENABLE_FEATURE_HTTPD_RANGES
2072                         if (STRNCASECMP(iobuf, "Range:") == 0) {
2073                                 /* We know only bytes=NNN-[MMM] */
2074                                 char *s = skip_whitespace(iobuf + sizeof("Range:")-1);
2075                                 if (strncmp(s, "bytes=", 6) == 0) {
2076                                         s += sizeof("bytes=")-1;
2077                                         range_start = BB_STRTOOFF(s, &s, 10);
2078                                         if (s[0] != '-' || range_start < 0) {
2079                                                 range_start = 0;
2080                                         } else if (s[1]) {
2081                                                 range_end = BB_STRTOOFF(s+1, NULL, 10);
2082                                                 if (errno || range_end < range_start)
2083                                                         range_start = 0;
2084                                         }
2085                                 }
2086                         }
2087 #endif
2088 #if ENABLE_FEATURE_HTTPD_GZIP
2089                         if (STRNCASECMP(iobuf, "Accept-Encoding:") == 0) {
2090                                 /* Note: we do not support "gzip;q=0"
2091                                  * method of _disabling_ gzip
2092                                  * delivery. No one uses that, though */
2093                                 const char *s = strstr(iobuf, "gzip");
2094                                 if (s) {
2095                                         // want more thorough checks?
2096                                         //if (s[-1] == ' '
2097                                         // || s[-1] == ','
2098                                         // || s[-1] == ':'
2099                                         //) {
2100                                                 content_gzip = 1;
2101                                         //}
2102                                 }
2103                         }
2104 #endif
2105                 } /* while extra header reading */
2106         }
2107
2108         /* We are done reading headers, disable peer timeout */
2109         alarm(0);
2110
2111         if (strcmp(bb_basename(urlcopy), HTTPD_CONF) == 0 || !ip_allowed) {
2112                 /* protect listing [/path]/httpd.conf or IP deny */
2113                 send_headers_and_exit(HTTP_FORBIDDEN);
2114         }
2115
2116 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
2117         /* Case: no "Authorization:" was seen, but page does require passwd.
2118          * Check that with dummy user:pass */
2119         if (authorized < 0)
2120                 authorized = check_user_passwd(urlcopy, ":");
2121         if (!authorized)
2122                 send_headers_and_exit(HTTP_UNAUTHORIZED);
2123 #endif
2124
2125         if (found_moved_temporarily) {
2126                 send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
2127         }
2128
2129 #if ENABLE_FEATURE_HTTPD_PROXY
2130         if (proxy_entry != NULL) {
2131                 int proxy_fd;
2132                 len_and_sockaddr *lsa;
2133
2134                 proxy_fd = socket(AF_INET, SOCK_STREAM, 0);
2135                 if (proxy_fd < 0)
2136                         send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
2137                 lsa = host2sockaddr(proxy_entry->host_port, 80);
2138                 if (lsa == NULL)
2139                         send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
2140                 if (connect(proxy_fd, &lsa->u.sa, lsa->len) < 0)
2141                         send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);
2142                 fdprintf(proxy_fd, "%s %s%s%s%s HTTP/%c.%c\r\n",
2143                                 prequest, /* GET or POST */
2144                                 proxy_entry->url_to, /* url part 1 */
2145                                 urlcopy + strlen(proxy_entry->url_from), /* url part 2 */
2146                                 (g_query ? "?" : ""), /* "?" (maybe) */
2147                                 (g_query ? g_query : ""), /* query string (maybe) */
2148                                 http_major_version, http_minor_version);
2149                 header_ptr[0] = '\r';
2150                 header_ptr[1] = '\n';
2151                 header_ptr += 2;
2152                 write(proxy_fd, header_buf, header_ptr - header_buf);
2153                 free(header_buf); /* on the order of 8k, free it */
2154                 cgi_io_loop_and_exit(proxy_fd, proxy_fd, length);
2155         }
2156 #endif
2157
2158         tptr = urlcopy + 1;      /* skip first '/' */
2159
2160 #if ENABLE_FEATURE_HTTPD_CGI
2161         if (strncmp(tptr, "cgi-bin/", 8) == 0) {
2162                 if (tptr[8] == '\0') {
2163                         /* protect listing "cgi-bin/" */
2164                         send_headers_and_exit(HTTP_FORBIDDEN);
2165                 }
2166                 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
2167         }
2168 #endif
2169
2170         if (urlp[-1] == '/')
2171                 strcpy(urlp, index_page);
2172         if (stat(tptr, &sb) == 0) {
2173 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
2174                 char *suffix = strrchr(tptr, '.');
2175                 if (suffix) {
2176                         Htaccess *cur;
2177                         for (cur = script_i; cur; cur = cur->next) {
2178                                 if (strcmp(cur->before_colon + 1, suffix) == 0) {
2179                                         send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
2180                                 }
2181                         }
2182                 }
2183 #endif
2184                 file_size = sb.st_size;
2185                 last_mod = sb.st_mtime;
2186         }
2187 #if ENABLE_FEATURE_HTTPD_CGI
2188         else if (urlp[-1] == '/') {
2189                 /* It's a dir URL and there is no index.html
2190                  * Try cgi-bin/index.cgi */
2191                 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
2192                         urlp[0] = '\0';
2193                         g_query = urlcopy;
2194                         send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
2195                 }
2196         }
2197         /* else fall through to send_file, it errors out if open fails: */
2198
2199         if (prequest != request_GET && prequest != request_HEAD) {
2200                 /* POST for files does not make sense */
2201                 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
2202         }
2203         send_file_and_exit(tptr,
2204                 (prequest != request_HEAD ? SEND_HEADERS_AND_BODY : SEND_HEADERS)
2205         );
2206 #else
2207         send_file_and_exit(tptr, SEND_HEADERS_AND_BODY);
2208 #endif
2209 }
2210
2211 /*
2212  * The main http server function.
2213  * Given a socket, listen for new connections and farm out
2214  * the processing as a [v]forked process.
2215  * Never returns.
2216  */
2217 #if BB_MMU
2218 static void mini_httpd(int server_socket) NORETURN;
2219 static void mini_httpd(int server_socket)
2220 {
2221         /* NB: it's best to not use xfuncs in this loop before fork().
2222          * Otherwise server may die on transient errors (temporary
2223          * out-of-memory condition, etc), which is Bad(tm).
2224          * Try to do any dangerous calls after fork.
2225          */
2226         while (1) {
2227                 int n;
2228                 len_and_sockaddr fromAddr;
2229
2230                 /* Wait for connections... */
2231                 fromAddr.len = LSA_SIZEOF_SA;
2232                 n = accept(server_socket, &fromAddr.u.sa, &fromAddr.len);
2233                 if (n < 0)
2234                         continue;
2235
2236                 /* set the KEEPALIVE option to cull dead connections */
2237                 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
2238
2239                 if (fork() == 0) {
2240                         /* child */
2241                         /* Do not reload config on HUP */
2242                         signal(SIGHUP, SIG_IGN);
2243                         close(server_socket);
2244                         xmove_fd(n, 0);
2245                         xdup2(0, 1);
2246
2247                         handle_incoming_and_exit(&fromAddr);
2248                 }
2249                 /* parent, or fork failed */
2250                 close(n);
2251         } /* while (1) */
2252         /* never reached */
2253 }
2254 #else
2255 static void mini_httpd_nommu(int server_socket, int argc, char **argv) NORETURN;
2256 static void mini_httpd_nommu(int server_socket, int argc, char **argv)
2257 {
2258         char *argv_copy[argc + 2];
2259
2260         argv_copy[0] = argv[0];
2261         argv_copy[1] = (char*)"-i";
2262         memcpy(&argv_copy[2], &argv[1], argc * sizeof(argv[0]));
2263
2264         /* NB: it's best to not use xfuncs in this loop before vfork().
2265          * Otherwise server may die on transient errors (temporary
2266          * out-of-memory condition, etc), which is Bad(tm).
2267          * Try to do any dangerous calls after fork.
2268          */
2269         while (1) {
2270                 int n;
2271                 len_and_sockaddr fromAddr;
2272
2273                 /* Wait for connections... */
2274                 fromAddr.len = LSA_SIZEOF_SA;
2275                 n = accept(server_socket, &fromAddr.u.sa, &fromAddr.len);
2276                 if (n < 0)
2277                         continue;
2278
2279                 /* set the KEEPALIVE option to cull dead connections */
2280                 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
2281
2282                 if (vfork() == 0) {
2283                         /* child */
2284                         /* Do not reload config on HUP */
2285                         signal(SIGHUP, SIG_IGN);
2286                         close(server_socket);
2287                         xmove_fd(n, 0);
2288                         xdup2(0, 1);
2289
2290                         /* Run a copy of ourself in inetd mode */
2291                         re_exec(argv_copy);
2292                 }
2293                 /* parent, or vfork failed */
2294                 close(n);
2295         } /* while (1) */
2296         /* never reached */
2297 }
2298 #endif
2299
2300 /*
2301  * Process a HTTP connection on stdin/out.
2302  * Never returns.
2303  */
2304 static void mini_httpd_inetd(void) NORETURN;
2305 static void mini_httpd_inetd(void)
2306 {
2307         len_and_sockaddr fromAddr;
2308
2309         memset(&fromAddr, 0, sizeof(fromAddr));
2310         fromAddr.len = LSA_SIZEOF_SA;
2311         /* NB: can fail if user runs it by hand and types in http cmds */
2312         getpeername(0, &fromAddr.u.sa, &fromAddr.len);
2313         handle_incoming_and_exit(&fromAddr);
2314 }
2315
2316 static void sighup_handler(int sig UNUSED_PARAM)
2317 {
2318         parse_conf(DEFAULT_PATH_HTTPD_CONF, SIGNALED_PARSE);
2319 }
2320
2321 enum {
2322         c_opt_config_file = 0,
2323         d_opt_decode_url,
2324         h_opt_home_httpd,
2325         IF_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
2326         IF_FEATURE_HTTPD_BASIC_AUTH(    r_opt_realm     ,)
2327         IF_FEATURE_HTTPD_AUTH_MD5(      m_opt_md5       ,)
2328         IF_FEATURE_HTTPD_SETUID(        u_opt_setuid    ,)
2329         p_opt_port      ,
2330         p_opt_inetd     ,
2331         p_opt_foreground,
2332         p_opt_verbose   ,
2333         OPT_CONFIG_FILE = 1 << c_opt_config_file,
2334         OPT_DECODE_URL  = 1 << d_opt_decode_url,
2335         OPT_HOME_HTTPD  = 1 << h_opt_home_httpd,
2336         OPT_ENCODE_URL  = IF_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
2337         OPT_REALM       = IF_FEATURE_HTTPD_BASIC_AUTH(    (1 << r_opt_realm     )) + 0,
2338         OPT_MD5         = IF_FEATURE_HTTPD_AUTH_MD5(      (1 << m_opt_md5       )) + 0,
2339         OPT_SETUID      = IF_FEATURE_HTTPD_SETUID(        (1 << u_opt_setuid    )) + 0,
2340         OPT_PORT        = 1 << p_opt_port,
2341         OPT_INETD       = 1 << p_opt_inetd,
2342         OPT_FOREGROUND  = 1 << p_opt_foreground,
2343         OPT_VERBOSE     = 1 << p_opt_verbose,
2344 };
2345
2346
2347 int httpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
2348 int httpd_main(int argc UNUSED_PARAM, char **argv)
2349 {
2350         int server_socket = server_socket; /* for gcc */
2351         unsigned opt;
2352         char *url_for_decode;
2353         IF_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
2354         IF_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
2355         IF_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
2356         IF_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
2357
2358         INIT_G();
2359
2360 #if ENABLE_LOCALE_SUPPORT
2361         /* Undo busybox.c: we want to speak English in http (dates etc) */
2362         setlocale(LC_TIME, "C");
2363 #endif
2364
2365         home_httpd = xrealloc_getcwd_or_warn(NULL);
2366         /* -v counts, -i implies -f */
2367         opt_complementary = "vv:if";
2368         /* We do not "absolutize" path given by -h (home) opt.
2369          * If user gives relative path in -h,
2370          * $SCRIPT_FILENAME will not be set. */
2371         opt = getopt32(argv, "c:d:h:"
2372                         IF_FEATURE_HTTPD_ENCODE_URL_STR("e:")
2373                         IF_FEATURE_HTTPD_BASIC_AUTH("r:")
2374                         IF_FEATURE_HTTPD_AUTH_MD5("m:")
2375                         IF_FEATURE_HTTPD_SETUID("u:")
2376                         "p:ifv",
2377                         &opt_c_configFile, &url_for_decode, &home_httpd
2378                         IF_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
2379                         IF_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
2380                         IF_FEATURE_HTTPD_AUTH_MD5(, &pass)
2381                         IF_FEATURE_HTTPD_SETUID(, &s_ugid)
2382                         , &bind_addr_or_port
2383                         , &verbose
2384                 );
2385         if (opt & OPT_DECODE_URL) {
2386                 fputs(decodeString(url_for_decode, 1), stdout);
2387                 return 0;
2388         }
2389 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
2390         if (opt & OPT_ENCODE_URL) {
2391                 fputs(encodeString(url_for_encode), stdout);
2392                 return 0;
2393         }
2394 #endif
2395 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
2396         if (opt & OPT_MD5) {
2397                 char salt[sizeof("$1$XXXXXXXX")];
2398                 salt[0] = '$';
2399                 salt[1] = '1';
2400                 salt[2] = '$';
2401                 crypt_make_salt(salt + 3, 4, 0);
2402                 puts(pw_encrypt(pass, salt, 1));
2403                 return 0;
2404         }
2405 #endif
2406 #if ENABLE_FEATURE_HTTPD_SETUID
2407         if (opt & OPT_SETUID) {
2408                 xget_uidgid(&ugid, s_ugid);
2409         }
2410 #endif
2411
2412 #if !BB_MMU
2413         if (!(opt & OPT_FOREGROUND)) {
2414                 bb_daemonize_or_rexec(0, argv); /* don't change current directory */
2415         }
2416 #endif
2417
2418         xchdir(home_httpd);
2419         if (!(opt & OPT_INETD)) {
2420                 signal(SIGCHLD, SIG_IGN);
2421                 server_socket = openServer();
2422 #if ENABLE_FEATURE_HTTPD_SETUID
2423                 /* drop privileges */
2424                 if (opt & OPT_SETUID) {
2425                         if (ugid.gid != (gid_t)-1) {
2426                                 if (setgroups(1, &ugid.gid) == -1)
2427                                         bb_perror_msg_and_die("setgroups");
2428                                 xsetgid(ugid.gid);
2429                         }
2430                         xsetuid(ugid.uid);
2431                 }
2432 #endif
2433         }
2434
2435 #if 0
2436         /* User can do it himself: 'env - PATH="$PATH" httpd'
2437          * We don't do it because we don't want to screw users
2438          * which want to do
2439          * 'env - VAR1=val1 VAR2=val2 httpd'
2440          * and have VAR1 and VAR2 values visible in their CGIs.
2441          * Besides, it is also smaller. */
2442         {
2443                 char *p = getenv("PATH");
2444                 /* env strings themself are not freed, no need to xstrdup(p): */
2445                 clearenv();
2446                 if (p)
2447                         putenv(p - 5);
2448 //              if (!(opt & OPT_INETD))
2449 //                      setenv_long("SERVER_PORT", ???);
2450         }
2451 #endif
2452
2453         parse_conf(DEFAULT_PATH_HTTPD_CONF, FIRST_PARSE);
2454         if (!(opt & OPT_INETD))
2455                 signal(SIGHUP, sighup_handler);
2456
2457         xfunc_error_retval = 0;
2458         if (opt & OPT_INETD)
2459                 mini_httpd_inetd();
2460 #if BB_MMU
2461         if (!(opt & OPT_FOREGROUND))
2462                 bb_daemonize(0); /* don't change current directory */
2463         mini_httpd(server_socket); /* never returns */
2464 #else
2465         mini_httpd_nommu(server_socket, argc, argv); /* never returns */
2466 #endif
2467         /* return 0; */
2468 }