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