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