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