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