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