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