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