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