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