c0b740f6ff3890b22dbeb017d2acc60709d0f531
[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          /* CONFIG_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")); /* Huh?? */
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
1149                                         if (WIFEXITED(status))
1150                                                 bb_error_msg("piped has exited with status=%d", WEXITSTATUS(status));
1151                                         if (WIFSIGNALED(status))
1152                                                 bb_error_msg("piped has exited with signal=%d", WTERMSIG(status));
1153 #endif
1154                                         break;
1155                                 }
1156                         } else if (post_readed_size > 0 && FD_ISSET(outFd, &writeSet)) {
1157                                 count = full_write(outFd, wbuf + post_readed_idx, post_readed_size);
1158                                 if (count > 0) {
1159                                         post_readed_size -= count;
1160                                         post_readed_idx += count;
1161                                         if (post_readed_size == 0)
1162                                                 post_readed_idx = 0;
1163                                 } else {
1164                                         post_readed_size = post_readed_idx = bodyLen = 0; /* broken pipe to CGI */
1165                                 }
1166                         } else if (bodyLen > 0 && post_readed_size == 0 && FD_ISSET(config->accepted_socket, &readSet)) {
1167                                 count = bodyLen > (int)sizeof(wbuf) ? (int)sizeof(wbuf) : bodyLen;
1168                                 count = safe_read(config->accepted_socket, wbuf, count);
1169                                 if (count > 0) {
1170                                         post_readed_size += count;
1171                                         bodyLen -= count;
1172                                 } else {
1173                                         bodyLen = 0;    /* closed */
1174                                 }
1175                         }
1176                         if (FD_ISSET(inFd, &readSet)) {
1177                                 int s = config->accepted_socket;
1178                                 char *rbuf = config->buf;
1179
1180 #ifndef PIPE_BUF
1181 # define PIPESIZE 4096          /* amount of buffering in a pipe */
1182 #else
1183 # define PIPESIZE PIPE_BUF
1184 #endif
1185 #if PIPESIZE >= MAX_MEMORY_BUFF
1186 # error "PIPESIZE >= MAX_MEMORY_BUFF"
1187 #endif
1188
1189                                 // There is something to read
1190                                 count = safe_read(inFd, rbuf, PIPESIZE);
1191                                 if (count == 0)
1192                                         break;  /* closed */
1193                                 if (count > 0) {
1194                                         if (firstLine) {
1195                                                 rbuf[count] = 0;
1196                                                 /* check to see if the user script added headers */
1197                                                 if (strncmp(rbuf, "HTTP/1.0 200 OK\r\n", 4) != 0) {
1198                                                         full_write(s, "HTTP/1.0 200 OK\r\n", 17);
1199                                                 }
1200                                                 if (strstr(rbuf, "ontent-") == 0) {
1201                                                         full_write(s, "Content-type: text/plain\r\n\r\n", 28);
1202                                                 }
1203                                                 firstLine = 0;
1204                                         }
1205                                         if (full_write(s, rbuf, count) != count)
1206                                                 break;
1207
1208 #if DEBUG
1209                                         fprintf(stderr, "cgi read %d bytes\n", count);
1210 #endif
1211                                 }
1212                         }
1213                 }
1214         }
1215         return 0;
1216 }
1217 #endif          /* CONFIG_FEATURE_HTTPD_CGI */
1218
1219 /****************************************************************************
1220  *
1221  > $Function: sendFile()
1222  *
1223  * $Description: Send a file response to a HTTP request
1224  *
1225  * $Parameter:
1226  *      (const char *) url . . The URL requested.
1227  *
1228  * $Return: (int)  . . . . . . Always 0.
1229  *
1230  ****************************************************************************/
1231 static int sendFile(const char *url)
1232 {
1233         char * suffix;
1234         int  f;
1235         const char * const * table;
1236         const char * try_suffix;
1237
1238         suffix = strrchr(url, '.');
1239
1240         for (table = suffixTable; *table; table += 2)
1241                 if (suffix != NULL && (try_suffix = strstr(*table, suffix)) != 0) {
1242                         try_suffix += strlen(suffix);
1243                         if (*try_suffix == 0 || *try_suffix == '.')
1244                                 break;
1245                 }
1246         /* also, if not found, set default as "application/octet-stream";  */
1247         config->found_mime_type = table[1];
1248 #if ENABLE_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES
1249         if (suffix) {
1250                 Htaccess * cur;
1251
1252                 for (cur = config->mime_a; cur; cur = cur->next) {
1253                         if (strcmp(cur->before_colon, suffix) == 0) {
1254                                 config->found_mime_type = cur->after_colon;
1255                                 break;
1256                         }
1257                 }
1258         }
1259 #endif  /* CONFIG_FEATURE_HTTPD_CONFIG_WITH_MIME_TYPES */
1260
1261 #if DEBUG
1262         fprintf(stderr, "sending file '%s' content-type: %s\n",
1263                         url, config->found_mime_type);
1264 #endif
1265
1266         f = open(url, O_RDONLY);
1267         if (f >= 0) {
1268                 int count;
1269                 char *buf = config->buf;
1270
1271                 sendHeaders(HTTP_OK);
1272                 while ((count = full_read(f, buf, MAX_MEMORY_BUFF)) > 0) {
1273                         if (full_write(config->accepted_socket, buf, count) != count)
1274                                 break;
1275                 }
1276                 close(f);
1277         } else {
1278 #if DEBUG
1279                 bb_perror_msg("cannot open '%s'", url);
1280 #endif
1281                 sendHeaders(HTTP_NOT_FOUND);
1282         }
1283
1284         return 0;
1285 }
1286
1287 static int checkPermIP(void)
1288 {
1289         Htaccess_IP * cur;
1290
1291         /* This could stand some work */
1292         for (cur = config->ip_a_d; cur; cur = cur->next) {
1293 #if DEBUG
1294                 fprintf(stderr, "checkPermIP: '%s' ? ", config->rmt_ip_str);
1295                 fprintf(stderr, "'%u.%u.%u.%u/%u.%u.%u.%u'\n",
1296                                 (unsigned char)(cur->ip >> 24),
1297                                 (unsigned char)(cur->ip >> 16),
1298                                 (unsigned char)(cur->ip >> 8),
1299                                                     cur->ip & 0xff,
1300                                 (unsigned char)(cur->mask >> 24),
1301                                 (unsigned char)(cur->mask >> 16),
1302                                 (unsigned char)(cur->mask >> 8),
1303                                                     cur->mask & 0xff);
1304 #endif
1305                 if ((config->rmt_ip & cur->mask) == cur->ip)
1306                         return cur->allow_deny == 'A';   /* Allow/Deny */
1307         }
1308
1309         /* if unconfigured, return 1 - access from all */
1310         return !config->flg_deny_all;
1311 }
1312
1313 /****************************************************************************
1314  *
1315  > $Function: checkPerm()
1316  *
1317  * $Description: Check the permission file for access password protected.
1318  *
1319  *   If config file isn't present, everything is allowed.
1320  *   Entries are of the form you can see example from header source
1321  *
1322  * $Parameters:
1323  *      (const char *) path  . . . . The file path.
1324  *      (const char *) request . . . User information to validate.
1325  *
1326  * $Return: (int)  . . . . . . . . . 1 if request OK, 0 otherwise.
1327  *
1328  ****************************************************************************/
1329
1330 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1331 static int checkPerm(const char *path, const char *request)
1332 {
1333         Htaccess * cur;
1334         const char *p;
1335         const char *p0;
1336
1337         const char *prev = NULL;
1338
1339         /* This could stand some work */
1340         for (cur = config->auth; cur; cur = cur->next) {
1341                 p0 = cur->before_colon;
1342                 if (prev != NULL && strcmp(prev, p0) != 0)
1343                         continue;       /* find next identical */
1344                 p = cur->after_colon;
1345 #if DEBUG
1346                 fprintf(stderr, "checkPerm: '%s' ? '%s'\n", p0, request);
1347 #endif
1348                 {
1349                         size_t l = strlen(p0);
1350
1351                         if (strncmp(p0, path, l) == 0 &&
1352                                             (l == 1 || path[l] == '/' || path[l] == 0)) {
1353                                 char *u;
1354                                 /* path match found.  Check request */
1355                                 /* for check next /path:user:password */
1356                                 prev = p0;
1357                                 u = strchr(request, ':');
1358                                 if (u == NULL) {
1359                                         /* bad request, ':' required */
1360                                         break;
1361                                 }
1362
1363 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1364                                 {
1365                                         char *cipher;
1366                                         char *pp;
1367
1368                                 if (strncmp(p, request, u-request) != 0) {
1369                                                 /* user uncompared */
1370                                                 continue;
1371                                         }
1372                                         pp = strchr(p, ':');
1373                                         if (pp && pp[1] == '$' && pp[2] == '1' &&
1374                                                         pp[3] == '$' && pp[4]) {
1375                                                 pp++;
1376                                                 cipher = pw_encrypt(u+1, pp);
1377                                                 if (strcmp(cipher, pp) == 0)
1378                                                         goto set_remoteuser_var;   /* Ok */
1379                                                 /* unauthorized */
1380                                                 continue;
1381                                         }
1382                                 }
1383 #endif
1384                                 if (strcmp(p, request) == 0) {
1385 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1386 set_remoteuser_var:
1387 #endif
1388                                         config->remoteuser = strdup(request);
1389                                         if (config->remoteuser)
1390                                                 config->remoteuser[(u - request)] = 0;
1391                                         return 1;   /* Ok */
1392                                 }
1393                                 /* unauthorized */
1394                         }
1395                 }
1396         }   /* for */
1397
1398         return prev == NULL;
1399 }
1400
1401 #endif  /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1402
1403 /****************************************************************************
1404  *
1405  > $Function: handle_sigalrm()
1406  *
1407  * $Description: Handle timeouts
1408  *
1409  ****************************************************************************/
1410
1411 static void handle_sigalrm(int sig)
1412 {
1413         sendHeaders(HTTP_REQUEST_TIMEOUT);
1414         config->alarm_signaled = sig;
1415 }
1416
1417 /****************************************************************************
1418  *
1419  > $Function: handleIncoming()
1420  *
1421  * $Description: Handle an incoming http request.
1422  *
1423  ****************************************************************************/
1424 static void handleIncoming(void)
1425 {
1426         char *buf = config->buf;
1427         char *url;
1428         char *purl;
1429         int  blank = -1;
1430         char *test;
1431         struct stat sb;
1432         int ip_allowed;
1433 #if ENABLE_FEATURE_HTTPD_CGI
1434         const char *prequest = request_GET;
1435         long length = 0;
1436         char *cookie = 0;
1437         char *content_type = 0;
1438 #endif
1439         fd_set s_fd;
1440         struct timeval tv;
1441         int retval;
1442         struct sigaction sa;
1443
1444 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1445         int credentials = -1;  /* if not required this is Ok */
1446 #endif
1447
1448         sa.sa_handler = handle_sigalrm;
1449         sigemptyset(&sa.sa_mask);
1450         sa.sa_flags = 0; /* no SA_RESTART */
1451         sigaction(SIGALRM, &sa, NULL);
1452
1453         do {
1454                 int count;
1455
1456                 (void) alarm(TIMEOUT);
1457                 if (getLine() <= 0)
1458                         break;  /* closed */
1459
1460                 purl = strpbrk(buf, " \t");
1461                 if (purl == NULL) {
1462 BAD_REQUEST:
1463                         sendHeaders(HTTP_BAD_REQUEST);
1464                         break;
1465                 }
1466                 *purl = 0;
1467 #if ENABLE_FEATURE_HTTPD_CGI
1468                 if (strcasecmp(buf, prequest) != 0) {
1469                         prequest = "POST";
1470                         if (strcasecmp(buf, prequest) != 0) {
1471                                 sendHeaders(HTTP_NOT_IMPLEMENTED);
1472                                 break;
1473                         }
1474                 }
1475 #else
1476                 if (strcasecmp(buf, request_GET) != 0) {
1477                         sendHeaders(HTTP_NOT_IMPLEMENTED);
1478                         break;
1479                 }
1480 #endif
1481                 *purl = ' ';
1482                 count = sscanf(purl, " %[^ ] HTTP/%d.%*d", buf, &blank);
1483
1484                 if (count < 1 || buf[0] != '/') {
1485                         /* Garbled request/URL */
1486                         goto BAD_REQUEST;
1487                 }
1488                 url = alloca(strlen(buf) + sizeof("/index.html"));
1489                 if (url == NULL) {
1490                         sendHeaders(HTTP_INTERNAL_SERVER_ERROR);
1491                         break;
1492                 }
1493                 strcpy(url, buf);
1494                 /* extract url args if present */
1495                 test = strchr(url, '?');
1496                 if (test) {
1497                         *test++ = 0;
1498                         config->query = test;
1499                 }
1500
1501                 test = decodeString(url, 0);
1502                 if (test == NULL)
1503                         goto BAD_REQUEST;
1504                 if (test == (buf+1)) {
1505                         sendHeaders(HTTP_NOT_FOUND);
1506                         break;
1507                 }
1508                 /* algorithm stolen from libbb bb_simplify_path(),
1509                          but don't strdup and reducing trailing slash and protect out root */
1510                 purl = test = url;
1511
1512                 do {
1513                         if (*purl == '/') {
1514                                 if (*test == '/') {        /* skip duplicate (or initial) slash */
1515                                         continue;
1516                                 } else if (*test == '.') {
1517                                         if (test[1] == '/' || test[1] == 0) { /* skip extra '.' */
1518                                                 continue;
1519                                         } else if ((test[1] == '.') && (test[2] == '/' || test[2] == 0)) {
1520                                                 ++test;
1521                                                 if (purl == url) {
1522                                                         /* protect out root */
1523                                                         goto BAD_REQUEST;
1524                                                 }
1525                                                 while (*--purl != '/') /* omit previous dir */;
1526                                                 continue;
1527                                         }
1528                                 }
1529                         }
1530                         *++purl = *test;
1531                 } while (*++test);
1532
1533                 *++purl = 0;        /* so keep last character */
1534                 test = purl;        /* end ptr */
1535
1536                 /* If URL is directory, adding '/' */
1537                 if (test[-1] != '/') {
1538                         if (is_directory(url + 1, 1, &sb)) {
1539                                 config->found_moved_temporarily = url;
1540                         }
1541                 }
1542 #if DEBUG
1543                 fprintf(stderr, "url='%s', args=%s\n", url, config->query);
1544 #endif
1545
1546                 test = url;
1547                 ip_allowed = checkPermIP();
1548                 while (ip_allowed && (test = strchr(test + 1, '/')) != NULL) {
1549                         /* have path1/path2 */
1550                         *test = '\0';
1551                         if (is_directory(url + 1, 1, &sb)) {
1552                                 /* may be having subdir config */
1553                                 parse_conf(url + 1, SUBDIR_PARSE);
1554                                 ip_allowed = checkPermIP();
1555                         }
1556                         *test = '/';
1557                 }
1558                 if (blank >= 0) {
1559                         // read until blank line for HTTP version specified, else parse immediate
1560                         while (1) {
1561                                 alarm(TIMEOUT);
1562                                 count = getLine();
1563                                 if (count <= 0)
1564                                         break;
1565
1566 #if DEBUG
1567                                 fprintf(stderr, "Header: '%s'\n", buf);
1568 #endif
1569
1570 #if ENABLE_FEATURE_HTTPD_CGI
1571                                 /* try and do our best to parse more lines */
1572                                 if ((strncasecmp(buf, Content_length, 15) == 0)) {
1573                                         if (prequest != request_GET)
1574                                                 length = strtol(buf + 15, 0, 0); // extra read only for POST
1575                                 } else if ((strncasecmp(buf, "Cookie:", 7) == 0)) {
1576                                         for (test = buf + 7; isspace(*test); test++)
1577                                                   ;
1578                                         cookie = strdup(test);
1579                                 } else if ((strncasecmp(buf, "Content-Type:", 13) == 0)) {
1580                                         for (test = buf + 13; isspace(*test); test++)
1581                                                   ;
1582                                         content_type = strdup(test);
1583                                 } else if ((strncasecmp(buf, "Referer:", 8) == 0)) {
1584                                         for (test = buf + 8; isspace(*test); test++)
1585                                                   ;
1586                                         config->referer = strdup(test);
1587                                 }
1588 #endif
1589
1590 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1591                                 if (strncasecmp(buf, "Authorization:", 14) == 0) {
1592                                         /* We only allow Basic credentials.
1593                                          * It shows up as "Authorization: Basic <userid:password>" where
1594                                          * the userid:password is base64 encoded.
1595                                          */
1596                                         for (test = buf + 14; isspace(*test); test++)
1597                                                 ;
1598                                         if (strncasecmp(test, "Basic", 5) != 0)
1599                                                 continue;
1600
1601                                         test += 5;  /* decodeBase64() skiping space self */
1602                                         decodeBase64(test);
1603                                         credentials = checkPerm(url, test);
1604                                 }
1605 #endif          /* CONFIG_FEATURE_HTTPD_BASIC_AUTH */
1606
1607                         } /* while extra header reading */
1608                 }
1609                 (void) alarm(0);
1610                 if (config->alarm_signaled)
1611                         break;
1612
1613                 if (strcmp(strrchr(url, '/') + 1, httpd_conf) == 0 || ip_allowed == 0) {
1614                                 /* protect listing [/path]/httpd_conf or IP deny */
1615 #if ENABLE_FEATURE_HTTPD_CGI
1616 FORBIDDEN:      /* protect listing /cgi-bin */
1617 #endif
1618                         sendHeaders(HTTP_FORBIDDEN);
1619                         break;
1620                 }
1621
1622 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1623                 if (credentials <= 0 && checkPerm(url, ":") == 0) {
1624                         sendHeaders(HTTP_UNAUTHORIZED);
1625                         break;
1626                 }
1627 #endif
1628
1629                 if (config->found_moved_temporarily) {
1630                         sendHeaders(HTTP_MOVED_TEMPORARILY);
1631                         /* clear unforked memory flag */
1632                         config->found_moved_temporarily = NULL;
1633                         break;
1634                 }
1635
1636                 test = url + 1;      /* skip first '/' */
1637
1638 #if ENABLE_FEATURE_HTTPD_CGI
1639                 /* if strange Content-Length */
1640                 if (length < 0)
1641                         break;
1642
1643                 if (strncmp(test, "cgi-bin", 7) == 0) {
1644                         if (test[7] == '/' && test[8] == 0)
1645                                 goto FORBIDDEN;     // protect listing cgi-bin/
1646                         sendCgi(url, prequest, length, cookie, content_type);
1647                 } else {
1648                         if (prequest != request_GET)
1649                                 sendHeaders(HTTP_NOT_IMPLEMENTED);
1650                         else {
1651 #endif  /* CONFIG_FEATURE_HTTPD_CGI */
1652                                 if (purl[-1] == '/')
1653                                         strcpy(purl, "index.html");
1654                                 if (stat(test, &sb) == 0) {
1655                                         config->ContentLength = sb.st_size;
1656                                         config->last_mod = sb.st_mtime;
1657                                 }
1658                                 sendFile(test);
1659                                 config->ContentLength = -1;
1660 #if ENABLE_FEATURE_HTTPD_CGI
1661                         }
1662                 }
1663 #endif
1664         } while (0);
1665
1666 # if DEBUG
1667         fprintf(stderr, "closing socket\n\n");
1668 # endif
1669 # if ENABLE_FEATURE_HTTPD_CGI
1670         free(cookie);
1671         free(content_type);
1672         free(config->referer); config->referer = NULL;
1673 #  if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1674         free(config->remoteuser); config->remoteuser = NULL;
1675 #  endif
1676 # endif
1677         shutdown(config->accepted_socket, SHUT_WR);
1678
1679         /* Properly wait for remote to closed */
1680         FD_ZERO(&s_fd);
1681         FD_SET(config->accepted_socket, &s_fd);
1682
1683         do {
1684                 tv.tv_sec = 2;
1685                 tv.tv_usec = 0;
1686                 retval = select(config->accepted_socket + 1, &s_fd, NULL, NULL, &tv);
1687         } while (retval > 0 && read(config->accepted_socket, buf, sizeof(config->buf) > 0));
1688
1689         shutdown(config->accepted_socket, SHUT_RD);
1690         /* In inetd case, we close fd 1 (stdout) here. We will exit soon anyway */
1691         close(config->accepted_socket);
1692 }
1693
1694 /****************************************************************************
1695  *
1696  > $Function: miniHttpd()
1697  *
1698  * $Description: The main http server function.
1699  *
1700  *   Given an open socket fildes, listen for new connections and farm out
1701  *   the processing as a forked process.
1702  *
1703  * $Parameters:
1704  *      (int) server. . . The server socket fildes.
1705  *
1706  * $Return: (int) . . . . Always 0.
1707  *
1708  ****************************************************************************/
1709 static int miniHttpd(int server)
1710 {
1711         fd_set readfd, portfd;
1712
1713         FD_ZERO(&portfd);
1714         FD_SET(server, &portfd);
1715
1716         /* copy the ports we are watching to the readfd set */
1717         while (1) {
1718                 int on, s;
1719                 socklen_t fromAddrLen;
1720                 struct sockaddr_in fromAddr;
1721
1722                 /* Now wait INDEFINITELY on the set of sockets! */
1723                 readfd = portfd;
1724                 if (select(server + 1, &readfd, 0, 0, 0) <= 0)
1725                         continue;
1726                 if (!FD_ISSET(server, &readfd))
1727                         continue;
1728                 fromAddrLen = sizeof(fromAddr);
1729                 s = accept(server, (struct sockaddr *)&fromAddr, &fromAddrLen);
1730                 if (s < 0)
1731                         continue;
1732                 config->accepted_socket = s;
1733                 config->rmt_ip = ntohl(fromAddr.sin_addr.s_addr);
1734 #if ENABLE_FEATURE_HTTPD_CGI || DEBUG
1735                 sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1736                                 (unsigned char)(config->rmt_ip >> 24),
1737                                 (unsigned char)(config->rmt_ip >> 16),
1738                                 (unsigned char)(config->rmt_ip >> 8),
1739                                 config->rmt_ip & 0xff);
1740                 config->port = ntohs(fromAddr.sin_port);
1741 #if DEBUG
1742                 bb_error_msg("connection from IP=%s, port %u",
1743                                 config->rmt_ip_str, config->port);
1744 #endif
1745 #endif /* CONFIG_FEATURE_HTTPD_CGI */
1746
1747                 /* set the KEEPALIVE option to cull dead connections */
1748                 on = 1;
1749                 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on));
1750 #if !DEBUG
1751                 if (fork() == 0)
1752 #endif
1753                 {
1754                         /* This is the spawned thread */
1755 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1756                         /* protect reload config, may be confuse checking */
1757                         signal(SIGHUP, SIG_IGN);
1758 #endif
1759                         handleIncoming();
1760 #if !DEBUG
1761                         exit(0);
1762 #endif
1763                 }
1764                 close(s);
1765         } // while (1)
1766         return 0;
1767 }
1768
1769 /* from inetd */
1770 static int miniHttpd_inetd(void)
1771 {
1772         struct sockaddr_in fromAddrLen;
1773         socklen_t sinlen = sizeof(struct sockaddr_in);
1774
1775         getpeername(0, (struct sockaddr *)&fromAddrLen, &sinlen);
1776         config->rmt_ip = ntohl(fromAddrLen.sin_addr.s_addr);
1777 #if ENABLE_FEATURE_HTTPD_CGI
1778         sprintf(config->rmt_ip_str, "%u.%u.%u.%u",
1779                                 (unsigned char)(config->rmt_ip >> 24),
1780                                 (unsigned char)(config->rmt_ip >> 16),
1781                                 (unsigned char)(config->rmt_ip >> 8),
1782                                                     config->rmt_ip & 0xff);
1783 #endif
1784         config->port = ntohs(fromAddrLen.sin_port);
1785         handleIncoming();
1786         return 0;
1787 }
1788
1789 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1790 static void sighup_handler(int sig)
1791 {
1792         /* set and reset */
1793         struct sigaction sa;
1794
1795         parse_conf(default_path_httpd_conf, sig == SIGHUP ? SIGNALED_PARSE : FIRST_PARSE);
1796         sa.sa_handler = sighup_handler;
1797         sigemptyset(&sa.sa_mask);
1798         sa.sa_flags = SA_RESTART;
1799         sigaction(SIGHUP, &sa, NULL);
1800 }
1801 #endif
1802
1803 enum {
1804         c_opt_config_file = 0,
1805         d_opt_decode_url,
1806         h_opt_home_httpd,
1807         USE_FEATURE_HTTPD_ENCODE_URL_STR(e_opt_encode_url,)
1808         USE_FEATURE_HTTPD_BASIC_AUTH(    r_opt_realm     ,)
1809         USE_FEATURE_HTTPD_AUTH_MD5(      m_opt_md5       ,)
1810         USE_FEATURE_HTTPD_SETUID(        u_opt_setuid    ,)
1811         p_opt_port      ,
1812         p_opt_inetd     ,
1813         p_opt_foreground,
1814         OPT_CONFIG_FILE = 1 << c_opt_config_file,
1815         OPT_DECODE_URL  = 1 << d_opt_decode_url,
1816         OPT_HOME_HTTPD  = 1 << h_opt_home_httpd,
1817         OPT_ENCODE_URL  = USE_FEATURE_HTTPD_ENCODE_URL_STR((1 << e_opt_encode_url)) + 0,
1818         OPT_REALM       = USE_FEATURE_HTTPD_BASIC_AUTH(    (1 << r_opt_realm     )) + 0,
1819         OPT_MD5         = USE_FEATURE_HTTPD_AUTH_MD5(      (1 << m_opt_md5       )) + 0,
1820         OPT_SETUID      = USE_FEATURE_HTTPD_SETUID(        (1 << u_opt_setuid    )) + 0,
1821         OPT_PORT        = 1 << p_opt_port,
1822         OPT_INETD       = 1 << p_opt_inetd,
1823         OPT_FOREGROUND  = 1 << p_opt_foreground,
1824 };
1825
1826 static const char httpd_opts[] = "c:d:h:"
1827         USE_FEATURE_HTTPD_ENCODE_URL_STR("e:")
1828         USE_FEATURE_HTTPD_BASIC_AUTH("r:")
1829         USE_FEATURE_HTTPD_AUTH_MD5("m:")
1830         USE_FEATURE_HTTPD_SETUID("u:")
1831         "p:if";
1832
1833
1834 int httpd_main(int argc, char *argv[])
1835 {
1836         unsigned opt;
1837         const char *home_httpd = home;
1838         char *url_for_decode;
1839         USE_FEATURE_HTTPD_ENCODE_URL_STR(const char *url_for_encode;)
1840         const char *s_port;
1841         USE_FEATURE_HTTPD_SETUID(const char *s_ugid = NULL;)
1842         USE_FEATURE_HTTPD_SETUID(struct bb_uidgid_t ugid;)
1843         USE_FEATURE_HTTPD_AUTH_MD5(const char *pass;)
1844
1845         config = xzalloc(sizeof(*config));
1846 #if ENABLE_FEATURE_HTTPD_BASIC_AUTH
1847         config->realm = "Web Server Authentication";
1848 #endif
1849         config->port = 80;
1850         config->ContentLength = -1;
1851
1852         opt = getopt32(argc, argv, httpd_opts,
1853                         &(config->configFile), &url_for_decode, &home_httpd
1854                         USE_FEATURE_HTTPD_ENCODE_URL_STR(, &url_for_encode)
1855                         USE_FEATURE_HTTPD_BASIC_AUTH(, &(config->realm))
1856                         USE_FEATURE_HTTPD_AUTH_MD5(, &pass)
1857                         USE_FEATURE_HTTPD_SETUID(, &s_ugid)
1858                         , &s_port
1859                 );
1860         if (opt & OPT_DECODE_URL) {
1861                 printf("%s", decodeString(url_for_decode, 1));
1862                 return 0;
1863         }
1864 #if ENABLE_FEATURE_HTTPD_ENCODE_URL_STR
1865         if (opt & OPT_ENCODE_URL) {
1866                 printf("%s", encodeString(url_for_encode));
1867                 return 0;
1868         }
1869 #endif
1870 #if ENABLE_FEATURE_HTTPD_AUTH_MD5
1871         if (opt & OPT_MD5) {
1872                 puts(pw_encrypt(pass, "$1$"));
1873                 return 0;
1874         }
1875 #endif
1876         if (opt & OPT_PORT)
1877                 config->port = xatou16(s_port);
1878
1879 #if ENABLE_FEATURE_HTTPD_SETUID
1880         if (opt & OPT_SETUID) {
1881                 char *e;
1882                 // FIXME: what the default group should be?
1883                 ugid.gid = -1;
1884                 ugid.uid = strtoul(s_ugid, &e, 0);
1885                 if (*e == ':') {
1886                         e++;
1887                         ugid.gid = strtoul(e, &e, 0);
1888                 }
1889                 if (*e != '\0') {
1890                         /* not integer */
1891                         if (!uidgid_get(&ugid, s_ugid))
1892                                 bb_error_msg_and_die("unrecognized user[:group] "
1893                                                 "name '%s'", s_ugid);
1894                 }
1895         }
1896 #endif
1897
1898         xchdir(home_httpd);
1899         if (!(opt & OPT_INETD)) {
1900                 config->server_socket = openServer();
1901 #if ENABLE_FEATURE_HTTPD_SETUID
1902                 /* drop privileges */
1903                 if (opt & OPT_SETUID) {
1904                         if (ugid.gid != (gid_t)-1) {
1905                                 if (setgroups(1, &ugid.gid) == -1)
1906                                         bb_perror_msg_and_die("setgroups");
1907                                 xsetgid(ugid.gid);
1908                         }
1909                         xsetuid(ugid.uid);
1910                 }
1911 #endif
1912         }
1913
1914 #if ENABLE_FEATURE_HTTPD_CGI
1915         {
1916                 char *p = getenv("PATH");
1917                 if (p) {
1918                         p = xstrdup(p);
1919                 }
1920                 clearenv();
1921                 if (p)
1922                         setenv1("PATH", p);
1923                 if (!(opt & OPT_INETD))
1924                         setenv_long("SERVER_PORT", config->port);
1925         }
1926 #endif
1927
1928 #if ENABLE_FEATURE_HTTPD_RELOAD_CONFIG_SIGHUP
1929         sighup_handler(0);
1930 #else
1931         parse_conf(default_path_httpd_conf, FIRST_PARSE);
1932 #endif
1933
1934         if (opt & OPT_INETD)
1935                 return miniHttpd_inetd();
1936
1937         if (!(opt & OPT_FOREGROUND))
1938                 xdaemon(1, 0);     /* don't change current directory */
1939         return miniHttpd(config->server_socket);
1940 }