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