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