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