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