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