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