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