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