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