httpd: add optional support for error pages
[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  * simplify patch stolen from libbb without using strdup
9  *
10  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
11  *
12  *****************************************************************************
13  *
14  * Typical usage:
15  *   for non root user
16  * httpd -p 8080 -h $HOME/public_html
17  *   or for daemon start from rc script with uid=0:
18  * httpd -u www
19  * This is equivalent if www user have uid=80 to
20  * httpd -p 80 -u 80 -h /www -c /etc/httpd.conf -r "Web Server Authentication"
21  *
22  *
23  * When a url starts by "/cgi-bin/" it is assumed to be a cgi script.  The
24  * server changes directory to the location of the script and executes it
25  * after setting QUERY_STRING and other environment variables.
26  *
27  * Doc:
28  * "CGI Environment Variables": http://hoohoo.ncsa.uiuc.edu/cgi/env.html
29  *
30  * The server can also be invoked as a url arg decoder and html text encoder
31  * as follows:
32  *  foo=`httpd -d $foo`           # decode "Hello%20World" as "Hello World"
33  *  bar=`httpd -e "<Hello World>"`  # encode as "&#60Hello&#32World&#62"
34  * Note that url encoding for arguments is not the same as html encoding for
35  * presentation.  -d decodes a url-encoded argument while -e encodes in html
36  * for page display.
37  *
38  * httpd.conf has the following format:
39  *
40  * A:172.20.         # Allow address from 172.20.0.0/16
41  * A:10.0.0.0/25     # Allow any address from 10.0.0.0-10.0.0.127
42  * A:10.0.0.0/255.255.255.128  # Allow any address that previous set
43  * A:127.0.0.1       # Allow local loopback connections
44  * D:*               # Deny from other IP connections
45  * E404:/path/e404.html # /path/e404.html is the 404 (not found) error page
46  * /cgi-bin:foo:bar  # Require user foo, pwd bar on urls starting with /cgi-bin/
47  * /adm:admin:setup  # Require user admin, pwd setup on urls starting with /adm/
48  * /adm:toor:PaSsWd  # or user toor, pwd PaSsWd on urls starting with /adm/
49  * .au:audio/basic   # additional mime type for audio.au files
50  * *.php:/path/php   # running cgi.php scripts through an interpreter
51  *
52  * A/D may be as a/d or allow/deny - first char case insensitive
53  * Deny IP rules take precedence over allow rules.
54  *
55  *
56  * The Deny/Allow IP logic:
57  *
58  *  - Default is to allow all.  No addresses are denied unless
59  *         denied with a D: rule.
60  *  - Order of Deny/Allow rules is significant
61  *  - Deny rules take precedence over allow rules.
62  *  - If a deny all rule (D:*) is used it acts as a catch-all for unmatched
63  *       addresses.
64  *  - Specification of Allow all (A:*) is a no-op
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 a 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
99 #include "libbb.h"
100 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
101 #include <sys/sendfile.h>
102 #endif
103
104 //#define DEBUG 1
105 #define DEBUG 0
106
107 /* amount of buffering in a pipe */
108 #ifndef PIPE_BUF
109 # define PIPE_BUF 4096
110 #endif
111
112 #define IOBUF_SIZE 8192    /* IO buffer */
113
114 #define HEADER_READ_TIMEOUT 60
115
116 static const char default_path_httpd_conf[] ALIGN1 = "/etc";
117 static const char httpd_conf[] ALIGN1 = "httpd.conf";
118 static const char HTTP_200[] ALIGN1 = "HTTP/1.0 200 OK\r\n";
119
120 typedef struct has_next_ptr {
121         struct has_next_ptr *next;
122 } has_next_ptr;
123
124 /* Must have "next" as a first member */
125 typedef struct Htaccess {
126         struct Htaccess *next;
127         char *after_colon;
128         char before_colon[1];  /* really bigger, must be last */
129 } Htaccess;
130
131 /* Must have "next" as a first member */
132 typedef struct Htaccess_IP {
133         struct Htaccess_IP *next;
134         unsigned ip;
135         unsigned mask;
136         int allow_deny;
137 } Htaccess_IP;
138
139 enum {
140         HTTP_OK = 200,
141         HTTP_MOVED_TEMPORARILY = 302,
142         HTTP_BAD_REQUEST = 400,       /* malformed syntax */
143         HTTP_UNAUTHORIZED = 401, /* authentication needed, respond with auth hdr */
144         HTTP_NOT_FOUND = 404,
145         HTTP_FORBIDDEN = 403,
146         HTTP_REQUEST_TIMEOUT = 408,
147         HTTP_NOT_IMPLEMENTED = 501,   /* used for unrecognized requests */
148         HTTP_INTERNAL_SERVER_ERROR = 500,
149         HTTP_CONTINUE = 100,
150 #if 0   /* future use */
151         HTTP_SWITCHING_PROTOCOLS = 101,
152         HTTP_CREATED = 201,
153         HTTP_ACCEPTED = 202,
154         HTTP_NON_AUTHORITATIVE_INFO = 203,
155         HTTP_NO_CONTENT = 204,
156         HTTP_MULTIPLE_CHOICES = 300,
157         HTTP_MOVED_PERMANENTLY = 301,
158         HTTP_NOT_MODIFIED = 304,
159         HTTP_PAYMENT_REQUIRED = 402,
160         HTTP_BAD_GATEWAY = 502,
161         HTTP_SERVICE_UNAVAILABLE = 503, /* overload, maintenance */
162         HTTP_RESPONSE_SETSIZE = 0xffffffff
163 #endif
164 };
165
166 static const uint16_t http_response_type[] = {
167         HTTP_OK,
168         HTTP_MOVED_TEMPORARILY,
169         HTTP_REQUEST_TIMEOUT,
170         HTTP_NOT_IMPLEMENTED,
171 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH 
172         HTTP_UNAUTHORIZED,
173 #endif
174         HTTP_NOT_FOUND,
175         HTTP_BAD_REQUEST,
176         HTTP_FORBIDDEN,
177         HTTP_INTERNAL_SERVER_ERROR,
178 #if 0   /* not implemented */
179         HTTP_CREATED,
180         HTTP_ACCEPTED,
181         HTTP_NO_CONTENT,
182         HTTP_MULTIPLE_CHOICES,
183         HTTP_MOVED_PERMANENTLY,
184         HTTP_NOT_MODIFIED,
185         HTTP_BAD_GATEWAY,
186         HTTP_SERVICE_UNAVAILABLE,
187 #endif
188 };
189
190 static const struct {
191         const char *name;
192         const char *info;
193 } http_response[ARRAY_SIZE(http_response_type)] = {
194         { "OK", NULL },
195         { "Found", "Directories must end with a slash" }, /* ?? */
196         { "Request Timeout", "No request appeared within 60 seconds" },
197         { "Not Implemented", "The requested method is not recognized" },
198 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
199         { "Unauthorized", "" },
200 #endif
201         { "Not Found", "The requested URL was not found" },
202         { "Bad Request", "Unsupported method" },
203         { "Forbidden", ""  },
204         { "Internal Server Error", "Internal Server Error" },
205 #if 0   /* not implemented */
206         { "Created" },
207         { "Accepted" },
208         { "No Content" },
209         { "Multiple Choices" },
210         { "Moved Permanently" },
211         { "Not Modified" },
212         { "Bad Gateway", "" },
213         { "Service Unavailable", "" },
214 #endif
215 };
216
217 struct globals {
218         int verbose;            /* must be int (used by getopt32) */
219         smallint flg_deny_all;
220
221         unsigned rmt_ip;        /* used for IP-based allow/deny rules */
222         time_t last_mod;
223         off_t ContentLength;    /* -1 - unknown */
224         char *rmt_ip_str;       /* for $REMOTE_ADDR and $REMOTE_PORT */
225         const char *bind_addr_or_port;
226
227         const char *g_query;
228         const char *configFile;
229         const char *home_httpd;
230
231         const char *found_mime_type;
232         const char *found_moved_temporarily;
233         Htaccess_IP *ip_a_d;    /* config allow/deny lines */
234
235         USE_FEATURE_HTTPD_BASIC_AUTH(const char *g_realm;)
236         USE_FEATURE_HTTPD_BASIC_AUTH(char *remoteuser;)
237         USE_FEATURE_HTTPD_CGI(char *referer;)
238         USE_FEATURE_HTTPD_CGI(char *user_agent;)
239
240 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
241         Htaccess *g_auth;       /* config user:password lines */
242 #endif
243 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
244         Htaccess *mime_a;       /* config mime types */
245 #endif
246 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
247         Htaccess *script_i;     /* config script interpreters */
248 #endif
249         char *iobuf;            /* [IOBUF_SIZE] */
250 #define hdr_buf bb_common_bufsiz1
251         char *hdr_ptr;
252         int hdr_cnt;
253 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
254         const char *http_error_page[ARRAY_SIZE(http_response_type)];
255 #endif
256 };
257 #define G (*ptr_to_globals)
258 #define verbose           (G.verbose          )
259 #define flg_deny_all      (G.flg_deny_all     )
260 #define rmt_ip            (G.rmt_ip           )
261 #define bind_addr_or_port (G.bind_addr_or_port)
262 #define g_query           (G.g_query          )
263 #define configFile        (G.configFile       )
264 #define home_httpd        (G.home_httpd       )
265 #define found_mime_type   (G.found_mime_type  )
266 #define found_moved_temporarily (G.found_moved_temporarily)
267 #define ContentLength     (G.ContentLength    )
268 #define last_mod          (G.last_mod         )
269 #define ip_a_d            (G.ip_a_d           )
270 #define g_realm           (G.g_realm          )
271 #define remoteuser        (G.remoteuser       )
272 #define referer           (G.referer          )
273 #define user_agent        (G.user_agent       )
274 #define rmt_ip_str        (G.rmt_ip_str       )
275 #define g_auth            (G.g_auth           )
276 #define mime_a            (G.mime_a           )
277 #define script_i          (G.script_i         )
278 #define iobuf             (G.iobuf            )
279 #define hdr_ptr           (G.hdr_ptr          )
280 #define hdr_cnt           (G.hdr_cnt          )
281 #define http_error_page   (G.http_error_page  )
282 #define INIT_G() do { \
283         PTR_TO_GLOBALS = xzalloc(sizeof(G)); \
284         USE_FEATURE_HTTPD_BASIC_AUTH(g_realm = "Web Server Authentication";) \
285         bind_addr_or_port = "80"; \
286         ContentLength = -1; \
287 } while (0)
288
289
290
291
292 #define STRNCASECMP(a, str) strncasecmp((a), (str), sizeof(str)-1)
293
294 /* Prototypes */
295 static void send_file_and_exit(const char *url, int headers) ATTRIBUTE_NORETURN;
296
297 static void free_llist(has_next_ptr **pptr)
298 {
299         has_next_ptr *cur = *pptr;
300         while (cur) {
301                 has_next_ptr *t = cur;
302                 cur = cur->next;
303                 free(t);
304         }
305         *pptr = NULL;
306 }
307
308 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
309  || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
310  || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
311 static ALWAYS_INLINE void free_Htaccess_list(Htaccess **pptr)
312 {
313         free_llist((has_next_ptr**)pptr);
314 }
315 #endif
316
317 static ALWAYS_INLINE void free_Htaccess_IP_list(Htaccess_IP **pptr)
318 {
319         free_llist((has_next_ptr**)pptr);
320 }
321
322 /* Returns presumed mask width in bits or < 0 on error.
323  * Updates strp, stores IP at provided pointer */
324 static int scan_ip(const char **strp, unsigned *ipp, unsigned char endc)
325 {
326         const char *p = *strp;
327         int auto_mask = 8;
328         unsigned ip = 0;
329         int j;
330
331         if (*p == '/')
332                 return -auto_mask;
333
334         for (j = 0; j < 4; j++) {
335                 unsigned octet;
336
337                 if ((*p < '0' || *p > '9') && *p != '/' && *p)
338                         return -auto_mask;
339                 octet = 0;
340                 while (*p >= '0' && *p <= '9') {
341                         octet *= 10;
342                         octet += *p - '0';
343                         if (octet > 255)
344                                 return -auto_mask;
345                         p++;
346                 }
347                 if (*p == '.')
348                         p++;
349                 if (*p != '/' && *p)
350                         auto_mask += 8;
351                 ip = (ip << 8) | octet;
352         }
353         if (*p) {
354                 if (*p != endc)
355                         return -auto_mask;
356                 p++;
357                 if (*p == '\0')
358                         return -auto_mask;
359         }
360         *ipp = ip;
361         *strp = p;
362         return auto_mask;
363 }
364
365 /* Returns 0 on success. Stores IP and mask at provided pointers */
366 static int scan_ip_mask(const char *str, unsigned *ipp, unsigned *maskp)
367 {
368         int i;
369         unsigned mask;
370         char *p;
371
372         i = scan_ip(&str, ipp, '/');
373         if (i < 0)
374                 return i;
375
376         if (*str) {
377                 /* there is /xxx after dotted-IP address */
378                 i = bb_strtou(str, &p, 10);
379                 if (*p == '.') {
380                         /* 'xxx' itself is dotted-IP mask, parse it */
381                         /* (return 0 (success) only if it has N.N.N.N form) */
382                         return scan_ip(&str, maskp, '\0') - 32;
383                 }
384                 if (*p)
385                         return -1;
386         }
387
388         if (i > 32)
389                 return -1;
390
391         if (sizeof(unsigned) == 4 && i == 32) {
392                 /* mask >>= 32 below may not work */
393                 mask = 0;
394         } else {
395                 mask = 0xffffffff;
396                 mask >>= i;
397         }
398         /* i == 0 -> *maskp = 0x00000000
399          * i == 1 -> *maskp = 0x80000000
400          * i == 4 -> *maskp = 0xf0000000
401          * i == 31 -> *maskp = 0xfffffffe
402          * i == 32 -> *maskp = 0xffffffff */
403         *maskp = (uint32_t)(~mask);
404         return 0;
405 }
406
407 /*
408  * Parse configuration file into in-memory linked list.
409  *
410  * The first non-white character is examined to determine if the config line
411  * is one of the following:
412  *    .ext:mime/type   # new mime type not compiled into httpd
413  *    [adAD]:from      # ip address allow/deny, * for wildcard
414  *    /path:user:pass  # username/password
415  *    Ennn:error.html  # error page for status nnn
416  *
417  * Any previous IP rules are discarded.
418  * If the flag argument is not SUBDIR_PARSE then all /path and mime rules
419  * are also discarded.  That is, previous settings are retained if flag is
420  * SUBDIR_PARSE.
421  * Error pages are only parsed on the main config file.
422  *
423  * path   Path where to look for httpd.conf (without filename).
424  * flag   Type of the parse request.
425  */
426 /* flag */
427 #define FIRST_PARSE          0
428 #define SUBDIR_PARSE         1
429 #define SIGNALED_PARSE       2
430 #define FIND_FROM_HTTPD_ROOT 3
431 static void parse_conf(const char *path, int flag)
432 {
433         FILE *f;
434 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
435         Htaccess *prev;
436 #endif
437 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
438  || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
439  || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
440         Htaccess *cur;
441 #endif
442         const char *cf = configFile;
443         char buf[160];
444         char *p0 = NULL;
445         char *c, *p;
446         Htaccess_IP *pip;
447
448         /* discard old rules */
449         free_Htaccess_IP_list(&ip_a_d);
450         flg_deny_all = 0;
451 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
452  || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
453  || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
454         /* retain previous auth and mime config only for subdir parse */
455         if (flag != SUBDIR_PARSE) {
456 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
457                 free_Htaccess_list(&g_auth);
458 #endif
459 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
460                 free_Htaccess_list(&mime_a);
461 #endif
462 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
463                 free_Htaccess_list(&script_i);
464 #endif
465         }
466 #endif
467
468         if (flag == SUBDIR_PARSE || cf == NULL) {
469                 cf = alloca(strlen(path) + sizeof(httpd_conf) + 2);
470                 if (cf == NULL) {
471                         if (flag == FIRST_PARSE)
472                                 bb_error_msg_and_die(bb_msg_memory_exhausted);
473                         return;
474                 }
475                 sprintf((char *)cf, "%s/%s", path, httpd_conf);
476         }
477
478         while ((f = fopen(cf, "r")) == NULL) {
479                 if (flag == SUBDIR_PARSE || flag == FIND_FROM_HTTPD_ROOT) {
480                         /* config file not found, no changes to config */
481                         return;
482                 }
483                 if (configFile && flag == FIRST_PARSE) /* if -c option given */
484                         bb_perror_msg_and_die("%s", cf);
485                 flag = FIND_FROM_HTTPD_ROOT;
486                 cf = httpd_conf;
487         }
488
489 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
490         prev = g_auth;
491 #endif
492         /* This could stand some work */
493         while ((p0 = fgets(buf, sizeof(buf), f)) != NULL) {
494                 c = NULL;
495                 for (p = p0; *p0 != '\0' && *p0 != '#'; p0++) {
496                         if (!isspace(*p0)) {
497                                 *p++ = *p0;
498                                 if (*p0 == ':' && c == NULL)
499                                         c = p;
500                         }
501                 }
502                 *p = '\0';
503
504                 /* test for empty or strange line */
505                 if (c == NULL || *c == '\0')
506                         continue;
507                 p0 = buf;
508                 if (*p0 == 'd')
509                         *p0 = 'D';
510                 if (*c == '*') {
511                         if (*p0 == 'D') {
512                                 /* memorize deny all */
513                                 flg_deny_all = 1;
514                         }
515                         /* skip default other "word:*" config lines */
516                         continue;
517                 }
518
519                 if (*p0 == 'a')
520                         *p0 = 'A';
521                 if (*p0 == 'A' || *p0 == 'D') {
522                         /* storing current config IP line */
523                         pip = xzalloc(sizeof(Htaccess_IP));
524                         if (pip) {
525                                 if (scan_ip_mask(c, &(pip->ip), &(pip->mask))) {
526                                         /* syntax IP{/mask} error detected, protect all */
527                                         *p0 = 'D';
528                                         pip->mask = 0;
529                                 }
530                                 pip->allow_deny = *p0;
531                                 if (*p0 == 'D') {
532                                         /* Deny:from_IP move top */
533                                         pip->next = ip_a_d;
534                                         ip_a_d = pip;
535                                 } else {
536                                         /* add to bottom A:form_IP config line */
537                                         Htaccess_IP *prev_IP = ip_a_d;
538
539                                         if (prev_IP == NULL) {
540                                                 ip_a_d = pip;
541                                         } else {
542                                                 while (prev_IP->next)
543                                                         prev_IP = prev_IP->next;
544                                                 prev_IP->next = pip;
545                                         }
546                                 }
547                         }
548                         continue;
549                 }
550
551 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
552                 if (flag == FIRST_PARSE && *p0 == 'E') {
553                         int i;
554                         /* error status code */
555                         int status = atoi(++p0);
556                         /* c already points at the character following ':' in parse loop */
557                         // c = strchr(p0, ':'); c++;
558                         if (status < HTTP_CONTINUE) {
559                                 bb_error_msg("config error '%s' in '%s'", buf, cf);
560                                 continue;
561                         }
562
563                         /* then error page; find matching status */
564                         for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
565                                 if (http_response_type[i] == status) {
566                                         http_error_page[i] = concat_path_file((*c == '/') ? NULL : home_httpd, c);
567                                         break;
568                                 }
569                         }
570                         continue;
571                 }
572 #endif
573
574 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
575                 if (*p0 == '/') {
576                         /* make full path from httpd root / current_path / config_line_path */
577                         cf = (flag == SUBDIR_PARSE ? path : "");
578                         p0 = malloc(strlen(cf) + (c - buf) + 2 + strlen(c));
579                         if (p0 == NULL)
580                                 continue;
581                         c[-1] = '\0';
582                         sprintf(p0, "/%s%s", cf, buf);
583
584                         /* another call bb_simplify_path */
585                         cf = p = p0;
586
587                         do {
588                                 if (*p == '/') {
589                                         if (*cf == '/') {    /* skip duplicate (or initial) slash */
590                                                 continue;
591                                         } else if (*cf == '.') {
592                                                 if (cf[1] == '/' || cf[1] == '\0') { /* remove extra '.' */
593                                                         continue;
594                                                 } else if ((cf[1] == '.') && (cf[2] == '/' || cf[2] == '\0')) {
595                                                         ++cf;
596                                                         if (p > p0) {
597                                                                 while (*--p != '/') /* omit previous dir */;
598                                                         }
599                                                         continue;
600                                                 }
601                                         }
602                                 }
603                                 *++p = *cf;
604                         } while (*++cf);
605
606                         if ((p == p0) || (*p != '/')) {      /* not a trailing slash */
607                                 ++p;                             /* so keep last character */
608                         }
609                         *p = '\0';
610                         sprintf(p0, "%s:%s", p0, c);
611                 }
612 #endif
613
614 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH \
615  || ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES \
616  || ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
617                 /* storing current config line */
618                 cur = xzalloc(sizeof(Htaccess) + strlen(p0));
619                 if (cur) {
620                         cf = strcpy(cur->before_colon, p0);
621                         c = strchr(cf, ':');
622                         *c++ = 0;
623                         cur->after_colon = c;
624 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
625                         if (*cf == '.') {
626                                 /* config .mime line move top for overwrite previous */
627                                 cur->next = mime_a;
628                                 mime_a = cur;
629                                 continue;
630                         }
631 #endif
632 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
633                         if (*cf == '*' && cf[1] == '.') {
634                                 /* config script interpreter line move top for overwrite previous */
635                                 cur->next = script_i;
636                                 script_i = cur;
637                                 continue;
638                         }
639 #endif
640 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
641                         free(p0);
642                         if (prev == NULL) {
643                                 /* first line */
644                                 g_auth = prev = cur;
645                         } else {
646                                 /* sort path, if current lenght eq or bigger then move up */
647                                 Htaccess *prev_hti = g_auth;
648                                 size_t l = strlen(cf);
649                                 Htaccess *hti;
650
651                                 for (hti = prev_hti; hti; hti = hti->next) {
652                                         if (l >= strlen(hti->before_colon)) {
653                                                 /* insert before hti */
654                                                 cur->next = hti;
655                                                 if (prev_hti != hti) {
656                                                         prev_hti->next = cur;
657                                                 } else {
658                                                         /* insert as top */
659                                                         g_auth = cur;
660                                                 }
661                                                 break;
662                                         }
663                                         if (prev_hti != hti)
664                                                 prev_hti = prev_hti->next;
665                                 }
666                                 if (!hti) {       /* not inserted, add to bottom */
667                                         prev->next = cur;
668                                         prev = cur;
669                                 }
670                         }
671 #endif
672                 }
673 #endif
674          }
675          fclose(f);
676 }
677
678 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
679 /*
680  * Given a string, html-encode special characters.
681  * This is used for the -e command line option to provide an easy way
682  * for scripts to encode result data without confusing browsers.  The
683  * returned string pointer is memory allocated by malloc().
684  *
685  * Returns a pointer to the encoded string (malloced).
686  */
687 static char *encodeString(const char *string)
688 {
689         /* take the simple route and encode everything */
690         /* could possibly scan once to get length.     */
691         int len = strlen(string);
692         char *out = xmalloc(len * 6 + 1);
693         char *p = out;
694         char ch;
695
696         while ((ch = *string++)) {
697                 // very simple check for what to encode
698                 if (isalnum(ch)) *p++ = ch;
699                 else p += sprintf(p, "&#%d;", (unsigned char) ch);
700         }
701         *p = '\0';
702         return out;
703 }
704 #endif          /* FEATURE_HTTPD_ENCODE_URL_STR */
705
706 /*
707  * Given a URL encoded string, convert it to plain ascii.
708  * Since decoding always makes strings smaller, the decode is done in-place.
709  * Thus, callers should strdup() the argument if they do not want the
710  * argument modified.  The return is the original pointer, allowing this
711  * function to be easily used as arguments to other functions.
712  *
713  * string    The first string to decode.
714  * option_d  1 if called for httpd -d
715  *
716  * Returns a pointer to the decoded string (same as input).
717  */
718 static unsigned hex_to_bin(unsigned char c)
719 {
720         unsigned v = c | 0x20; /* lowercase */
721         v = v - '0';
722         if (v <= 9)
723                 return v;
724         v = v + ('0' - 'a');
725         if (v <= 5)
726                 return v + 10;
727         return ~0;
728 }
729 /* For testing:
730 void t(char c) { printf("'%c' %u\n", c, hex_to_bin(c)); }
731 int main() { t('0'); t('9'); t('A'); t('F'); t('a'); t('f');
732 t('0'-1); t('9'+1); t('A'-1); t('F'+1); t('a'-1); t('f'+1); return 0; }
733 */
734 static char *decodeString(char *orig, int option_d)
735 {
736         /* note that decoded string is always shorter than original */
737         char *string = orig;
738         char *ptr = string;
739         char c;
740
741         while ((c = *ptr++) != '\0') {
742                 unsigned v;
743
744                 if (option_d && c == '+') {
745                         *string++ = ' ';
746                         continue;
747                 }
748                 if (c != '%') {
749                         *string++ = c;
750                         continue;
751                 }
752                 v = hex_to_bin(ptr[0]);
753                 if (v > 15) {
754  bad_hex:
755                         if (!option_d)
756                                 return NULL;
757                         *string++ = '%';
758                         continue;
759                 }
760                 v = (v * 16) | hex_to_bin(ptr[1]);
761                 if (v > 255)
762                         goto bad_hex;
763                 if (!option_d && (v == '/' || v == '\0')) {
764                         /* caller takes it as indication of invalid
765                          * (dangerous wrt exploits) chars */
766                         return orig + 1;
767                 }
768                 *string++ = v;
769                 ptr += 2;
770         }
771         *string = '\0';
772         return orig;
773 }
774
775 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
776 /*
777  * Decode a base64 data stream as per rfc1521.
778  * Note that the rfc states that non base64 chars are to be ignored.
779  * Since the decode always results in a shorter size than the input,
780  * it is OK to pass the input arg as an output arg.
781  * Parameter: a pointer to a base64 encoded string.
782  * Decoded data is stored in-place.
783  */
784 static void decodeBase64(char *Data)
785 {
786         const unsigned char *in = (const unsigned char *)Data;
787         /* The decoded size will be at most 3/4 the size of the encoded */
788         unsigned ch = 0;
789         int i = 0;
790
791         while (*in) {
792                 int t = *in++;
793
794                 if (t >= '0' && t <= '9')
795                         t = t - '0' + 52;
796                 else if (t >= 'A' && t <= 'Z')
797                         t = t - 'A';
798                 else if (t >= 'a' && t <= 'z')
799                         t = t - 'a' + 26;
800                 else if (t == '+')
801                         t = 62;
802                 else if (t == '/')
803                         t = 63;
804                 else if (t == '=')
805                         t = 0;
806                 else
807                         continue;
808
809                 ch = (ch << 6) | t;
810                 i++;
811                 if (i == 4) {
812                         *Data++ = (char) (ch >> 16);
813                         *Data++ = (char) (ch >> 8);
814                         *Data++ = (char) ch;
815                         i = 0;
816                 }
817         }
818         *Data = '\0';
819 }
820 #endif
821
822 /*
823  * Create a listen server socket on the designated port.
824  */
825 static int openServer(void)
826 {
827         int n = bb_strtou(bind_addr_or_port, NULL, 10);
828         if (!errno && n && n <= 0xffff)
829                 n = create_and_bind_stream_or_die(NULL, n);
830         else
831                 n = create_and_bind_stream_or_die(bind_addr_or_port, 80);
832         xlisten(n, 9);
833         return n;
834 }
835
836 /*
837  * Log the connection closure and exit.
838  */
839 static void log_and_exit(void) ATTRIBUTE_NORETURN;
840 static void log_and_exit(void)
841 {
842         /* Paranoia. IE said to be buggy. It may send some extra data
843          * or be confused by us just exiting without SHUT_WR. Oh well. */
844         shutdown(1, SHUT_WR);
845         ndelay_on(0);
846         while (read(0, iobuf, IOBUF_SIZE) > 0)
847                 continue;
848
849         if (verbose > 2)
850                 bb_error_msg("closed");
851         _exit(xfunc_error_retval);
852 }
853
854 /*
855  * Create and send HTTP response headers.
856  * The arguments are combined and sent as one write operation.  Note that
857  * IE will puke big-time if the headers are not sent in one packet and the
858  * second packet is delayed for any reason.
859  * responseNum - the result code to send.
860  */
861 static void send_headers(int responseNum)
862 {
863         static const char RFC1123FMT[] ALIGN1 = "%a, %d %b %Y %H:%M:%S GMT";
864
865         const char *responseString = "";
866         const char *infoString = NULL;
867         const char *mime_type;
868 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
869         const char *error_page = 0;
870 #endif
871         unsigned i;
872         time_t timer = time(0);
873         char tmp_str[80];
874         int len;
875
876         for (i = 0; i < ARRAY_SIZE(http_response_type); i++) {
877                 if (http_response_type[i] == responseNum) {
878                         responseString = http_response[i].name;
879                         infoString = http_response[i].info;
880 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
881                         error_page = http_error_page[i];
882 #endif
883                         break;
884                 }
885         }
886         /* error message is HTML */
887         mime_type = responseNum == HTTP_OK ?
888                                 found_mime_type : "text/html";
889
890         if (verbose)
891                 bb_error_msg("response:%u", responseNum);
892
893         /* emit the current date */
894         strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&timer));
895         len = sprintf(iobuf,
896                         "HTTP/1.0 %d %s\r\nContent-type: %s\r\n"
897                         "Date: %s\r\nConnection: close\r\n",
898                         responseNum, responseString, mime_type, tmp_str);
899
900 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
901         if (responseNum == HTTP_UNAUTHORIZED) {
902                 len += sprintf(iobuf + len,
903                                 "WWW-Authenticate: Basic realm=\"%s\"\r\n",
904                                 g_realm);
905         }
906 #endif
907         if (responseNum == HTTP_MOVED_TEMPORARILY) {
908                 len += sprintf(iobuf + len, "Location: %s/%s%s\r\n",
909                                 found_moved_temporarily,
910                                 (g_query ? "?" : ""),
911                                 (g_query ? g_query : ""));
912         }
913
914 #if ENABLE_FEATURE_HTTPD_ERROR_PAGES
915         if (error_page && !access(error_page, R_OK)) {
916                 strcat(iobuf, "\r\n");
917                 len += 2;
918
919                 if (DEBUG)
920                         fprintf(stderr, "headers: '%s'\n", iobuf);
921                 full_write(1, iobuf, len);
922                 if (DEBUG)
923                         fprintf(stderr, "writing error page: '%s'\n", error_page);
924                 return send_file_and_exit(error_page, FALSE);
925         }
926 #endif
927
928         if (ContentLength != -1) {    /* file */
929                 strftime(tmp_str, sizeof(tmp_str), RFC1123FMT, gmtime(&last_mod));
930                 len += sprintf(iobuf + len, "Last-Modified: %s\r\n%s %"OFF_FMT"d\r\n",
931                         tmp_str, "Content-length:", ContentLength);
932         }
933         iobuf[len++] = '\r';
934         iobuf[len++] = '\n';
935         if (infoString) {
936                 len += sprintf(iobuf + len,
937                                 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n"
938                                 "<BODY><H1>%d %s</H1>\n%s\n</BODY></HTML>\n",
939                                 responseNum, responseString,
940                                 responseNum, responseString, infoString);
941         }
942         if (DEBUG)
943                 fprintf(stderr, "headers: '%s'\n", iobuf);
944         if (full_write(1, iobuf, len) != len) {
945                 if (verbose > 1)
946                         bb_perror_msg("error");
947                 log_and_exit();
948         }
949 }
950
951 static void send_headers_and_exit(int responseNum) ATTRIBUTE_NORETURN;
952 static void send_headers_and_exit(int responseNum)
953 {
954         send_headers(responseNum);
955         log_and_exit();
956 }
957
958 /*
959  * Read from the socket until '\n' or EOF. '\r' chars are removed.
960  * '\n' is replaced with NUL.
961  * Return number of characters read or 0 if nothing is read
962  * ('\r' and '\n' are not counted).
963  * Data is returned in iobuf.
964  */
965 static int get_line(void)
966 {
967         int count = 0;
968         char c;
969
970         while (1) {
971                 if (hdr_cnt <= 0) {
972                         hdr_cnt = safe_read(0, hdr_buf, sizeof(hdr_buf));
973                         if (hdr_cnt <= 0)
974                                 break;
975                         hdr_ptr = hdr_buf;
976                 }
977                 iobuf[count] = c = *hdr_ptr++;
978                 hdr_cnt--;
979
980                 if (c == '\r')
981                         continue;
982                 if (c == '\n') {
983                         iobuf[count] = '\0';
984                         return count;
985                 }
986                 if (count < (IOBUF_SIZE - 1))      /* check overflow */
987                         count++;
988         }
989         return count;
990 }
991
992 #if ENABLE_FEATURE_HTTPD_CGI
993 static void setenv1(const char *name, const char *value)
994 {
995         setenv(name, value ? value : "", 1);
996 }
997
998 /*
999  * Spawn CGI script, forward CGI's stdin/out <=> network
1000  *
1001  * Environment variables are set up and the script is invoked with pipes
1002  * for stdin/stdout.  If a post is being done the script is fed the POST
1003  * data in addition to setting the QUERY_STRING variable (for GETs or POSTs).
1004  *
1005  * Parameters:
1006  * const char *url              The requested URL (with leading /).
1007  * int bodyLen                  Length of the post body.
1008  * const char *cookie           For set HTTP_COOKIE.
1009  * const char *content_type     For set CONTENT_TYPE.
1010  */
1011 static void send_cgi_and_exit(
1012                 const char *url,
1013                 const char *request,
1014                 int bodyLen,
1015                 const char *cookie,
1016                 const char *content_type) ATTRIBUTE_NORETURN;
1017 static void send_cgi_and_exit(
1018                 const char *url,
1019                 const char *request,
1020                 int bodyLen,
1021                 const char *cookie,
1022                 const char *content_type)
1023 {
1024         struct { int rd; int wr; } fromCgi;  /* CGI -> httpd pipe */
1025         struct { int rd; int wr; } toCgi;    /* httpd -> CGI pipe */
1026         char *fullpath;
1027         char *script;
1028         char *purl;
1029         int buf_count;
1030         int status;
1031         int pid = 0;
1032
1033         /*
1034          * We are mucking with environment _first_ and then vfork/exec,
1035          * this allows us to use vfork safely. Parent don't care about
1036          * these environment changes anyway.
1037          */
1038
1039         /*
1040          * Find PATH_INFO.
1041          */
1042         purl = xstrdup(url);
1043         script = purl;
1044         while ((script = strchr(script + 1, '/')) != NULL) {
1045                 /* have script.cgi/PATH_INFO or dirs/script.cgi[/PATH_INFO] */
1046                 struct stat sb;
1047
1048                 *script = '\0';
1049                 if (!is_directory(purl + 1, 1, &sb)) {
1050                         /* not directory, found script.cgi/PATH_INFO */
1051                         *script = '/';
1052                         break;
1053                 }
1054                 *script = '/';          /* is directory, find next '/' */
1055         }
1056         setenv1("PATH_INFO", script);   /* set /PATH_INFO or "" */
1057         setenv1("REQUEST_METHOD", request);
1058         if (g_query) {
1059                 putenv(xasprintf("%s=%s?%s", "REQUEST_URI", purl, g_query));
1060         } else {
1061                 setenv1("REQUEST_URI", purl);
1062         }
1063         if (script != NULL)
1064                 *script = '\0';         /* cut off /PATH_INFO */
1065
1066         /* SCRIPT_FILENAME required by PHP in CGI mode */
1067         fullpath = concat_path_file(home_httpd, purl);
1068         setenv1("SCRIPT_FILENAME", fullpath);
1069         /* set SCRIPT_NAME as full path: /cgi-bin/dirs/script.cgi */
1070         setenv1("SCRIPT_NAME", purl);
1071         /* http://hoohoo.ncsa.uiuc.edu/cgi/env.html:
1072          * QUERY_STRING: The information which follows the ? in the URL
1073          * which referenced this script. This is the query information.
1074          * It should not be decoded in any fashion. This variable
1075          * should always be set when there is query information,
1076          * regardless of command line decoding. */
1077         /* (Older versions of bbox seem to do some decoding) */
1078         setenv1("QUERY_STRING", g_query);
1079         putenv((char*)"SERVER_SOFTWARE=busybox httpd/"BB_VER);
1080         putenv((char*)"SERVER_PROTOCOL=HTTP/1.0");
1081         putenv((char*)"GATEWAY_INTERFACE=CGI/1.1");
1082         /* Having _separate_ variables for IP and port defeats
1083          * the purpose of having socket abstraction. Which "port"
1084          * are you using on Unix domain socket?
1085          * IOW - REMOTE_PEER="1.2.3.4:56" makes much more sense.
1086          * Oh well... */
1087         {
1088                 char *p = rmt_ip_str ? rmt_ip_str : (char*)"";
1089                 char *cp = strrchr(p, ':');
1090                 if (ENABLE_FEATURE_IPV6 && cp && strchr(cp, ']'))
1091                         cp = NULL;
1092                 if (cp) *cp = '\0'; /* delete :PORT */
1093                 setenv1("REMOTE_ADDR", p);
1094                 if (cp) {
1095                         *cp = ':';
1096 #if ENABLE_FEATURE_HTTPD_SET_REMOTE_PORT_TO_ENV
1097                         setenv1("REMOTE_PORT", cp + 1);
1098 #endif
1099                 }
1100         }
1101         setenv1("HTTP_USER_AGENT", user_agent);
1102         if (bodyLen)
1103                 putenv(xasprintf("CONTENT_LENGTH=%d", bodyLen));
1104         if (cookie)
1105                 setenv1("HTTP_COOKIE", cookie);
1106         if (content_type)
1107                 setenv1("CONTENT_TYPE", content_type);
1108 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1109         if (remoteuser) {
1110                 setenv1("REMOTE_USER", remoteuser);
1111                 putenv((char*)"AUTH_TYPE=Basic");
1112         }
1113 #endif
1114         if (referer)
1115                 setenv1("HTTP_REFERER", referer);
1116
1117         xpipe(&fromCgi.rd);
1118         xpipe(&toCgi.rd);
1119
1120         pid = vfork();
1121         if (pid < 0) {
1122                 /* TODO: log perror? */
1123                 log_and_exit();
1124         }
1125
1126         if (!pid) {
1127                 /* Child process */
1128                 xfunc_error_retval = 242;
1129
1130                 xmove_fd(toCgi.rd, 0);  /* replace stdin with the pipe */
1131                 xmove_fd(fromCgi.wr, 1);  /* replace stdout with the pipe */
1132                 close(fromCgi.rd);
1133                 close(toCgi.wr);
1134                 /* User seeing stderr output can be a security problem.
1135                  * If CGI really wants that, it can always do dup itself. */
1136                 /* dup2(1, 2); */
1137
1138                 /* script must have absolute path */
1139                 script = strrchr(fullpath, '/');
1140                 if (!script)
1141                         goto error_execing_cgi;
1142                 *script = '\0';
1143                 /* chdiring to script's dir */
1144                 if (chdir(fullpath) == 0) {
1145                         char *argv[2];
1146 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1147                         char *interpr = NULL;
1148                         char *suffix = strrchr(purl, '.');
1149
1150                         if (suffix) {
1151                                 Htaccess *cur;
1152                                 for (cur = script_i; cur; cur = cur->next) {
1153                                         if (strcmp(cur->before_colon + 1, suffix) == 0) {
1154                                                 interpr = cur->after_colon;
1155                                                 break;
1156                                         }
1157                                 }
1158                         }
1159 #endif
1160                         *script = '/';
1161                         /* set argv[0] to name without path */
1162                         argv[0] = (char*)bb_basename(purl);
1163                         argv[1] = NULL;
1164 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1165                         if (interpr)
1166                                 execv(interpr, argv);
1167                         else
1168 #endif
1169                                 execv(fullpath, argv);
1170                 }
1171  error_execing_cgi:
1172                 /* send to stdout
1173                  * (we are CGI here, our stdout is pumped to the net) */
1174                 send_headers_and_exit(HTTP_NOT_FOUND);
1175         } /* end child */
1176
1177         /* Parent process */
1178
1179         /* First, restore variables possibly changed by child */
1180         xfunc_error_retval = 0;
1181
1182         /* Prepare for pumping data.
1183          * iobuf is used for CGI -> network data,
1184          * hdr_buf is for network -> CGI data (POSTDATA) */
1185         buf_count = 0;
1186         close(fromCgi.wr);
1187         close(toCgi.rd);
1188
1189         /* If CGI dies, we still want to correctly finish reading its output
1190          * and send it to the peer. So please no SIGPIPEs! */
1191         signal(SIGPIPE, SIG_IGN);
1192
1193         /* This loop still looks messy. What is an exit criteria?
1194          * "CGI's output closed"? Or "CGI has exited"?
1195          * What to do if CGI has closed both input and output, but
1196          * didn't exit? etc... */
1197
1198         /* NB: breaking out of this loop jumps to log_and_exit() */
1199         while (1) {
1200                 fd_set readSet;
1201                 fd_set writeSet;
1202                 int nfound;
1203                 int count;
1204
1205                 FD_ZERO(&readSet);
1206                 FD_ZERO(&writeSet);
1207                 FD_SET(fromCgi.rd, &readSet);
1208                 if (bodyLen > 0 || hdr_cnt > 0) {
1209                         FD_SET(toCgi.wr, &writeSet);
1210                         nfound = toCgi.wr > fromCgi.rd ? toCgi.wr : fromCgi.rd;
1211                         if (hdr_cnt <= 0)
1212                                 FD_SET(0, &readSet);
1213                         /* Now wait on the set of sockets! */
1214                         nfound = select(nfound + 1, &readSet, &writeSet, NULL, NULL);
1215                 } else {
1216                         if (!bodyLen) {
1217                                 close(toCgi.wr); /* no more POST data to CGI */
1218                                 bodyLen = -1;
1219                         }
1220                         nfound = select(fromCgi.rd + 1, &readSet, NULL, NULL, NULL);
1221                 }
1222
1223                 if (nfound <= 0) {
1224                         if (waitpid(pid, &status, WNOHANG) <= 0) {
1225                                 /* Weird. CGI didn't exit and no fd's
1226                                  * are ready, yet select returned?! */
1227                                 continue;
1228                         }
1229                         close(fromCgi.rd);
1230                         if (DEBUG && WIFEXITED(status))
1231                                 bb_error_msg("CGI exited, status=%d", WEXITSTATUS(status));
1232                         if (DEBUG && WIFSIGNALED(status))
1233                                 bb_error_msg("CGI killed, signal=%d", WTERMSIG(status));
1234                         break;
1235                 }
1236
1237                 if (hdr_cnt > 0 && FD_ISSET(toCgi.wr, &writeSet)) {
1238                         /* Have data from peer and can write to CGI */
1239                         count = safe_write(toCgi.wr, hdr_ptr, hdr_cnt);
1240                         /* Doesn't happen, we dont use nonblocking IO here
1241                          *if (count < 0 && errno == EAGAIN) {
1242                          *      ...
1243                          *} else */
1244                         if (count > 0) {
1245                                 hdr_ptr += count;
1246                                 hdr_cnt -= count;
1247                         } else {
1248                                 hdr_cnt = bodyLen = 0; /* EOF/broken pipe to CGI */
1249                         }
1250                 } else if (bodyLen > 0 && hdr_cnt == 0
1251                  && FD_ISSET(0, &readSet)
1252                 ) {
1253                         /* We expect data, prev data portion is eaten by CGI
1254                          * and there *is* data to read from the peer
1255                          * (POSTDATA?) */
1256                         count = bodyLen > (int)sizeof(hdr_buf) ? (int)sizeof(hdr_buf) : bodyLen;
1257                         count = safe_read(0, hdr_buf, count);
1258                         if (count > 0) {
1259                                 hdr_cnt = count;
1260                                 hdr_ptr = hdr_buf;
1261                                 bodyLen -= count;
1262                         } else {
1263                                 bodyLen = 0; /* closed */
1264                         }
1265                 }
1266
1267 #define PIPESIZE PIPE_BUF
1268 #if PIPESIZE >= IOBUF_SIZE
1269 # error "PIPESIZE >= IOBUF_SIZE"
1270 #endif
1271                 if (FD_ISSET(fromCgi.rd, &readSet)) {
1272                         /* There is something to read from CGI */
1273                         char *rbuf = iobuf;
1274
1275                         /* Are we still buffering CGI output? */
1276                         if (buf_count >= 0) {
1277                                 /* HTTP_200[] has single "\r\n" at the end.
1278                                  * According to http://hoohoo.ncsa.uiuc.edu/cgi/out.html,
1279                                  * CGI scripts MUST send their own header terminated by
1280                                  * empty line, then data. That's why we have only one
1281                                  * <cr><lf> pair here. We will output "200 OK" line
1282                                  * if needed, but CGI still has to provide blank line
1283                                  * between header and body */
1284
1285                                 /* Must use safe_read, not full_read, because
1286                                  * CGI may output a few first bytes and then wait
1287                                  * for POSTDATA without closing stdout.
1288                                  * With full_read we may wait here forever. */
1289                                 count = safe_read(fromCgi.rd, rbuf + buf_count, PIPESIZE - 8);
1290                                 if (count <= 0) {
1291                                         /* eof (or error) and there was no "HTTP",
1292                                          * so write it, then write received data */
1293                                         if (buf_count) {
1294                                                 full_write(1, HTTP_200, sizeof(HTTP_200)-1);
1295                                                 full_write(1, rbuf, buf_count);
1296                                         }
1297                                         break; /* CGI stdout is closed, exiting */
1298                                 }
1299                                 buf_count += count;
1300                                 count = 0;
1301                                 /* "Status" header format is: "Status: 302 Redirected\r\n" */
1302                                 if (buf_count >= 8 && memcmp(rbuf, "Status: ", 8) == 0) {
1303                                         /* send "HTTP/1.0 " */
1304                                         if (full_write(1, HTTP_200, 9) != 9)
1305                                                 break;
1306                                         rbuf += 8; /* skip "Status: " */
1307                                         count = buf_count - 8;
1308                                         buf_count = -1; /* buffering off */
1309                                 } else if (buf_count >= 4) {
1310                                         /* Did CGI add "HTTP"? */
1311                                         if (memcmp(rbuf, HTTP_200, 4) != 0) {
1312                                                 /* there is no "HTTP", do it ourself */
1313                                                 if (full_write(1, HTTP_200, sizeof(HTTP_200)-1) != sizeof(HTTP_200)-1)
1314                                                         break;
1315                                         }
1316                                         /* Commented out:
1317                                         if (!strstr(rbuf, "ontent-")) {
1318                                                 full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1319                                         }
1320                                          * Counter-example of valid CGI without Content-type:
1321                                          * echo -en "HTTP/1.0 302 Found\r\n"
1322                                          * echo -en "Location: http://www.busybox.net\r\n"
1323                                          * echo -en "\r\n"
1324                                          */
1325                                         count = buf_count;
1326                                         buf_count = -1; /* buffering off */
1327                                 }
1328                         } else {
1329                                 count = safe_read(fromCgi.rd, rbuf, PIPESIZE);
1330                                 if (count <= 0)
1331                                         break;  /* eof (or error) */
1332                         }
1333                         if (full_write(1, rbuf, count) != count)
1334                                 break;
1335                         if (DEBUG)
1336                                 fprintf(stderr, "cgi read %d bytes: '%.*s'\n", count, count, rbuf);
1337                 } /* if (FD_ISSET(fromCgi.rd)) */
1338         } /* while (1) */
1339         log_and_exit();
1340 }
1341 #endif          /* FEATURE_HTTPD_CGI */
1342
1343 /*
1344  * Send a file response to a HTTP request, and exit
1345  * 
1346  * Parameters:
1347  * const char *url    The requested URL (with leading /).
1348  * headers            Don't send headers before if FALSE.
1349  */
1350 static void send_file_and_exit(const char *url, int headers)
1351 {
1352         static const char *const suffixTable[] = {
1353         /* Warning: shorter equivalent suffix in one line must be first */
1354                 ".htm.html", "text/html",
1355                 ".jpg.jpeg", "image/jpeg",
1356                 ".gif",      "image/gif",
1357                 ".png",      "image/png",
1358                 ".txt.h.c.cc.cpp", "text/plain",
1359                 ".css",      "text/css",
1360                 ".wav",      "audio/wav",
1361                 ".avi",      "video/x-msvideo",
1362                 ".qt.mov",   "video/quicktime",
1363                 ".mpe.mpeg", "video/mpeg",
1364                 ".mid.midi", "audio/midi",
1365                 ".mp3",      "audio/mpeg",
1366 #if 0                        /* unpopular */
1367                 ".au",       "audio/basic",
1368                 ".pac",      "application/x-ns-proxy-autoconfig",
1369                 ".vrml.wrl", "model/vrml",
1370 #endif
1371                 NULL
1372         };
1373
1374         char *suffix;
1375         int f;
1376         const char *const *table;
1377         const char *try_suffix;
1378         ssize_t count;
1379 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1380         off_t offset = 0;
1381 #endif
1382
1383         suffix = strrchr(url, '.');
1384
1385         /* If not found, set default as "application/octet-stream";  */
1386         found_mime_type = "application/octet-stream";
1387         if (suffix) {
1388 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1389                 Htaccess *cur;
1390 #endif
1391                 for (table = suffixTable; *table; table += 2) {
1392                         try_suffix = strstr(table[0], suffix);
1393                         if (try_suffix) {
1394                                 try_suffix += strlen(suffix);
1395                                 if (*try_suffix == '\0' || *try_suffix == '.') {
1396                                         found_mime_type = table[1];
1397                                         break;
1398                                 }
1399                         }
1400                 }
1401 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1402                 for (cur = mime_a; cur; cur = cur->next) {
1403                         if (strcmp(cur->before_colon, suffix) == 0) {
1404                                 found_mime_type = cur->after_colon;
1405                                 break;
1406                         }
1407                 }
1408 #endif
1409         }
1410
1411         if (DEBUG)
1412                 bb_error_msg("sending file '%s' content-type: %s",
1413                         url, found_mime_type);
1414
1415         f = open(url, O_RDONLY);
1416         if (f < 0) {
1417                 if (DEBUG)
1418                         bb_perror_msg("cannot open '%s'", url);
1419                 if (headers)
1420                         send_headers_and_exit(HTTP_NOT_FOUND);
1421         }
1422
1423         if (headers)
1424                 send_headers(HTTP_OK);
1425
1426         /* If you want to know about EPIPE below
1427          * (happens if you abort downloads from local httpd): */
1428         signal(SIGPIPE, SIG_IGN);
1429
1430 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1431         do {
1432                 /* byte count (3rd arg) is rounded down to 64k */
1433                 count = sendfile(1, f, &offset, MAXINT(ssize_t) - 0xffff);
1434                 if (count < 0) {
1435                         if (offset == 0)
1436                                 goto fallback;
1437                         goto fin;
1438                 }
1439         } while (count > 0);
1440         log_and_exit();
1441
1442  fallback:
1443 #endif
1444         while ((count = safe_read(f, iobuf, IOBUF_SIZE)) > 0) {
1445                 ssize_t n = count;
1446                 count = full_write(1, iobuf, count);
1447                 if (count != n)
1448                         break;
1449         }
1450 #if ENABLE_FEATURE_HTTPD_USE_SENDFILE
1451  fin:
1452 #endif
1453         if (count < 0 && verbose > 1)
1454                 bb_perror_msg("error");
1455         log_and_exit();
1456 }
1457
1458 static int checkPermIP(void)
1459 {
1460         Htaccess_IP *cur;
1461
1462         /* This could stand some work */
1463         for (cur = ip_a_d; cur; cur = cur->next) {
1464 #if DEBUG
1465                 fprintf(stderr,
1466                         "checkPermIP: '%s' ? '%u.%u.%u.%u/%u.%u.%u.%u'\n",
1467                         rmt_ip_str,
1468                         (unsigned char)(cur->ip >> 24),
1469                         (unsigned char)(cur->ip >> 16),
1470                         (unsigned char)(cur->ip >> 8),
1471                         (unsigned char)(cur->ip),
1472                         (unsigned char)(cur->mask >> 24),
1473                         (unsigned char)(cur->mask >> 16),
1474                         (unsigned char)(cur->mask >> 8),
1475                         (unsigned char)(cur->mask)
1476                 );
1477 #endif
1478                 if ((rmt_ip & cur->mask) == cur->ip)
1479                         return cur->allow_deny == 'A';   /* Allow/Deny */
1480         }
1481
1482         /* if unconfigured, return 1 - access from all */
1483         return !flg_deny_all;
1484 }
1485
1486 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1487 /*
1488  * Check the permission file for access password protected.
1489  *
1490  * If config file isn't present, everything is allowed.
1491  * Entries are of the form you can see example from header source
1492  *
1493  * path      The file path.
1494  * request   User information to validate.
1495  *
1496  * Returns 1 if request is OK.
1497  */
1498 static int checkPerm(const char *path, const char *request)
1499 {
1500         Htaccess *cur;
1501         const char *p;
1502         const char *p0;
1503
1504         const char *prev = NULL;
1505
1506         /* This could stand some work */
1507         for (cur = g_auth; cur; cur = cur->next) {
1508                 size_t l;
1509
1510                 p0 = cur->before_colon;
1511                 if (prev != NULL && strcmp(prev, p0) != 0)
1512                         continue;       /* find next identical */
1513                 p = cur->after_colon;
1514                 if (DEBUG)
1515                         fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1516
1517                 l = strlen(p0);
1518                 if (strncmp(p0, path, l) == 0
1519                  && (l == 1 || path[l] == '/' || path[l] == '\0')
1520                 ) {
1521                         char *u;
1522                         /* path match found.  Check request */
1523                         /* for check next /path:user:password */
1524                         prev = p0;
1525                         u = strchr(request, ':');
1526                         if (u == NULL) {
1527                                 /* bad request, ':' required */
1528                                 break;
1529                         }
1530
1531                         if (ENABLE_FEATURE_HTTPD_AUTH_MD5) {
1532                                 char *cipher;
1533                                 char *pp;
1534
1535                                 if (strncmp(p, request, u - request) != 0) {
1536                                         /* user doesn't match */
1537                                         continue;
1538                                 }
1539                                 pp = strchr(p, ':');
1540                                 if (pp && pp[1] == '$' && pp[2] == '1'
1541                                  && pp[3] == '$' && pp[4]
1542                                 ) {
1543                                         pp++;
1544                                         cipher = pw_encrypt(u+1, pp);
1545                                         if (strcmp(cipher, pp) == 0)
1546                                                 goto set_remoteuser_var;   /* Ok */
1547                                         /* unauthorized */
1548                                         continue;
1549                                 }
1550                         }
1551
1552                         if (strcmp(p, request) == 0) {
1553  set_remoteuser_var:
1554                                 remoteuser = strdup(request);
1555                                 if (remoteuser)
1556                                         remoteuser[u - request] = '\0';
1557                                 return 1;   /* Ok */
1558                         }
1559                         /* unauthorized */
1560                 }
1561         } /* for */
1562
1563         return prev == NULL;
1564 }
1565 #endif  /* FEATURE_HTTPD_BASIC_AUTH */
1566
1567 /*
1568  * Handle timeouts
1569  */
1570 static void exit_on_signal(int sig) ATTRIBUTE_NORETURN;
1571 static void exit_on_signal(int sig)
1572 {
1573         send_headers_and_exit(HTTP_REQUEST_TIMEOUT);
1574 }
1575
1576 /*
1577  * Handle an incoming http request and exit.
1578  */
1579 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr) ATTRIBUTE_NORETURN;
1580 static void handle_incoming_and_exit(const len_and_sockaddr *fromAddr)
1581 {
1582         static const char request_GET[] ALIGN1 = "GET";
1583
1584         struct stat sb;
1585         char *urlcopy;
1586         char *urlp;
1587         char *tptr;
1588         int http_major_version;
1589         int ip_allowed;
1590 #if ENABLE_FEATURE_HTTPD_CGI
1591         const char *prequest;
1592         unsigned long length = 0;
1593         char *cookie = 0;
1594         char *content_type = 0;
1595 #endif
1596         struct sigaction sa;
1597 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1598         int credentials = -1;  /* if not required this is Ok */
1599 #endif
1600
1601         /* Allocation of iobuf is postponed until now
1602          * (IOW, server process doesn't need to waste 8k) */
1603         iobuf = xmalloc(IOBUF_SIZE);
1604
1605         rmt_ip = 0;
1606         if (fromAddr->sa.sa_family == AF_INET) {
1607                 rmt_ip = ntohl(fromAddr->sin.sin_addr.s_addr);
1608         }
1609         if (ENABLE_FEATURE_HTTPD_CGI || DEBUG || verbose) {
1610                 rmt_ip_str = xmalloc_sockaddr2dotted(&fromAddr->sa);
1611         }
1612         if (verbose) {
1613                 /* this trick makes -v logging much simpler */
1614                 applet_name = rmt_ip_str;
1615                 if (verbose > 2)
1616                         bb_error_msg("connected");
1617         }
1618
1619         /* Install timeout handler */
1620         memset(&sa, 0, sizeof(sa));
1621         sa.sa_handler = exit_on_signal;
1622         /* sigemptyset(&sa.sa_mask); - memset should be enough */
1623         /*sa.sa_flags = 0; - no SA_RESTART */
1624         sigaction(SIGALRM, &sa, NULL);
1625         alarm(HEADER_READ_TIMEOUT);
1626
1627         if (!get_line()) /* EOF or error or empty line */
1628                 send_headers_and_exit(HTTP_BAD_REQUEST);
1629
1630         /* Determine type of request (GET/POST) */
1631         urlp = strpbrk(iobuf, " \t");
1632         if (urlp == NULL)
1633                 send_headers_and_exit(HTTP_BAD_REQUEST);
1634         *urlp++ = '\0';
1635 #if ENABLE_FEATURE_HTTPD_CGI
1636         prequest = request_GET;
1637         if (strcasecmp(iobuf, prequest) != 0) {
1638                 prequest = "POST";
1639                 if (strcasecmp(iobuf, prequest) != 0)
1640                         send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1641         }
1642 #else
1643         if (strcasecmp(iobuf, request_GET) != 0)
1644                 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1645 #endif
1646         urlp = skip_whitespace(urlp);
1647         if (urlp[0] != '/')
1648                 send_headers_and_exit(HTTP_BAD_REQUEST);
1649
1650         /* Find end of URL and parse HTTP version, if any */
1651         http_major_version = -1;
1652         tptr = strchrnul(urlp, ' ');
1653         /* Is it " HTTP/"? */
1654         if (tptr[0] && strncmp(tptr + 1, HTTP_200, 5) == 0)
1655                 http_major_version = (tptr[6] - '0');
1656         *tptr = '\0';
1657
1658         /* Copy URL from after "GET "/"POST " to stack-allocated char[] */
1659         urlcopy = alloca((tptr - urlp) + sizeof("/index.html"));
1660         /*if (urlcopy == NULL)
1661          *      send_headers_and_exit(HTTP_INTERNAL_SERVER_ERROR);*/
1662         strcpy(urlcopy, urlp);
1663         /* NB: urlcopy ptr is never changed after this */
1664
1665         /* Extract url args if present */
1666         tptr = strchr(urlcopy, '?');
1667         g_query = NULL;
1668         if (tptr) {
1669                 *tptr++ = '\0';
1670                 g_query = tptr;
1671         }
1672
1673         /* Decode URL escape sequences */
1674         tptr = decodeString(urlcopy, 0);
1675         if (tptr == NULL)
1676                 send_headers_and_exit(HTTP_BAD_REQUEST);
1677         if (tptr == urlcopy + 1) {
1678                 /* '/' or NUL is encoded */
1679                 send_headers_and_exit(HTTP_NOT_FOUND);
1680         }
1681
1682         /* Canonicalize path */
1683         /* Algorithm stolen from libbb bb_simplify_path(),
1684          * but don't strdup and reducing trailing slash and protect out root */
1685         urlp = tptr = urlcopy;
1686         do {
1687                 if (*urlp == '/') {
1688                         /* skip duplicate (or initial) slash */
1689                         if (*tptr == '/') {
1690                                 continue;
1691                         }
1692                         if (*tptr == '.') {
1693                                 /* skip extra '.' */
1694                                 if (tptr[1] == '/' || !tptr[1]) {
1695                                         continue;
1696                                 }
1697                                 /* '..': be careful */
1698                                 if (tptr[1] == '.' && (tptr[2] == '/' || !tptr[2])) {
1699                                         ++tptr;
1700                                         if (urlp == urlcopy) /* protect root */
1701                                                 send_headers_and_exit(HTTP_BAD_REQUEST);
1702                                         while (*--urlp != '/') /* omit previous dir */;
1703                                                 continue;
1704                                 }
1705                         }
1706                 }
1707                 *++urlp = *tptr;
1708         } while (*++tptr);
1709         *++urlp = '\0';       /* so keep last character */
1710         tptr = urlp;          /* end ptr */
1711
1712         /* If URL is a directory, add '/' */
1713         if (tptr[-1] != '/') {
1714                 if (is_directory(urlcopy + 1, 1, &sb)) {
1715                         found_moved_temporarily = urlcopy;
1716                 }
1717         }
1718
1719         /* Log it */
1720         if (verbose > 1)
1721                 bb_error_msg("url:%s", urlcopy);
1722
1723         tptr = urlcopy;
1724         ip_allowed = checkPermIP();
1725         while (ip_allowed && (tptr = strchr(tptr + 1, '/')) != NULL) {
1726                 /* have path1/path2 */
1727                 *tptr = '\0';
1728                 if (is_directory(urlcopy + 1, 1, &sb)) {
1729                         /* may be having subdir config */
1730                         parse_conf(urlcopy + 1, SUBDIR_PARSE);
1731                         ip_allowed = checkPermIP();
1732                 }
1733                 *tptr = '/';
1734         }
1735         if (http_major_version >= 0) {
1736                 /* Request was with "... HTTP/nXXX", and n >= 0 */
1737
1738                 /* Read until blank line for HTTP version specified, else parse immediate */
1739                 while (1) {
1740                         alarm(HEADER_READ_TIMEOUT);
1741                         if (!get_line())
1742                                 break; /* EOF or error or empty line */
1743                         if (DEBUG)
1744                                 bb_error_msg("header: '%s'", iobuf);
1745
1746 #if ENABLE_FEATURE_HTTPD_CGI
1747                         /* try and do our best to parse more lines */
1748                         if ((STRNCASECMP(iobuf, "Content-length:") == 0)) {
1749                                 /* extra read only for POST */
1750                                 if (prequest != request_GET) {
1751                                         tptr = iobuf + sizeof("Content-length:") - 1;
1752                                         if (!tptr[0])
1753                                                 send_headers_and_exit(HTTP_BAD_REQUEST);
1754                                         errno = 0;
1755                                         /* not using strtoul: it ignores leading minus! */
1756                                         length = strtol(tptr, &tptr, 10);
1757                                         /* length is "ulong", but we need to pass it to int later */
1758                                         /* so we check for negative or too large values in one go: */
1759                                         /* (long -> ulong conv caused negatives to be seen as > INT_MAX) */
1760                                         if (tptr[0] || errno || length > INT_MAX)
1761                                                 send_headers_and_exit(HTTP_BAD_REQUEST);
1762                                 }
1763                         } else if (STRNCASECMP(iobuf, "Cookie:") == 0) {
1764                                 cookie = strdup(skip_whitespace(iobuf + sizeof("Cookie:")-1));
1765                         } else if (STRNCASECMP(iobuf, "Content-Type:") == 0) {
1766                                 content_type = strdup(skip_whitespace(iobuf + sizeof("Content-Type:")-1));
1767                         } else if (STRNCASECMP(iobuf, "Referer:") == 0) {
1768                                 referer = strdup(skip_whitespace(iobuf + sizeof("Referer:")-1));
1769                         } else if (STRNCASECMP(iobuf, "User-Agent:") == 0) {
1770                                 user_agent = strdup(skip_whitespace(iobuf + sizeof("User-Agent:")-1));
1771                         }
1772 #endif
1773 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1774                         if (STRNCASECMP(iobuf, "Authorization:") == 0) {
1775                                 /* We only allow Basic credentials.
1776                                  * It shows up as "Authorization: Basic <userid:password>" where
1777                                  * the userid:password is base64 encoded.
1778                                  */
1779                                 tptr = skip_whitespace(iobuf + sizeof("Authorization:")-1);
1780                                 if (STRNCASECMP(tptr, "Basic") != 0)
1781                                         continue;
1782                                 tptr += sizeof("Basic")-1;
1783                                 /* decodeBase64() skips whitespace itself */
1784                                 decodeBase64(tptr);
1785                                 credentials = checkPerm(urlcopy, tptr);
1786                         }
1787 #endif          /* FEATURE_HTTPD_BASIC_AUTH */
1788                 } /* while extra header reading */
1789         }
1790
1791         /* We read headers, disable peer timeout */
1792         alarm(0);
1793
1794         if (strcmp(bb_basename(urlcopy), httpd_conf) == 0 || ip_allowed == 0) {
1795                 /* protect listing [/path]/httpd_conf or IP deny */
1796                 send_headers_and_exit(HTTP_FORBIDDEN);
1797         }
1798
1799 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1800         if (credentials <= 0 && checkPerm(urlcopy, ":") == 0) {
1801                 send_headers_and_exit(HTTP_UNAUTHORIZED);
1802         }
1803 #endif
1804
1805         if (found_moved_temporarily) {
1806                 send_headers_and_exit(HTTP_MOVED_TEMPORARILY);
1807         }
1808
1809         tptr = urlcopy + 1;      /* skip first '/' */
1810
1811 #if ENABLE_FEATURE_HTTPD_CGI
1812         if (strncmp(tptr, "cgi-bin/", 8) == 0) {
1813                 if (tptr[8] == '\0') {
1814                         /* protect listing "cgi-bin/" */
1815                         send_headers_and_exit(HTTP_FORBIDDEN);
1816                 }
1817                 send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1818         }
1819 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR
1820         {
1821                 char *suffix = strrchr(tptr, '.');
1822                 if (suffix) {
1823                         Htaccess *cur;
1824                         for (cur = script_i; cur; cur = cur->next) {
1825                                 if (strcmp(cur->before_colon + 1, suffix) == 0) {
1826                                         send_cgi_and_exit(urlcopy, prequest, length, cookie, content_type);
1827                                 }
1828                         }
1829                 }
1830         }
1831 #endif
1832         if (prequest != request_GET) {
1833                 send_headers_and_exit(HTTP_NOT_IMPLEMENTED);
1834         }
1835 #endif  /* FEATURE_HTTPD_CGI */
1836
1837         if (urlp[-1] == '/')
1838                 strcpy(urlp, "index.html");
1839         if (stat(tptr, &sb) == 0) {
1840                 /* It's a dir URL and there is index.html */
1841                 ContentLength = sb.st_size;
1842                 last_mod = sb.st_mtime;
1843         }
1844 #if ENABLE_FEATURE_HTTPD_CGI
1845         else if (urlp[-1] == '/') {
1846                 /* It's a dir URL and there is no index.html
1847                  * Try cgi-bin/index.cgi */
1848                 if (access("/cgi-bin/index.cgi"+1, X_OK) == 0) {
1849                         urlp[0] = '\0';
1850                         g_query = urlcopy;
1851                         send_cgi_and_exit("/cgi-bin/index.cgi", prequest, length, cookie, content_type);
1852                 }
1853         }
1854 #endif
1855         /* else {
1856          *      fall through to send_file, it errors out if open fails
1857          * }
1858          */
1859
1860         send_file_and_exit(tptr, TRUE);
1861 }
1862
1863 /*
1864  * The main http server function.
1865  * Given a socket, listen for new connections and farm out
1866  * the processing as a [v]forked process.
1867  * Never returns.
1868  */
1869 #if BB_MMU
1870 static void mini_httpd(int server_socket) ATTRIBUTE_NORETURN;
1871 static void mini_httpd(int server_socket)
1872 {
1873         /* NB: it's best to not use xfuncs in this loop before fork().
1874          * Otherwise server may die on transient errors (temporary
1875          * out-of-memory condition, etc), which is Bad(tm).
1876          * Try to do any dangerous calls after fork.
1877          */
1878         while (1) {
1879                 int n;
1880                 len_and_sockaddr fromAddr;
1881                 
1882                 /* Wait for connections... */
1883                 fromAddr.len = LSA_SIZEOF_SA;
1884                 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1885
1886                 if (n < 0)
1887                         continue;
1888                 /* set the KEEPALIVE option to cull dead connections */
1889                 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1890
1891                 if (fork() == 0) {
1892                         /* child */
1893 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1894                         /* Do not reload config on HUP */
1895                         signal(SIGHUP, SIG_IGN);
1896 #endif
1897                         close(server_socket);
1898                         xmove_fd(n, 0);
1899                         xdup2(0, 1);
1900
1901                         handle_incoming_and_exit(&fromAddr);
1902                 }
1903                 /* parent, or fork failed */
1904                 close(n);
1905         } /* while (1) */
1906         /* never reached */
1907 }
1908 #else
1909 static void mini_httpd_nommu(int server_socket, int argc, char **argv) ATTRIBUTE_NORETURN;
1910 static void mini_httpd_nommu(int server_socket, int argc, char **argv)
1911 {
1912         char *argv_copy[argc + 2];
1913
1914         argv_copy[0] = argv[0];
1915         argv_copy[1] = (char*)"-i";
1916         memcpy(&argv_copy[2], &argv[1], argc * sizeof(argv[0]));
1917
1918         /* NB: it's best to not use xfuncs in this loop before vfork().
1919          * Otherwise server may die on transient errors (temporary
1920          * out-of-memory condition, etc), which is Bad(tm).
1921          * Try to do any dangerous calls after fork.
1922          */
1923         while (1) {
1924                 int n;
1925                 len_and_sockaddr fromAddr;
1926                 
1927                 /* Wait for connections... */
1928                 fromAddr.len = LSA_SIZEOF_SA;
1929                 n = accept(server_socket, &fromAddr.sa, &fromAddr.len);
1930
1931                 if (n < 0)
1932                         continue;
1933                 /* set the KEEPALIVE option to cull dead connections */
1934                 setsockopt(n, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
1935
1936                 if (vfork() == 0) {
1937                         /* child */
1938 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1939                         /* Do not reload config on HUP */
1940                         signal(SIGHUP, SIG_IGN);
1941 #endif
1942                         close(server_socket);
1943                         xmove_fd(n, 0);
1944                         xdup2(0, 1);
1945
1946                         /* Run a copy of ourself in inetd mode */
1947                         re_exec(argv_copy);
1948                 }
1949                 /* parent, or vfork failed */
1950                 close(n);
1951         } /* while (1) */
1952         /* never reached */
1953 }
1954 #endif
1955
1956 /*
1957  * Process a HTTP connection on stdin/out.
1958  * Never returns.
1959  */
1960 static void mini_httpd_inetd(void) ATTRIBUTE_NORETURN;
1961 static void mini_httpd_inetd(void)
1962 {
1963         len_and_sockaddr fromAddr;
1964
1965         fromAddr.len = LSA_SIZEOF_SA;
1966         getpeername(0, &fromAddr.sa, &fromAddr.len);
1967         handle_incoming_and_exit(&fromAddr);
1968 }
1969
1970 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1971 static void sighup_handler(int sig)
1972 {
1973         struct sigaction sa;
1974
1975         parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1976
1977         memset(&sa, 0, sizeof(sa));
1978         sa.sa_handler = sighup_handler;
1979         /*sigemptyset(&sa.sa_mask); - memset should be enough */
1980         sa.sa_flags = SA_RESTART;
1981         sigaction(SIGHUP, &sa, NULL);
1982 }
1983 #endif
1984
1985 enum {
1986         c_opt_config_file = 0,
1987         d_opt_decode_url,
1988         h_opt_home_httpd,
1989         USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1990         USE_FEATURE_HTTPD_BASIC_AUTH(    r_opt_realm     ,)
1991         USE_FEATURE_HTTPD_AUTH_MD5(      m_opt_md5       ,)
1992         USE_FEATURE_HTTPD_SETUID(        u_opt_setuid    ,)
1993         p_opt_port      ,
1994         p_opt_inetd     ,
1995         p_opt_foreground,
1996         p_opt_verbose   ,
1997         OPT_CONFIG_FILE = 1 << c_opt_config_file,
1998         OPT_DECODE_URL  = 1 << d_opt_decode_url,
1999         OPT_HOME_HTTPD  = 1 << h_opt_home_httpd,
2000         OPT_ENCODE_URL  = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
2001         OPT_REALM       = USE_FEATURE_HTTPD_BASIC_AUTH(    (1 << r_opt_realm     )) + 0,
2002         OPT_MD5         = USE_FEATURE_HTTPD_AUTH_MD5(      (1 << m_opt_md5       )) + 0,
2003         OPT_SETUID      = USE_FEATURE_HTTPD_SETUID(        (1 << u_opt_setuid    )) + 0,
2004         OPT_PORT        = 1 << p_opt_port,
2005         OPT_INETD       = 1 << p_opt_inetd,
2006         OPT_FOREGROUND  = 1 << p_opt_foreground,
2007         OPT_VERBOSE     = 1 << p_opt_verbose,
2008 };
2009
2010
2011 int httpd_main(int argc, char **argv);
2012 int httpd_main(int argc, char **argv)
2013 {
2014         int server_socket = server_socket; /* for gcc */
2015         unsigned opt;
2016         char *url_for_decode;
2017         USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
2018         USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
2019         USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
2020         USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
2021
2022         INIT_G();
2023
2024 #if ENABLE_LOCALE_SUPPORT
2025         /* Undo busybox.c: we want to speak English in http (dates etc) */
2026         setlocale(LC_TIME, "C");
2027 #endif
2028
2029         home_httpd = xrealloc_getcwd_or_warn(NULL);
2030         /* -v counts, -i implies -f */
2031         opt_complementary = "vv:if";
2032         /* We do not "absolutize" path given by -h (home) opt.
2033          * If user gives relative path in -h, $SCRIPT_FILENAME can end up
2034          * relative too. */
2035         opt = getopt32(argv, "c:d:h:"
2036                         USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
2037                         USE_FEATURE_HTTPD_BASIC_AUTH("r:")
2038                         USE_FEATURE_HTTPD_AUTH_MD5("m:")
2039                         USE_FEATURE_HTTPD_SETUID("u:")
2040                         "p:ifv",
2041                         &configFile, &url_for_decode, &home_httpd
2042                         USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
2043                         USE_FEATURE_HTTPD_BASIC_AUTH(, &g_realm)
2044                         USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
2045                         USE_FEATURE_HTTPD_SETUID(, &s_ugid)
2046                         , &bind_addr_or_port
2047                         , &verbose
2048                 );
2049         if (opt & OPT_DECODE_URL) {
2050                 fputs(decodeString(url_for_decode, 1), stdout);
2051                 return 0;
2052         }
2053 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
2054         if (opt & OPT_ENCODE_URL) {
2055                 fputs(encodeString(url_for_encode), stdout);
2056                 return 0;
2057         }
2058 #endif
2059 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
2060         if (opt & OPT_MD5) {
2061                 puts(pw_encrypt(pass, "$1$"));
2062                 return 0;
2063         }
2064 #endif
2065 #if ENABLE_FEATURE_HTTPD_SETUID
2066         if (opt & OPT_SETUID) {
2067                 if (!get_uidgid(&ugid, s_ugid, 1))
2068                         bb_error_msg_and_die("unrecognized user[:group] "
2069                                                 "name '%s'", s_ugid);
2070         }
2071 #endif
2072
2073 #if !BB_MMU
2074         if (!(opt & OPT_FOREGROUND)) {
2075                 bb_daemonize_or_rexec(0, argv); /* don't change current directory */
2076         }
2077 #endif
2078
2079         xchdir(home_httpd);
2080         if (!(opt & OPT_INETD)) {
2081                 signal(SIGCHLD, SIG_IGN);
2082                 server_socket = openServer();
2083 #if ENABLE_FEATURE_HTTPD_SETUID
2084                 /* drop privileges */
2085                 if (opt & OPT_SETUID) {
2086                         if (ugid.gid != (gid_t)-1) {
2087                                 if (setgroups(1, &ugid.gid) == -1)
2088                                         bb_perror_msg_and_die("setgroups");
2089                                 xsetgid(ugid.gid);
2090                         }
2091                         xsetuid(ugid.uid);
2092                 }
2093 #endif
2094         }
2095
2096 #if ENABLE_FEATURE_HTTPD_CGI
2097         {
2098                 char *p = getenv("PATH");
2099                 /* env strings themself are not freed, no need to strdup(p): */
2100                 clearenv();
2101                 if (p)
2102                         putenv(p - 5);
2103 //              if (!(opt & OPT_INETD))
2104 //                      setenv_long("SERVER_PORT", ???);
2105         }
2106 #endif
2107
2108 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
2109         if (!(opt & OPT_INETD))
2110                 sighup_handler(0);
2111         else /* do not install HUP handler in inetd mode */
2112 #endif
2113                 parse_conf(default_path_httpd_conf, FIRST_PARSE);
2114
2115         xfunc_error_retval = 0;
2116         if (opt & OPT_INETD)
2117                 mini_httpd_inetd();
2118 #if BB_MMU
2119         if (!(opt & OPT_FOREGROUND))
2120                 bb_daemonize(0); /* don't change current directory */
2121         mini_httpd(server_socket); /* never returns */
2122 #else
2123         mini_httpd_nommu(server_socket, argc, argv); /* never returns */
2124 #endif
2125         /* return 0; */
2126 }