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