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