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