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