ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/thttpd/libhttpd.c
Revision: 1.2
Committed: Mon Jun 25 02:35:16 2001 UTC (23 years ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.1: +88 -26 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 /* libhttpd.c - HTTP protocol library
2 **
3 ** Copyright © 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@acme.com>.
4 ** All rights reserved.
5 **
6 ** Redistribution and use in source and binary forms, with or without
7 ** modification, are permitted provided that the following conditions
8 ** are met:
9 ** 1. Redistributions of source code must retain the above copyright
10 ** notice, this list of conditions and the following disclaimer.
11 ** 2. Redistributions in binary form must reproduce the above copyright
12 ** notice, this list of conditions and the following disclaimer in the
13 ** documentation and/or other materials provided with the distribution.
14 **
15 ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 ** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 ** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 ** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 ** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 ** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 ** SUCH DAMAGE.
26 */
27
28
29 #include "config.h"
30 #include "version.h"
31
32 #ifdef SHOW_SERVER_VERSION
33 #define EXPOSED_SERVER_SOFTWARE SERVER_SOFTWARE
34 #else /* SHOW_SERVER_VERSION */
35 #define EXPOSED_SERVER_SOFTWARE "thttpd"
36 #endif /* SHOW_SERVER_VERSION */
37
38 #include <sys/types.h>
39 #include <sys/param.h>
40 #include <sys/wait.h>
41 #include <sys/stat.h>
42
43 #include <ctype.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <time.h>
47 #ifdef HAVE_MEMORY_H
48 #include <memory.h>
49 #endif /* HAVE_MEMORY_H */
50 #include <pwd.h>
51 #include <signal.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <syslog.h>
56 #include <unistd.h>
57 #include <stdarg.h>
58
59 #ifdef HAVE_OSRELDATE_H
60 #include <osreldate.h>
61 #endif /* HAVE_OSRELDATE_H */
62
63 #ifdef HAVE_DIRENT_H
64 # include <dirent.h>
65 # define NAMLEN(dirent) strlen((dirent)->d_name)
66 #else
67 # define dirent direct
68 # define NAMLEN(dirent) (dirent)->d_namlen
69 # ifdef HAVE_SYS_NDIR_H
70 # include <sys/ndir.h>
71 # endif
72 # ifdef HAVE_SYS_DIR_H
73 # include <sys/dir.h>
74 # endif
75 # ifdef HAVE_NDIR_H
76 # include <ndir.h>
77 # endif
78 #endif
79
80 extern char* crypt( const char* key, const char* setting );
81
82 #include "libhttpd.h"
83 #include "mmc.h"
84 #include "timers.h"
85 #include "match.h"
86 #include "tdate_parse.h"
87
88 #ifndef STDIN_FILENO
89 #define STDIN_FILENO 0
90 #endif
91 #ifndef STDOUT_FILENO
92 #define STDOUT_FILENO 1
93 #endif
94 #ifndef STDERR_FILENO
95 #define STDERR_FILENO 2
96 #endif
97
98 #ifndef max
99 #define max(a,b) ((a) > (b) ? (a) : (b))
100 #endif
101 #ifndef min
102 #define min(a,b) ((a) < (b) ? (a) : (b))
103 #endif
104
105
106 /* Forwards. */
107 static void child_reaper( ClientData client_data, struct timeval* nowP );
108 static int do_reap( void );
109 static void check_options( void );
110 static void free_httpd_server( httpd_server* hs );
111 static int initialize_listen_socket( httpd_sockaddr* saP );
112 static void unlisten( httpd_server* hs );
113 static void add_response( httpd_conn* hc, char* str );
114 static void send_mime( httpd_conn* hc, int status, char* title, char* encodings, char* extraheads, char* type, int length, time_t mod );
115 static void send_response( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg );
116 static void send_response_tail( httpd_conn* hc );
117 static void defang( char* str, char* dfstr, int dfsize );
118 #ifdef ERR_DIR
119 static int send_err_file( httpd_conn* hc, int status, char* title, char* extraheads, char* filename );
120 #endif /* ERR_DIR */
121 #ifdef AUTH_FILE
122 static void send_authenticate( httpd_conn* hc, char* realm );
123 static int b64_decode( const char* str, unsigned char* space, int size );
124 static int auth_check( httpd_conn* hc, char* dirname );
125 static int auth_check2( httpd_conn* hc, char* dirname );
126 #endif /* AUTH_FILE */
127 static void send_dirredirect( httpd_conn* hc );
128 static int hexit( char c );
129 static void strdecode( char* to, char* from );
130 #ifdef GENERATE_INDEXES
131 static void strencode( char* to, int tosize, char* from );
132 #endif /* GENERATE_INDEXES */
133 #ifdef TILDE_MAP_1
134 static int tilde_map_1( httpd_conn* hc );
135 #endif /* TILDE_MAP_1 */
136 #ifdef TILDE_MAP_2
137 static int tilde_map_2( httpd_conn* hc );
138 #endif /* TILDE_MAP_2 */
139 static int vhost_map( httpd_conn* hc );
140 static char* expand_symlinks( char* path, char** restP, int no_symlink, int tildemapped );
141 static char* bufgets( httpd_conn* hc );
142 static void de_dotdot( char* file );
143 static void figure_mime( httpd_conn* hc );
144 #ifdef CGI_TIMELIMIT
145 static void cgi_kill2( ClientData client_data, struct timeval* nowP );
146 static void cgi_kill( ClientData client_data, struct timeval* nowP );
147 #endif /* CGI_TIMELIMIT */
148 #ifdef GENERATE_INDEXES
149 static off_t ls( httpd_conn* hc );
150 #endif /* GENERATE_INDEXES */
151 static char* build_env( char* fmt, char* arg );
152 #ifdef SERVER_NAME_LIST
153 static char* hostname_map( char* hostname );
154 #endif /* SERVER_NAME_LIST */
155 static char** make_envp( httpd_conn* hc );
156 static char** make_argp( httpd_conn* hc );
157 static void cgi_interpose_input( httpd_conn* hc, int wfd );
158 static void post_post_garbage_hack( httpd_conn* hc );
159 static void cgi_interpose_output( httpd_conn* hc, int rfd );
160 static void cgi_child( httpd_conn* hc, char* exefilename );
161 static off_t cgi( httpd_conn* hc, char* exefilename );
162 static int really_start_request( httpd_conn* hc, struct timeval* nowP );
163 static void make_log_entry( httpd_conn* hc, struct timeval* nowP );
164 static int check_referer( httpd_conn* hc );
165 static int really_check_referer( httpd_conn* hc );
166 static int sockaddr_check( httpd_sockaddr* saP );
167 static size_t sockaddr_len( httpd_sockaddr* saP );
168 static int my_snprintf( char* str, size_t size, const char* format, ... );
169
170
171 static int reap_time;
172
173 static void
174 child_reaper( ClientData client_data, struct timeval* nowP )
175 {
176 int child_count;
177 static int prev_child_count = 0;
178
179 child_count = do_reap();
180
181 /* Reschedule reaping, with adaptively changed time. */
182 if ( child_count > prev_child_count * 3 / 2 )
183 reap_time = max( reap_time / 2, MIN_REAP_TIME );
184 else if ( child_count < prev_child_count * 2 / 3 )
185 reap_time = min( reap_time * 5 / 4, MAX_REAP_TIME );
186 if ( tmr_create( nowP, child_reaper, JunkClientData, reap_time * 1000L, 0 ) == (Timer*) 0 )
187 {
188 syslog( LOG_CRIT, "tmr_create(child_reaper) failed" );
189 exit( 1 );
190 }
191 }
192
193 static int
194 do_reap( void )
195 {
196 int child_count;
197 pid_t pid;
198 int status;
199
200 /* Reap defunct children until there aren't any more. */
201 for ( child_count = 0; ; ++child_count )
202 {
203 #ifdef HAVE_WAITPID
204 pid = waitpid( (pid_t) -1, &status, WNOHANG );
205 #else /* HAVE_WAITPID */
206 pid = wait3( &status, WNOHANG, (struct rusage*) 0 );
207 #endif /* HAVE_WAITPID */
208 if ( (int) pid == 0 ) /* none left */
209 break;
210 if ( (int) pid < 0 )
211 {
212 if ( errno == EINTR ) /* because of ptrace */
213 continue;
214 /* ECHILD shouldn't happen with the WNOHANG option, but with
215 ** some kernels it does anyway. Ignore it.
216 */
217 if ( errno != ECHILD )
218 syslog( LOG_ERR, "waitpid - %m" );
219 break;
220 }
221 }
222 return child_count;
223 }
224
225
226 static void
227 check_options( void )
228 {
229 #if defined(TILDE_MAP_1) && defined(TILDE_MAP_2)
230 syslog( LOG_CRIT, "both TILDE_MAP_1 and TILDE_MAP_2 are defined" );
231 exit( 1 );
232 #endif /* both */
233 }
234
235
236 static void
237 free_httpd_server( httpd_server* hs )
238 {
239 if ( hs->binding_hostname != (char*) 0 )
240 free( (void*) hs->binding_hostname );
241 if ( hs->cwd != (char*) 0 )
242 free( (void*) hs->cwd );
243 if ( hs->autoindex_prog != (char*) 0 )
244 free( (void*) hs->autoindex_prog );
245 if ( hs->cgi_pattern != (char*) 0 )
246 free( (void*) hs->cgi_pattern );
247 if ( hs->charset != (char*) 0 )
248 free( (void*) hs->charset );
249 if ( hs->url_pattern != (char*) 0 )
250 free( (void*) hs->url_pattern );
251 if ( hs->local_pattern != (char*) 0 )
252 free( (void*) hs->local_pattern );
253 free( (void*) hs );
254 }
255
256
257 httpd_server*
258 httpd_initialize(
259 char* hostname, httpd_sockaddr* sa4P, httpd_sockaddr* sa6P, int port,
260 char* cgi_pattern, char* charset, char* cwd, int no_log, FILE* logfp,
261 int no_symlink, int vhost, int global_passwd, char* url_pattern,
262 char* local_pattern, int no_empty_referers,
263 char* autoindex_prog)
264 {
265 httpd_server* hs;
266 static char ghnbuf[256];
267 char* cp;
268
269 check_options();
270
271 /* Set up child-process reaper. */
272 reap_time = min( MIN_REAP_TIME * 4, MAX_REAP_TIME );
273 if ( tmr_create( (struct timeval*) 0, child_reaper, JunkClientData, reap_time * 1000L, 0 ) == (Timer*) 0 )
274 {
275 syslog( LOG_CRIT, "tmr_create(child_reaper) failed" );
276 return (httpd_server*) 0;
277 }
278
279 hs = NEW( httpd_server, 1 );
280 if ( hs == (httpd_server*) 0 )
281 {
282 syslog( LOG_CRIT, "out of memory allocating an httpd_server" );
283 return (httpd_server*) 0;
284 }
285
286 if ( hostname != (char*) 0 )
287 {
288 hs->binding_hostname = strdup( hostname );
289 if ( hs->binding_hostname == (char*) 0 )
290 {
291 syslog( LOG_CRIT, "out of memory copying hostname" );
292 return (httpd_server*) 0;
293 }
294 hs->server_hostname = hs->binding_hostname;
295 }
296 else
297 {
298 hs->binding_hostname = (char*) 0;
299 hs->server_hostname = (char*) 0;
300 if ( gethostname( ghnbuf, sizeof(ghnbuf) ) < 0 )
301 ghnbuf[0] = '\0';
302 #ifdef SERVER_NAME_LIST
303 if ( ghnbuf[0] != '\0' )
304 hs->server_hostname = hostname_map( ghnbuf );
305 #endif /* SERVER_NAME_LIST */
306 if ( hs->server_hostname == (char*) 0 )
307 {
308 #ifdef SERVER_NAME
309 hs->server_hostname = SERVER_NAME;
310 #else /* SERVER_NAME */
311 if ( ghnbuf[0] != '\0' )
312 hs->server_hostname = ghnbuf;
313 #endif /* SERVER_NAME */
314 }
315 }
316
317 hs->port = port;
318 if ( cgi_pattern == (char*) 0 )
319 hs->cgi_pattern = (char*) 0;
320 else
321 {
322 /* Nuke any leading slashes. */
323 if ( cgi_pattern[0] == '/' )
324 ++cgi_pattern;
325 hs->cgi_pattern = strdup( cgi_pattern );
326 if ( hs->cgi_pattern == (char*) 0 )
327 {
328 syslog( LOG_CRIT, "out of memory copying cgi_pattern" );
329 return (httpd_server*) 0;
330 }
331 /* Nuke any leading slashes in the cgi pattern. */
332 while ( ( cp = strstr( hs->cgi_pattern, "|/" ) ) != (char*) 0 )
333 (void) strcpy( cp + 1, cp + 2 );
334 }
335 hs->autoindex_prog = autoindex_prog ? strdup( autoindex_prog ) : 0;
336 hs->charset = strdup( charset );
337 hs->cwd = strdup( cwd );
338 if ( hs->cwd == (char*) 0 )
339 {
340 syslog( LOG_CRIT, "out of memory copying cwd" );
341 return (httpd_server*) 0;
342 }
343 if ( url_pattern == (char*) 0 )
344 hs->url_pattern = (char*) 0;
345 else
346 {
347 hs->url_pattern = strdup( url_pattern );
348 if ( hs->url_pattern == (char*) 0 )
349 {
350 syslog( LOG_CRIT, "out of memory copying url_pattern" );
351 return (httpd_server*) 0;
352 }
353 }
354 if ( local_pattern == (char*) 0 )
355 hs->local_pattern = (char*) 0;
356 else
357 {
358 hs->local_pattern = strdup( local_pattern );
359 if ( hs->local_pattern == (char*) 0 )
360 {
361 syslog( LOG_CRIT, "out of memory copying local_pattern" );
362 return (httpd_server*) 0;
363 }
364 }
365 hs->no_log = no_log;
366 hs->logfp = (FILE*) 0;
367 httpd_set_logfp( hs, logfp );
368 hs->no_symlink = no_symlink;
369 hs->vhost = vhost;
370 hs->global_passwd = global_passwd;
371 hs->no_empty_referers = no_empty_referers;
372
373 /* Initialize listen sockets. Try v6 first because of a Linux peculiarity;
374 ** unlike other systems, it has magical v6 sockets that also listen for v4,
375 ** but if you bind a v4 socket first then the v6 bind fails.
376 */
377 if ( sa6P == (httpd_sockaddr*) 0 )
378 hs->listen6_fd = -1;
379 else
380 hs->listen6_fd = initialize_listen_socket( sa6P );
381 if ( sa4P == (httpd_sockaddr*) 0 )
382 hs->listen4_fd = -1;
383 else
384 hs->listen4_fd = initialize_listen_socket( sa4P );
385 /* If we didn't get any valid sockets, fail. */
386 if ( hs->listen4_fd == -1 && hs->listen6_fd == -1 )
387 {
388 free_httpd_server( hs );
389 return (httpd_server*) 0;
390 }
391
392 /* Done initializing. */
393 if ( hs->binding_hostname == (char*) 0 )
394 syslog( LOG_INFO, "%.80s starting on port %d", SERVER_SOFTWARE, hs->port );
395 else
396 syslog(
397 LOG_INFO, "%.80s starting on %.80s, port %d", SERVER_SOFTWARE,
398 httpd_ntoa( hs->listen4_fd != -1 ? sa4P : sa6P ), hs->port );
399 return hs;
400 }
401
402
403 static int
404 initialize_listen_socket( httpd_sockaddr* saP )
405 {
406 int listen_fd;
407 int on, flags;
408
409 /* Check sockaddr. */
410 if ( ! sockaddr_check( saP ) )
411 {
412 syslog( LOG_CRIT, "unknown sockaddr family on listen socket" );
413 return -1;
414 }
415
416 /* Create socket. */
417 listen_fd = socket( saP->sa.sa_family, SOCK_STREAM, 0 );
418 if ( listen_fd < 0 )
419 {
420 syslog( LOG_CRIT, "socket %.80s - %m", httpd_ntoa( saP ) );
421 return -1;
422 }
423 (void) fcntl( listen_fd, F_SETFD, 1 );
424
425 /* Allow reuse of local addresses. */
426 on = 1;
427 if ( setsockopt(
428 listen_fd, SOL_SOCKET, SO_REUSEADDR, (char*) &on,
429 sizeof(on) ) < 0 )
430 syslog( LOG_CRIT, "setsockopt SO_REUSEADDR - %m" );
431
432 /* Use accept filtering, if available. */
433 #ifdef SO_ACCEPTFILTER
434 {
435 #if ( __FreeBSD_version >= 411000 )
436 #define ACCEPT_FILTER_NAME "httpready"
437 #else
438 #define ACCEPT_FILTER_NAME "dataready"
439 #endif
440 struct accept_filter_arg af;
441 (void) bzero( &af, sizeof(af) );
442 (void) strcpy( af.af_name, ACCEPT_FILTER_NAME );
443 (void) setsockopt(
444 listen_fd, SOL_SOCKET, SO_ACCEPTFILTER, (char*) &af, sizeof(af) );
445 }
446 #endif /* SO_ACCEPTFILTER */
447
448 /* Bind to it. */
449 if ( bind( listen_fd, &saP->sa, sockaddr_len( saP ) ) < 0 )
450 {
451 syslog(
452 LOG_CRIT, "bind %.80s - %m", httpd_ntoa( saP ) );
453 (void) close( listen_fd );
454 return -1;
455 }
456
457 /* Set the listen file descriptor to no-delay mode. */
458 flags = fcntl( listen_fd, F_GETFL, 0 );
459 if ( flags == -1 )
460 {
461 syslog( LOG_CRIT, "fcntl F_GETFL - %m" );
462 (void) close( listen_fd );
463 return -1;
464 }
465 if ( fcntl( listen_fd, F_SETFL, flags | O_NDELAY ) < 0 )
466 {
467 syslog( LOG_CRIT, "fcntl O_NDELAY - %m" );
468 (void) close( listen_fd );
469 return -1;
470 }
471
472 /* Start a listen going. */
473 if ( listen( listen_fd, LISTEN_BACKLOG ) < 0 )
474 {
475 syslog( LOG_CRIT, "listen - %m" );
476 (void) close( listen_fd );
477 return -1;
478 }
479
480 return listen_fd;
481 }
482
483
484 void
485 httpd_set_logfp( httpd_server* hs, FILE* logfp )
486 {
487 if ( hs->logfp != (FILE*) 0 )
488 (void) fclose( hs->logfp );
489 hs->logfp = logfp;
490 }
491
492
493 void
494 httpd_terminate( httpd_server* hs )
495 {
496 unlisten( hs );
497 if ( hs->logfp != (FILE*) 0 )
498 (void) fclose( hs->logfp );
499 free_httpd_server( hs );
500 }
501
502
503 static void
504 unlisten( httpd_server* hs )
505 {
506 if ( hs->listen4_fd != -1 )
507 (void) close( hs->listen4_fd );
508 if ( hs->listen6_fd != -1 )
509 (void) close( hs->listen6_fd );
510 }
511
512
513 /* Conditional macro to allow two alternate forms for use in the built-in
514 ** error pages. If EXPLICIT_ERROR_PAGES is defined, the second and more
515 ** explicit error form is used; otherwise, the first and more generic
516 ** form is used.
517 */
518 #ifdef EXPLICIT_ERROR_PAGES
519 #define ERROR_FORM(a,b) b
520 #else /* EXPLICIT_ERROR_PAGES */
521 #define ERROR_FORM(a,b) a
522 #endif /* EXPLICIT_ERROR_PAGES */
523
524
525 static char* ok200title = "OK";
526 static char* ok206title = "Partial Content";
527
528 static char* err302title = "Found";
529 static char* err302form = "The actual URL is '%.80s'.\n";
530
531 static char* err304title = "Not Modified";
532
533 char* httpd_err400title = "Bad Request";
534 char* httpd_err400form =
535 "Your request has bad syntax or is inherently impossible to satisfy.\n";
536
537 #ifdef AUTH_FILE
538 static char* err401title = "Unauthorized";
539 static char* err401form =
540 "Authorization required for the URL '%.80s'.\n";
541 #endif /* AUTH_FILE */
542
543 static char* err403title = "Forbidden";
544 static char* err403form =
545 "You do not have permission to get URL '%.80s' from this server.\n";
546
547 static char* err404title = "Not Found";
548 static char* err404form =
549 "The requested URL '%.80s' was not found on this server.\n";
550
551 char* httpd_err408title = "Request Timeout";
552 char* httpd_err408form =
553 "No request appeared within a reasonable time period.\n";
554
555 static char* err500title = "Internal Error";
556 static char* err500form =
557 "There was an unusual problem serving the requested URL '%.80s'.\n";
558
559 static char* err501title = "Not Implemented";
560 static char* err501form =
561 "The requested method '%.80s' is not implemented by this server.\n";
562
563 char* httpd_err503title = "Service Temporarily Overloaded";
564 char* httpd_err503form =
565 "The requested URL '%.80s' is temporarily overloaded. Please try again later.\n";
566
567
568 /* Append a string to the buffer waiting to be sent as response. */
569 static void
570 add_response( httpd_conn* hc, char* str )
571 {
572 int len;
573
574 len = strlen( str );
575 httpd_realloc_str( &hc->response, &hc->maxresponse, hc->responselen + len );
576 (void) memcpy( &(hc->response[hc->responselen]), str, len );
577 hc->responselen += len;
578 }
579
580 /* Send the buffered response. */
581 void
582 httpd_write_response( httpd_conn* hc )
583 {
584 /* First turn off NDELAY mode. */
585 httpd_clear_ndelay( hc->conn_fd );
586 /* And send it, if necessary. */
587 if ( hc->responselen > 0 )
588 {
589 (void) write( hc->conn_fd, hc->response, hc->responselen );
590 hc->responselen = 0;
591 }
592 }
593
594
595 /* Set NDELAY mode on a socket. */
596 void
597 httpd_set_ndelay( int fd )
598 {
599 int flags, newflags;
600
601 flags = fcntl( fd, F_GETFL, 0 );
602 if ( flags != -1 )
603 {
604 newflags = flags | (int) O_NDELAY;
605 if ( newflags != flags )
606 (void) fcntl( fd, F_SETFL, newflags );
607 }
608 }
609
610
611 /* Clear NDELAY mode on a socket. */
612 void
613 httpd_clear_ndelay( int fd )
614 {
615 int flags, newflags;
616
617 flags = fcntl( fd, F_GETFL, 0 );
618 if ( flags != -1 )
619 {
620 newflags = flags & ~ (int) O_NDELAY;
621 if ( newflags != flags )
622 (void) fcntl( fd, F_SETFL, newflags );
623 }
624 }
625
626
627 static void
628 send_mime( httpd_conn* hc, int status, char* title, char* encodings, char* extraheads, char* type, int length, time_t mod )
629 {
630 time_t now;
631 const char* rfc1123fmt = "%a, %d %b %Y %H:%M:%S GMT";
632 char nowbuf[100];
633 char modbuf[100];
634 char fixed_type[500];
635 char buf[1000];
636 int partial_content;
637
638 hc->status = status;
639 hc->bytes_to_send = length;
640 if ( hc->mime_flag )
641 {
642 if ( status == 200 && hc->got_range &&
643 ( hc->end_byte_loc >= hc->init_byte_loc ) &&
644 ( ( hc->end_byte_loc != length - 1 ) ||
645 ( hc->init_byte_loc != 0 ) ) &&
646 ( hc->range_if == (time_t) -1 ||
647 hc->range_if == hc->sb.st_mtime ) )
648 {
649 partial_content = 1;
650 hc->status = status = 206;
651 title = ok206title;
652 }
653 else
654 partial_content = 0;
655
656 now = time( (time_t*) 0 );
657 if ( mod == (time_t) 0 )
658 mod = now;
659 (void) strftime( nowbuf, sizeof(nowbuf), rfc1123fmt, gmtime( &now ) );
660 (void) strftime( modbuf, sizeof(modbuf), rfc1123fmt, gmtime( &mod ) );
661 (void) my_snprintf(
662 fixed_type, sizeof(fixed_type), type, hc->hs->charset );
663 (void) my_snprintf( buf, sizeof(buf),
664 "%.20s %d %s\r\nServer: %s\r\nContent-Type: %s\r\nDate: %s\r\nLast-Modified: %s\r\nAccept-Ranges: bytes\r\nConnection: close\r\n",
665 hc->protocol, status, title, EXPOSED_SERVER_SOFTWARE, fixed_type,
666 nowbuf, modbuf );
667 add_response( hc, buf );
668 if ( encodings[0] != '\0' )
669 {
670 (void) my_snprintf( buf, sizeof(buf),
671 "Content-Encoding: %s\r\n", encodings );
672 add_response( hc, buf );
673 }
674 if ( partial_content )
675 {
676 (void) my_snprintf( buf, sizeof(buf),
677 "Content-Range: bytes %ld-%ld/%d\r\nContent-Length: %ld\r\n",
678 (long) hc->init_byte_loc, (long) hc->end_byte_loc, length,
679 (long) ( hc->end_byte_loc - hc->init_byte_loc + 1 ) );
680 add_response( hc, buf );
681 }
682 else if ( length >= 0 )
683 {
684 (void) my_snprintf( buf, sizeof(buf),
685 "Content-Length: %d\r\n", length );
686 add_response( hc, buf );
687 }
688 if ( extraheads[0] != '\0' )
689 add_response( hc, extraheads );
690 add_response( hc, "\r\n" );
691 }
692 }
693
694
695 static int str_alloc_count = 0;
696 static long str_alloc_size = 0;
697
698 void
699 httpd_realloc_str( char** strP, int* maxsizeP, int size )
700 {
701 if ( *maxsizeP == 0 )
702 {
703 *maxsizeP = MAX( 200, size ); /* arbitrary */
704 *strP = NEW( char, *maxsizeP + 1 );
705 ++str_alloc_count;
706 str_alloc_size += *maxsizeP;
707 }
708 else if ( size > *maxsizeP )
709 {
710 str_alloc_size -= *maxsizeP;
711 *maxsizeP = MAX( *maxsizeP * 2, size * 5 / 4 );
712 *strP = RENEW( *strP, char, *maxsizeP + 1 );
713 str_alloc_size += *maxsizeP;
714 }
715 else
716 return;
717 if ( *strP == (char*) 0 )
718 {
719 syslog(
720 LOG_ERR, "out of memory reallocating a string to %d bytes",
721 *maxsizeP );
722 exit( 1 );
723 }
724 }
725
726
727 static void
728 send_response( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg )
729 {
730 char defanged_arg[1000], buf[2000];
731
732 send_mime( hc, status, title, "", extraheads, "text/html", -1, 0 );
733 (void) my_snprintf( buf, sizeof(buf),
734 "<HTML><HEAD><TITLE>%d %s</TITLE></HEAD>\n<BODY BGCOLOR=\"#cc9999\"><H2>%d %s</H2>\n",
735 status, title, status, title );
736 add_response( hc, buf );
737 defang( arg, defanged_arg, sizeof(defanged_arg) );
738 (void) my_snprintf( buf, sizeof(buf), form, defanged_arg );
739 add_response( hc, buf );
740 if ( match( "**MSIE**", hc->useragent ) )
741 {
742 int n;
743 add_response( hc, "<!--\n" );
744 for ( n = 0; n < 6; ++n )
745 add_response( hc, "Padding so that MSIE deigns to show this error instead of its own canned one.\n");
746 add_response( hc, "-->\n" );
747 }
748 send_response_tail( hc );
749 }
750
751
752 static void
753 send_response_tail( httpd_conn* hc )
754 {
755 char buf[1000];
756
757 (void) my_snprintf( buf, sizeof(buf),
758 "<HR>\n<ADDRESS><A HREF=\"%s\">%s</A></ADDRESS>\n</BODY></HTML>\n",
759 SERVER_ADDRESS, EXPOSED_SERVER_SOFTWARE );
760 add_response( hc, buf );
761 }
762
763
764 static void
765 defang( char* str, char* dfstr, int dfsize )
766 {
767 char* cp1;
768 char* cp2;
769
770 for ( cp1 = str, cp2 = dfstr;
771 *cp1 != '\0' && cp2 - dfstr < dfsize - 1;
772 ++cp1, ++cp2 )
773 {
774 switch ( *cp1 )
775 {
776 case '<':
777 *cp2++ = '&';
778 *cp2++ = 'l';
779 *cp2++ = 't';
780 *cp2 = ';';
781 break;
782 case '>':
783 *cp2++ = '&';
784 *cp2++ = 'g';
785 *cp2++ = 't';
786 *cp2 = ';';
787 break;
788 default:
789 *cp2 = *cp1;
790 break;
791 }
792 }
793 *cp2 = '\0';
794 }
795
796
797 void
798 httpd_send_err( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg )
799 {
800 #ifdef ERR_DIR
801
802 char filename[1000];
803
804 /* Try virtual host error page. */
805 if ( hc->hs->vhost && hc->hostdir[0] != '\0' )
806 {
807 (void) my_snprintf( filename, sizeof(filename),
808 "%s/%s/err%d.html", hc->hostdir, ERR_DIR, status );
809 if ( send_err_file( hc, status, title, extraheads, filename ) )
810 return;
811 }
812
813 /* Try server-wide error page. */
814 (void) my_snprintf( filename, sizeof(filename),
815 "%s/err%d.html", ERR_DIR, status );
816 if ( send_err_file( hc, status, title, extraheads, filename ) )
817 return;
818
819 /* Fall back on built-in error page. */
820 send_response( hc, status, title, extraheads, form, arg );
821
822 #else /* ERR_DIR */
823
824 send_response( hc, status, title, extraheads, form, arg );
825
826 #endif /* ERR_DIR */
827 }
828
829 void
830 httpd_send_err_blocked( httpd_conn* hc )
831 {
832 #ifdef ERR_DIR
833
834 char filename[1000];
835
836 /* Try virtual host error page. */
837 if ( hc->hs->vhost && hc->hostdir[0] != '\0' )
838 {
839 (void) my_snprintf( filename, sizeof(filename),
840 "%s/%s/err403blocked.html", hc->hostdir, ERR_DIR );
841 if ( send_err_file( hc, 403, err403title, "", filename ) )
842 return;
843 }
844
845 /* Try server-wide error page. */
846 (void) my_snprintf( filename, sizeof(filename),
847 "%s/errerr403blocked.html", ERR_DIR );
848 if ( send_err_file( hc, 403, err403title, "", filename ) )
849 return;
850
851 /* Fall back on built-in error page. */
852 send_response( hc, 403, err403title, "", err403form, "" );
853
854 #else /* ERR_DIR */
855
856 send_response( hc, 403, err403title, "", err403form, "" );
857
858 #endif /* ERR_DIR */
859 }
860
861 #ifdef ERR_DIR
862 static int
863 send_err_file( httpd_conn* hc, int status, char* title, char* extraheads, char* filename )
864 {
865 FILE* fp;
866 char buf[1000];
867 int r;
868
869 fp = fopen( filename, "r" );
870 if ( fp == (FILE*) 0 )
871 return 0;
872 send_mime( hc, status, title, "", extraheads, "text/html", -1, 0 );
873 for (;;)
874 {
875 r = fread( buf, 1, sizeof(buf) - 1, fp );
876 if ( r <= 0 )
877 break;
878 buf[r] = '\0';
879 add_response( hc, buf );
880 }
881 (void) fclose( fp );
882
883 #ifdef ERR_APPEND_SERVER_INFO
884 send_response_tail( hc );
885 #endif /* ERR_APPEND_SERVER_INFO */
886
887 return 1;
888 }
889 #endif /* ERR_DIR */
890
891
892 #ifdef AUTH_FILE
893
894 static void
895 send_authenticate( httpd_conn* hc, char* realm )
896 {
897 static char* header;
898 static int maxheader = 0;
899 static char headstr[] = "WWW-Authenticate: Basic realm=\"";
900
901 httpd_realloc_str(
902 &header, &maxheader, sizeof(headstr) + strlen( realm ) + 3 );
903 (void) my_snprintf( header, maxheader, "%s%s\"\r\n", headstr, realm );
904 httpd_send_err( hc, 401, err401title, header, err401form, hc->encodedurl );
905 /* If the request was a POST then there might still be data to be read,
906 ** so we need to do a lingering close.
907 */
908 if ( hc->method == METHOD_POST )
909 hc->should_linger = 1;
910 }
911
912
913 /* Base-64 decoding. This represents binary data as printable ASCII
914 ** characters. Three 8-bit binary bytes are turned into four 6-bit
915 ** values, like so:
916 **
917 ** [11111111] [22222222] [33333333]
918 **
919 ** [111111] [112222] [222233] [333333]
920 **
921 ** Then the 6-bit values are represented using the characters "A-Za-z0-9+/".
922 */
923
924 static int b64_decode_table[256] = {
925 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 00-0F */
926 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 10-1F */
927 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, /* 20-2F */
928 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, /* 30-3F */
929 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */
930 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* 50-5F */
931 -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */
932 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, /* 70-7F */
933 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 80-8F */
934 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 90-9F */
935 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* A0-AF */
936 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* B0-BF */
937 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* C0-CF */
938 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* D0-DF */
939 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* E0-EF */
940 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 /* F0-FF */
941 };
942
943 /* Do base-64 decoding on a string. Ignore any non-base64 bytes.
944 ** Return the actual number of bytes generated. The decoded size will
945 ** be at most 3/4 the size of the encoded, and may be smaller if there
946 ** are padding characters (blanks, newlines).
947 */
948 static int
949 b64_decode( const char* str, unsigned char* space, int size )
950 {
951 const char* cp;
952 int space_idx, phase;
953 int d, prev_d = 0;
954 unsigned char c;
955
956 space_idx = 0;
957 phase = 0;
958 for ( cp = str; *cp != '\0'; ++cp )
959 {
960 d = b64_decode_table[(int) *cp];
961 if ( d != -1 )
962 {
963 switch ( phase )
964 {
965 case 0:
966 ++phase;
967 break;
968 case 1:
969 c = ( ( prev_d << 2 ) | ( ( d & 0x30 ) >> 4 ) );
970 if ( space_idx < size )
971 space[space_idx++] = c;
972 ++phase;
973 break;
974 case 2:
975 c = ( ( ( prev_d & 0xf ) << 4 ) | ( ( d & 0x3c ) >> 2 ) );
976 if ( space_idx < size )
977 space[space_idx++] = c;
978 ++phase;
979 break;
980 case 3:
981 c = ( ( ( prev_d & 0x03 ) << 6 ) | d );
982 if ( space_idx < size )
983 space[space_idx++] = c;
984 phase = 0;
985 break;
986 }
987 prev_d = d;
988 }
989 }
990 return space_idx;
991 }
992
993
994 /* Returns -1 == unauthorized, 0 == no auth file, 1 = authorized. */
995 static int
996 auth_check( httpd_conn* hc, char* dirname )
997 {
998 if ( hc->hs->global_passwd )
999 {
1000 char* topdir;
1001 if ( hc->hs->vhost && hc->hostdir[0] != '\0' )
1002 topdir = hc->hostdir;
1003 else
1004 topdir = ".";
1005 switch ( auth_check2( hc, topdir ) )
1006 {
1007 case -1:
1008 return -1;
1009 case 1:
1010 return 1;
1011 }
1012 }
1013 return auth_check2( hc, dirname );
1014 }
1015
1016
1017 /* Returns -1 == unauthorized, 0 == no auth file, 1 = authorized. */
1018 static int
1019 auth_check2( httpd_conn* hc, char* dirname )
1020 {
1021 static char* authpath;
1022 static int maxauthpath = 0;
1023 struct stat sb;
1024 char authinfo[500];
1025 char* authpass;
1026 int l;
1027 FILE* fp;
1028 char line[500];
1029 char* cryp;
1030 static char* prevauthpath;
1031 static int maxprevauthpath = 0;
1032 static time_t prevmtime;
1033 static char* prevuser;
1034 static int maxprevuser = 0;
1035 static char* prevcryp;
1036 static int maxprevcryp = 0;
1037
1038 /* Construct auth filename. */
1039 httpd_realloc_str(
1040 &authpath, &maxauthpath, strlen( dirname ) + 1 + sizeof(AUTH_FILE) );
1041 (void) my_snprintf( authpath, maxauthpath,
1042 "%s/%s", dirname, AUTH_FILE );
1043
1044 /* Does this directory have an auth file? */
1045 if ( stat( authpath, &sb ) < 0 )
1046 /* Nope, let the request go through. */
1047 return 0;
1048
1049 /* Does this request contain basic authorization info? */
1050 if ( hc->authorization[0] == '\0' ||
1051 strncmp( hc->authorization, "Basic ", 6 ) != 0 )
1052 {
1053 /* Nope, return a 401 Unauthorized. */
1054 send_authenticate( hc, dirname );
1055 return -1;
1056 }
1057
1058 /* Decode it. */
1059 l = b64_decode( &(hc->authorization[6]), authinfo, sizeof(authinfo) - 1 );
1060 authinfo[l] = '\0';
1061 /* Split into user and password. */
1062 authpass = strchr( authinfo, ':' );
1063 if ( authpass == (char*) 0 )
1064 {
1065 /* No colon? Bogus auth info. */
1066 send_authenticate( hc, dirname );
1067 return -1;
1068 }
1069 *authpass++ = '\0';
1070
1071 /* See if we have a cached entry and can use it. */
1072 if ( maxprevauthpath != 0 &&
1073 strcmp( authpath, prevauthpath ) == 0 &&
1074 sb.st_mtime == prevmtime &&
1075 strcmp( authinfo, prevuser ) == 0 )
1076 {
1077 /* Yes. Check against the cached encrypted password. */
1078 if ( strcmp( crypt( authpass, prevcryp ), prevcryp ) == 0 )
1079 {
1080 /* Ok! */
1081 httpd_realloc_str(
1082 &hc->remoteuser, &hc->maxremoteuser, strlen( authinfo ) );
1083 (void) strcpy( hc->remoteuser, authinfo );
1084 return 1;
1085 }
1086 else
1087 {
1088 /* No. */
1089 send_authenticate( hc, dirname );
1090 return -1;
1091 }
1092 }
1093
1094 /* Open the password file. */
1095 fp = fopen( authpath, "r" );
1096 if ( fp == (FILE*) 0 )
1097 {
1098 /* The file exists but we can't open it? Disallow access. */
1099 syslog(
1100 LOG_ERR, "%.80s auth file %.80s could not be opened - %m",
1101 httpd_ntoa( &hc->client_addr ), authpath );
1102 httpd_send_err(
1103 hc, 403, err403title, "",
1104 ERROR_FORM( err403form, "The requested URL '%.80s' is protected by an authentication file, but the authentication file cannot be opened.\n" ),
1105 hc->encodedurl );
1106 return -1;
1107 }
1108
1109 /* Read it. */
1110 while ( fgets( line, sizeof(line), fp ) != (char*) 0 )
1111 {
1112 /* Nuke newline. */
1113 l = strlen( line );
1114 if ( line[l - 1] == '\n' )
1115 line[l - 1] = '\0';
1116 /* Split into user and encrypted password. */
1117 cryp = strchr( line, ':' );
1118 if ( cryp == (char*) 0 )
1119 continue;
1120 *cryp++ = '\0';
1121 /* Is this the right user? */
1122 if ( strcmp( line, authinfo ) == 0 )
1123 {
1124 /* Yes. */
1125 (void) fclose( fp );
1126 /* So is the password right? */
1127 if ( strcmp( crypt( authpass, cryp ), cryp ) == 0 )
1128 {
1129 /* Ok! */
1130 httpd_realloc_str(
1131 &hc->remoteuser, &hc->maxremoteuser, strlen( line ) );
1132 (void) strcpy( hc->remoteuser, line );
1133 /* And cache this user's info for next time. */
1134 httpd_realloc_str(
1135 &prevauthpath, &maxprevauthpath, strlen( authpath ) );
1136 (void) strcpy( prevauthpath, authpath );
1137 prevmtime = sb.st_mtime;
1138 httpd_realloc_str(
1139 &prevuser, &maxprevuser, strlen( authinfo ) );
1140 (void) strcpy( prevuser, authinfo );
1141 httpd_realloc_str( &prevcryp, &maxprevcryp, strlen( cryp ) );
1142 (void) strcpy( prevcryp, cryp );
1143 return 1;
1144 }
1145 else
1146 {
1147 /* No. */
1148 send_authenticate( hc, dirname );
1149 return -1;
1150 }
1151 }
1152 }
1153
1154 /* Didn't find that user. Access denied. */
1155 (void) fclose( fp );
1156 send_authenticate( hc, dirname );
1157 return -1;
1158 }
1159
1160 #endif /* AUTH_FILE */
1161
1162
1163 static void
1164 send_dirredirect( httpd_conn* hc )
1165 {
1166 static char* location;
1167 static char* header;
1168 static int maxlocation = 0, maxheader = 0;
1169 static char headstr[] = "Location: ";
1170
1171 httpd_realloc_str( &location, &maxlocation, strlen( hc->encodedurl ) + 1 );
1172 (void) my_snprintf( location, maxlocation,
1173 "%s/", hc->encodedurl );
1174 httpd_realloc_str(
1175 &header, &maxheader, sizeof(headstr) + strlen( location ) );
1176 (void) my_snprintf( header, maxheader,
1177 "%s%s\r\n", headstr, location );
1178 send_response( hc, 302, err302title, header, err302form, location );
1179 }
1180
1181
1182 char*
1183 httpd_method_str( int method )
1184 {
1185 switch ( method )
1186 {
1187 case METHOD_GET: return "GET";
1188 case METHOD_HEAD: return "HEAD";
1189 case METHOD_POST: return "POST";
1190 default: return "UNKNOWN";
1191 }
1192 }
1193
1194
1195 static int
1196 hexit( char c )
1197 {
1198 if ( c >= '0' && c <= '9' )
1199 return c - '0';
1200 if ( c >= 'a' && c <= 'f' )
1201 return c - 'a' + 10;
1202 if ( c >= 'A' && c <= 'F' )
1203 return c - 'A' + 10;
1204 return 0; /* shouldn't happen, we're guarded by isxdigit() */
1205 }
1206
1207
1208 /* Copies and decodes a string. It's ok for from and to to be the
1209 ** same string.
1210 */
1211 static void
1212 strdecode( char* to, char* from )
1213 {
1214 for ( ; *from != '\0'; ++to, ++from )
1215 {
1216 if ( from[0] == '%' && isxdigit( from[1] ) && isxdigit( from[2] ) )
1217 {
1218 *to = hexit( from[1] ) * 16 + hexit( from[2] );
1219 from += 2;
1220 }
1221 else
1222 *to = *from;
1223 }
1224 *to = '\0';
1225 }
1226
1227
1228 #ifdef GENERATE_INDEXES
1229 /* Copies and encodes a string. */
1230 static void
1231 strencode( char* to, int tosize, char* from )
1232 {
1233 int tolen;
1234
1235 for ( tolen = 0; *from != '\0' && tolen + 4 < tosize; ++from )
1236 {
1237 if ( isalnum(*from) || strchr( "/_.-~", *from ) != (char*) 0 )
1238 {
1239 *to = *from;
1240 ++to;
1241 ++tolen;
1242 }
1243 else
1244 {
1245 (void) sprintf( to, "%%%02x", (int) *from & 0xff );
1246 to += 3;
1247 tolen += 3;
1248 }
1249 }
1250 *to = '\0';
1251 }
1252 #endif /* GENERATE_INDEXES */
1253
1254
1255 #ifdef TILDE_MAP_1
1256 /* Map a ~username/whatever URL into <prefix>/username. */
1257 static int
1258 tilde_map_1( httpd_conn* hc )
1259 {
1260 static char* temp;
1261 static int maxtemp = 0;
1262 int len;
1263 static char* prefix = TILDE_MAP_1;
1264
1265 len = strlen( hc->expnfilename ) - 1;
1266 httpd_realloc_str( &temp, &maxtemp, len );
1267 (void) strcpy( temp, &hc->expnfilename[1] );
1268 httpd_realloc_str(
1269 &hc->expnfilename, &hc->maxexpnfilename, strlen( prefix ) + 1 + len );
1270 (void) strcpy( hc->expnfilename, prefix );
1271 if ( prefix[0] != '\0' )
1272 (void) strcat( hc->expnfilename, "/" );
1273 (void) strcat( hc->expnfilename, temp );
1274 return 1;
1275 }
1276 #endif /* TILDE_MAP_1 */
1277
1278 #ifdef TILDE_MAP_2
1279 /* Map a ~username/whatever URL into <user's homedir>/<postfix>. */
1280 static int
1281 tilde_map_2( httpd_conn* hc )
1282 {
1283 static char* temp;
1284 static int maxtemp = 0;
1285 static char* postfix = TILDE_MAP_2;
1286 char* cp;
1287 struct passwd* pw;
1288 char* alt;
1289 char* rest;
1290
1291 /* Get the username. */
1292 httpd_realloc_str( &temp, &maxtemp, strlen( hc->expnfilename ) - 1 );
1293 (void) strcpy( temp, &hc->expnfilename[1] );
1294 cp = strchr( temp, '/' );
1295 if ( cp != (char*) 0 )
1296 *cp++ = '\0';
1297 else
1298 cp = "";
1299
1300 /* Get the passwd entry. */
1301 pw = getpwnam( temp );
1302 if ( pw == (struct passwd*) 0 )
1303 return 0;
1304
1305 /* Set up altdir. */
1306 httpd_realloc_str(
1307 &hc->altdir, &hc->maxaltdir,
1308 strlen( pw->pw_dir ) + 1 + strlen( postfix ) );
1309 (void) strcpy( hc->altdir, pw->pw_dir );
1310 if ( postfix[0] != '\0' )
1311 {
1312 (void) strcat( hc->altdir, "/" );
1313 (void) strcat( hc->altdir, postfix );
1314 }
1315 alt = expand_symlinks( hc->altdir, &rest, 0, 1 );
1316 if ( rest[0] != '\0' )
1317 return 0;
1318 httpd_realloc_str( &hc->altdir, &hc->maxaltdir, strlen( alt ) );
1319 (void) strcpy( hc->altdir, alt );
1320
1321 /* And the filename becomes altdir plus the post-~ part of the original. */
1322 httpd_realloc_str(
1323 &hc->expnfilename, &hc->maxexpnfilename,
1324 strlen( hc->altdir ) + 1 + strlen( cp ) );
1325 (void) my_snprintf( hc->expnfilename, hc->maxexpnfilename,
1326 "%s/%s", hc->altdir, cp );
1327
1328 /* For this type of tilde mapping, we want to defeat vhost mapping. */
1329 hc->tildemapped = 1;
1330
1331 return 1;
1332 }
1333 #endif /* TILDE_MAP_2 */
1334
1335
1336 /* Virtual host mapping. */
1337 static int
1338 vhost_map( httpd_conn* hc )
1339 {
1340 httpd_sockaddr sa;
1341 int sz;
1342 static char* tempfilename;
1343 static int maxtempfilename = 0;
1344 char* cp1;
1345 int len;
1346 #ifdef VHOST_DIRLEVELS
1347 int i;
1348 char* cp2;
1349 #endif /* VHOST_DIRLEVELS */
1350
1351 /* Figure out the virtual hostname. */
1352 if ( hc->reqhost[0] != '\0' )
1353 hc->hostname = hc->reqhost;
1354 else if ( hc->hdrhost[0] != '\0' )
1355 hc->hostname = hc->hdrhost;
1356 else
1357 {
1358 sz = sizeof(sa);
1359 if ( getsockname( hc->conn_fd, &sa.sa, &sz ) < 0 )
1360 {
1361 syslog( LOG_ERR, "getsockname - %m" );
1362 return 0;
1363 }
1364 hc->hostname = httpd_ntoa( &sa );
1365 }
1366 /* Pound it to lower case. */
1367 for ( cp1 = hc->hostname; *cp1 != '\0'; ++cp1 )
1368 if ( isupper( *cp1 ) )
1369 *cp1 = tolower( *cp1 );
1370
1371 if ( hc->tildemapped )
1372 return 1;
1373
1374 /* Figure out the host directory. */
1375 #ifdef VHOST_DIRLEVELS
1376 httpd_realloc_str(
1377 &hc->hostdir, &hc->maxhostdir,
1378 strlen( hc->hostname ) + 2 * VHOST_DIRLEVELS );
1379 if ( strncmp( hc->hostname, "www.", 4 ) == 0 )
1380 cp1 = &hc->hostname[4];
1381 else
1382 cp1 = hc->hostname;
1383 for ( cp2 = hc->hostdir, i = 0; i < VHOST_DIRLEVELS; ++i )
1384 {
1385 /* Skip dots in the hostname. If we don't, then we get vhost
1386 ** directories in higher level of filestructure if dot gets
1387 ** involved into path construction. It's `while' used here instead
1388 ** of `if' for it's possible to have a hostname formed with two
1389 ** dots at the end of it.
1390 */
1391 while ( *cp1 == '.' )
1392 ++cp1;
1393 /* Copy a character from the hostname, or '_' if we ran out. */
1394 if ( *cp1 != '\0' )
1395 *cp2++ = *cp1++;
1396 else
1397 *cp2++ = '_';
1398 /* Copy a slash. */
1399 *cp2++ = '/';
1400 }
1401 (void) strcpy( cp2, hc->hostname );
1402 #else /* VHOST_DIRLEVELS */
1403 httpd_realloc_str( &hc->hostdir, &hc->maxhostdir, strlen( hc->hostname ) );
1404 (void) strcpy( hc->hostdir, hc->hostname );
1405 #endif /* VHOST_DIRLEVELS */
1406
1407 /* Prepend hostdir to the filename. */
1408 len = strlen( hc->expnfilename );
1409 httpd_realloc_str( &tempfilename, &maxtempfilename, len );
1410 (void) strcpy( tempfilename, hc->expnfilename );
1411 httpd_realloc_str(
1412 &hc->expnfilename, &hc->maxexpnfilename,
1413 strlen( hc->hostdir ) + 1 + len );
1414 (void) strcpy( hc->expnfilename, hc->hostdir );
1415 (void) strcat( hc->expnfilename, "/" );
1416 (void) strcat( hc->expnfilename, tempfilename );
1417 return 1;
1418 }
1419
1420
1421 /* Expands all symlinks in the given filename, eliding ..'s and leading /'s.
1422 ** Returns the expanded path (pointer to static string), or (char*) 0 on
1423 ** errors. Also returns, in the string pointed to by restP, any trailing
1424 ** parts of the path that don't exist.
1425 **
1426 ** This is a fairly nice little routine. It handles any size filenames
1427 ** without excessive mallocs.
1428 */
1429 static char*
1430 expand_symlinks( char* path, char** restP, int no_symlink, int tildemapped )
1431 {
1432 static char* checked;
1433 static char* rest;
1434 char link[5000];
1435 static int maxchecked = 0, maxrest = 0;
1436 int checkedlen, restlen, linklen, prevcheckedlen, prevrestlen, nlinks, i;
1437 char* r;
1438 char* cp1;
1439 char* cp2;
1440
1441 if ( no_symlink )
1442 {
1443 /* If we are chrooted, we can actually skip the symlink-expansion,
1444 ** since it's impossible to get out of the tree. However, we still
1445 ** need to do the pathinfo check, and the existing symlink expansion
1446 ** code is a pretty reasonable way to do this. So, what we do is
1447 ** a single stat() of the whole filename - if it exists, then we
1448 ** return it as is with nothing in restP. If it doesn't exist, we
1449 ** fall through to the existing code.
1450 **
1451 ** One side-effect of this is that users can't symlink to central
1452 ** approved CGIs any more. The workaround is to use the central
1453 ** URL for the CGI instead of a local symlinked one.
1454 */
1455 struct stat sb;
1456 if ( stat( path, &sb ) != -1 )
1457 {
1458 httpd_realloc_str( &checked, &maxchecked, strlen( path ) );
1459 (void) strcpy( checked, path );
1460 httpd_realloc_str( &rest, &maxrest, 0 );
1461 rest[0] = '\0';
1462 *restP = rest;
1463 return checked;
1464 }
1465 }
1466
1467 /* Start out with nothing in checked and the whole filename in rest. */
1468 httpd_realloc_str( &checked, &maxchecked, 1 );
1469 checked[0] = '\0';
1470 checkedlen = 0;
1471 restlen = strlen( path );
1472 httpd_realloc_str( &rest, &maxrest, restlen );
1473 (void) strcpy( rest, path );
1474 if ( ! tildemapped )
1475 /* Remove any leading slashes. */
1476 while ( rest[0] == '/' )
1477 {
1478 (void) strcpy( rest, &(rest[1]) );
1479 --restlen;
1480 }
1481 r = rest;
1482 nlinks = 0;
1483
1484 /* While there are still components to check... */
1485 while ( restlen > 0 )
1486 {
1487 /* Save current checkedlen in case we get a symlink. Save current
1488 ** restlen in case we get a non-existant component.
1489 */
1490 prevcheckedlen = checkedlen;
1491 prevrestlen = restlen;
1492
1493 /* Grab one component from r and transfer it to checked. */
1494 cp1 = strchr( r, '/' );
1495 if ( cp1 != (char*) 0 )
1496 {
1497 i = cp1 - r;
1498 if ( i == 0 )
1499 {
1500 /* Special case for absolute paths. */
1501 httpd_realloc_str( &checked, &maxchecked, checkedlen + 1 );
1502 (void) strncpy( &checked[checkedlen], r, 1 );
1503 checkedlen += 1;
1504 }
1505 else if ( strncmp( r, "..", MAX( i, 2 ) ) == 0 )
1506 {
1507 /* Ignore ..'s that go above the start of the path. */
1508 if ( checkedlen != 0 )
1509 {
1510 cp2 = strrchr( checked, '/' );
1511 if ( cp2 == (char*) 0 )
1512 checkedlen = 0;
1513 else if ( cp2 == checked )
1514 checkedlen = 1;
1515 else
1516 checkedlen = cp2 - checked;
1517 }
1518 }
1519 else
1520 {
1521 httpd_realloc_str( &checked, &maxchecked, checkedlen + 1 + i );
1522 if ( checkedlen > 0 && checked[checkedlen-1] != '/' )
1523 checked[checkedlen++] = '/';
1524 (void) strncpy( &checked[checkedlen], r, i );
1525 checkedlen += i;
1526 }
1527 checked[checkedlen] = '\0';
1528 r += i + 1;
1529 restlen -= i + 1;
1530 }
1531 else
1532 {
1533 /* No slashes remaining, r is all one component. */
1534 if ( strcmp( r, ".." ) == 0 )
1535 {
1536 /* Ignore ..'s that go above the start of the path. */
1537 if ( checkedlen != 0 )
1538 {
1539 cp2 = strrchr( checked, '/' );
1540 if ( cp2 == (char*) 0 )
1541 checkedlen = 0;
1542 else if ( cp2 == checked )
1543 checkedlen = 1;
1544 else
1545 checkedlen = cp2 - checked;
1546 checked[checkedlen] = '\0';
1547 }
1548 }
1549 else
1550 {
1551 httpd_realloc_str(
1552 &checked, &maxchecked, checkedlen + 1 + restlen );
1553 if ( checkedlen > 0 && checked[checkedlen-1] != '/' )
1554 checked[checkedlen++] = '/';
1555 (void) strcpy( &checked[checkedlen], r );
1556 checkedlen += restlen;
1557 }
1558 r += restlen;
1559 restlen = 0;
1560 }
1561
1562 /* Try reading the current filename as a symlink */
1563 if ( checked[0] == '\0' )
1564 continue;
1565 linklen = readlink( checked, link, sizeof(link) );
1566 if ( linklen == -1 )
1567 {
1568 if ( errno == EINVAL )
1569 continue; /* not a symlink */
1570 if ( errno == EACCES || errno == ENOENT || errno == ENOTDIR )
1571 {
1572 /* That last component was bogus. Restore and return. */
1573 *restP = r - ( prevrestlen - restlen );
1574 if ( prevcheckedlen == 0 )
1575 (void) strcpy( checked, "." );
1576 else
1577 checked[prevcheckedlen] = '\0';
1578 return checked;
1579 }
1580 syslog( LOG_ERR, "readlink %.80s - %m", checked );
1581 return (char*) 0;
1582 }
1583 ++nlinks;
1584 if ( nlinks > MAX_LINKS )
1585 {
1586 syslog( LOG_ERR, "too many symlinks in %.80s", path );
1587 return (char*) 0;
1588 }
1589 link[linklen] = '\0';
1590 if ( link[linklen - 1] == '/' )
1591 link[--linklen] = '\0'; /* trim trailing slash */
1592
1593 /* Insert the link contents in front of the rest of the filename. */
1594 if ( restlen != 0 )
1595 {
1596 (void) strcpy( rest, r );
1597 httpd_realloc_str( &rest, &maxrest, restlen + linklen + 1 );
1598 for ( i = restlen; i >= 0; --i )
1599 rest[i + linklen + 1] = rest[i];
1600 (void) strcpy( rest, link );
1601 rest[linklen] = '/';
1602 restlen += linklen + 1;
1603 r = rest;
1604 }
1605 else
1606 {
1607 /* There's nothing left in the filename, so the link contents
1608 ** becomes the rest.
1609 */
1610 httpd_realloc_str( &rest, &maxrest, linklen );
1611 (void) strcpy( rest, link );
1612 restlen = linklen;
1613 r = rest;
1614 }
1615
1616 if ( rest[0] == '/' )
1617 {
1618 /* There must have been an absolute symlink - zero out checked. */
1619 checked[0] = '\0';
1620 checkedlen = 0;
1621 }
1622 else
1623 {
1624 /* Re-check this component. */
1625 checkedlen = prevcheckedlen;
1626 checked[checkedlen] = '\0';
1627 }
1628 }
1629
1630 /* Ok. */
1631 *restP = r;
1632 if ( checked[0] == '\0' )
1633 (void) strcpy( checked, "." );
1634 return checked;
1635 }
1636
1637
1638 int
1639 httpd_get_conn( httpd_server* hs, int listen_fd, httpd_conn* hc )
1640 {
1641 httpd_sockaddr sa;
1642 int sz;
1643
1644 if ( ! hc->initialized )
1645 {
1646 hc->read_size = 0;
1647 httpd_realloc_str( &hc->read_buf, &hc->read_size, 500 );
1648 hc->maxdecodedurl =
1649 hc->maxorigfilename = hc->maxexpnfilename = hc->maxencodings =
1650 hc->maxpathinfo = hc->maxquery = hc->maxaccept =
1651 hc->maxaccepte = hc->maxreqhost = hc->maxhostdir =
1652 hc->maxremoteuser = hc->maxresponse = 0;
1653 #ifdef TILDE_MAP_2
1654 hc->maxaltdir = 0;
1655 #endif /* TILDE_MAP_2 */
1656 httpd_realloc_str( &hc->decodedurl, &hc->maxdecodedurl, 1 );
1657 httpd_realloc_str( &hc->origfilename, &hc->maxorigfilename, 1 );
1658 httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, 0 );
1659 httpd_realloc_str( &hc->encodings, &hc->maxencodings, 0 );
1660 httpd_realloc_str( &hc->pathinfo, &hc->maxpathinfo, 0 );
1661 httpd_realloc_str( &hc->query, &hc->maxquery, 0 );
1662 httpd_realloc_str( &hc->accept, &hc->maxaccept, 0 );
1663 httpd_realloc_str( &hc->accepte, &hc->maxaccepte, 0 );
1664 httpd_realloc_str( &hc->reqhost, &hc->maxreqhost, 0 );
1665 httpd_realloc_str( &hc->hostdir, &hc->maxhostdir, 0 );
1666 httpd_realloc_str( &hc->remoteuser, &hc->maxremoteuser, 0 );
1667 httpd_realloc_str( &hc->response, &hc->maxresponse, 0 );
1668 #ifdef TILDE_MAP_2
1669 httpd_realloc_str( &hc->altdir, &hc->maxaltdir, 0 );
1670 #endif /* TILDE_MAP_2 */
1671 hc->initialized = 1;
1672 }
1673
1674 /* Accept the new connection. */
1675 sz = sizeof(sa);
1676 hc->conn_fd = accept( listen_fd, &sa.sa, &sz );
1677 if ( hc->conn_fd < 0 )
1678 {
1679 if ( errno == EWOULDBLOCK )
1680 return GC_NO_MORE;
1681 syslog( LOG_ERR, "accept - %m" );
1682 return GC_FAIL;
1683 }
1684 if ( ! sockaddr_check( &sa ) )
1685 {
1686 syslog( LOG_ERR, "unknown sockaddr family" );
1687 return GC_FAIL;
1688 }
1689 (void) fcntl( hc->conn_fd, F_SETFD, 1 );
1690 hc->hs = hs;
1691 memset( &hc->client_addr, 0, sizeof(hc->client_addr) );
1692 memcpy( &hc->client_addr, &sa, sockaddr_len( &sa ) );
1693 hc->read_idx = 0;
1694 hc->checked_idx = 0;
1695 hc->checked_state = CHST_FIRSTWORD;
1696 hc->method = METHOD_UNKNOWN;
1697 hc->status = 0;
1698 hc->bytes_to_send = 0;
1699 hc->bytes_sent = 0;
1700 hc->encodedurl = "";
1701 hc->decodedurl[0] = '\0';
1702 hc->protocol = "UNKNOWN";
1703 hc->origfilename[0] = '\0';
1704 hc->expnfilename[0] = '\0';
1705 hc->encodings[0] = '\0';
1706 hc->pathinfo[0] = '\0';
1707 hc->query[0] = '\0';
1708 hc->referer = "";
1709 hc->useragent = "";
1710 hc->accept[0] = '\0';
1711 hc->accepte[0] = '\0';
1712 hc->acceptl = "";
1713 hc->cookie = "";
1714 hc->contenttype = "";
1715 hc->reqhost[0] = '\0';
1716 hc->hdrhost = "";
1717 hc->hostdir[0] = '\0';
1718 hc->authorization = "";
1719 hc->remoteuser[0] = '\0';
1720 hc->response[0] = '\0';
1721 #ifdef TILDE_MAP_2
1722 hc->altdir[0] = '\0';
1723 #endif /* TILDE_MAP_2 */
1724 hc->responselen = 0;
1725 hc->if_modified_since = (time_t) -1;
1726 hc->range_if = (time_t) -1;
1727 hc->contentlength = -1;
1728 hc->type = "";
1729 hc->hostname = (char*) 0;
1730 hc->mime_flag = 1;
1731 hc->one_one = 0;
1732 hc->got_range = 0;
1733 hc->tildemapped = 0;
1734 hc->init_byte_loc = 0;
1735 hc->end_byte_loc = -1;
1736 hc->keep_alive = 0;
1737 hc->should_linger = 0;
1738 hc->file_address = (char*) 0;
1739 #ifdef MMAP_MAX
1740 hc->file_fd = -1;
1741 hc->write_buf = (char*) 0;
1742 #endif
1743 return GC_OK;
1744 }
1745
1746
1747 /* Checks hc->read_buf to see whether a complete request has been read so far;
1748 ** either the first line has two words (an HTTP/0.9 request), or the first
1749 ** line has three words and there's a blank line present.
1750 **
1751 ** hc->read_idx is how much has been read in; hc->checked_idx is how much we
1752 ** have checked so far; and hc->checked_state is the current state of the
1753 ** finite state machine.
1754 */
1755 int
1756 httpd_got_request( httpd_conn* hc )
1757 {
1758 char c;
1759
1760 for ( ; hc->checked_idx < hc->read_idx; ++hc->checked_idx )
1761 {
1762 c = hc->read_buf[hc->checked_idx];
1763 switch ( hc->checked_state )
1764 {
1765 case CHST_FIRSTWORD:
1766 switch ( c )
1767 {
1768 case ' ': case '\t':
1769 hc->checked_state = CHST_FIRSTWS;
1770 break;
1771 case '\n': case '\r':
1772 hc->checked_state = CHST_BOGUS;
1773 return GR_BAD_REQUEST;
1774 }
1775 break;
1776 case CHST_FIRSTWS:
1777 switch ( c )
1778 {
1779 case ' ': case '\t':
1780 break;
1781 case '\n': case '\r':
1782 hc->checked_state = CHST_BOGUS;
1783 return GR_BAD_REQUEST;
1784 default:
1785 hc->checked_state = CHST_SECONDWORD;
1786 break;
1787 }
1788 break;
1789 case CHST_SECONDWORD:
1790 switch ( c )
1791 {
1792 case ' ': case '\t':
1793 hc->checked_state = CHST_SECONDWS;
1794 break;
1795 case '\n': case '\r':
1796 /* The first line has only two words - an HTTP/0.9 request. */
1797 return GR_GOT_REQUEST;
1798 }
1799 break;
1800 case CHST_SECONDWS:
1801 switch ( c )
1802 {
1803 case ' ': case '\t':
1804 break;
1805 case '\n': case '\r':
1806 hc->checked_state = CHST_BOGUS;
1807 return GR_BAD_REQUEST;
1808 default:
1809 hc->checked_state = CHST_THIRDWORD;
1810 break;
1811 }
1812 break;
1813 case CHST_THIRDWORD:
1814 switch ( c )
1815 {
1816 case ' ': case '\t':
1817 hc->checked_state = CHST_THIRDWS;
1818 break;
1819 case '\n':
1820 hc->checked_state = CHST_LF;
1821 break;
1822 case '\r':
1823 hc->checked_state = CHST_CR;
1824 break;
1825 }
1826 break;
1827 case CHST_THIRDWS:
1828 switch ( c )
1829 {
1830 case ' ': case '\t':
1831 break;
1832 case '\n':
1833 hc->checked_state = CHST_LF;
1834 break;
1835 case '\r':
1836 hc->checked_state = CHST_CR;
1837 break;
1838 default:
1839 hc->checked_state = CHST_BOGUS;
1840 return GR_BAD_REQUEST;
1841 }
1842 break;
1843 case CHST_LINE:
1844 switch ( c )
1845 {
1846 case '\n':
1847 hc->checked_state = CHST_LF;
1848 break;
1849 case '\r':
1850 hc->checked_state = CHST_CR;
1851 break;
1852 }
1853 break;
1854 case CHST_LF:
1855 switch ( c )
1856 {
1857 case '\n':
1858 /* Two newlines in a row - a blank line - end of request. */
1859 return GR_GOT_REQUEST;
1860 case '\r':
1861 hc->checked_state = CHST_CR;
1862 break;
1863 default:
1864 hc->checked_state = CHST_LINE;
1865 break;
1866 }
1867 break;
1868 case CHST_CR:
1869 switch ( c )
1870 {
1871 case '\n':
1872 hc->checked_state = CHST_CRLF;
1873 break;
1874 case '\r':
1875 /* Two returns in a row - end of request. */
1876 return GR_GOT_REQUEST;
1877 default:
1878 hc->checked_state = CHST_LINE;
1879 break;
1880 }
1881 break;
1882 case CHST_CRLF:
1883 switch ( c )
1884 {
1885 case '\n':
1886 /* Two newlines in a row - end of request. */
1887 return GR_GOT_REQUEST;
1888 case '\r':
1889 hc->checked_state = CHST_CRLFCR;
1890 break;
1891 default:
1892 hc->checked_state = CHST_LINE;
1893 break;
1894 }
1895 break;
1896 case CHST_CRLFCR:
1897 switch ( c )
1898 {
1899 case '\n': case '\r':
1900 /* Two CRLFs or two CRs in a row - end of request. */
1901 return GR_GOT_REQUEST;
1902 default:
1903 hc->checked_state = CHST_LINE;
1904 break;
1905 }
1906 break;
1907 case CHST_BOGUS:
1908 return GR_BAD_REQUEST;
1909 }
1910 }
1911 return GR_NO_REQUEST;
1912 }
1913
1914
1915 int
1916 httpd_parse_request( httpd_conn* hc )
1917 {
1918 char* buf;
1919 char* method_str;
1920 char* url;
1921 char* protocol;
1922 char* reqhost;
1923 char* eol;
1924 char* cp;
1925 char* pi;
1926
1927 hc->checked_idx = 0; /* reset */
1928 method_str = bufgets( hc );
1929 url = strpbrk( method_str, " \t\n\r" );
1930 if ( url == (char*) 0 )
1931 {
1932 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
1933 return -1;
1934 }
1935 *url++ = '\0';
1936 url += strspn( url, " \t\n\r" );
1937 protocol = strpbrk( url, " \t\n\r" );
1938 if ( protocol == (char*) 0 )
1939 {
1940 protocol = "HTTP/0.9";
1941 hc->mime_flag = 0;
1942 }
1943 else
1944 {
1945 *protocol++ = '\0';
1946 protocol += strspn( protocol, " \t\n\r" );
1947 if ( *protocol != '\0' )
1948 {
1949 eol = strpbrk( protocol, " \t\n\r" );
1950 if ( eol != (char*) 0 )
1951 *eol = '\0';
1952 if ( strcasecmp( protocol, "HTTP/1.0" ) != 0 )
1953 hc->one_one = 1;
1954 }
1955 }
1956 /* Check for HTTP/1.1 absolute URL. */
1957 if ( strncasecmp( url, "http://", 7 ) == 0 )
1958 {
1959 if ( ! hc->one_one )
1960 {
1961 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
1962 return -1;
1963 }
1964 reqhost = url + 7;
1965 url = strchr( reqhost, '/' );
1966 if ( url == (char*) 0 )
1967 {
1968 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
1969 return -1;
1970 }
1971 *url = '\0';
1972 httpd_realloc_str( &hc->reqhost, &hc->maxreqhost, strlen( reqhost ) );
1973 (void) strcpy( hc->reqhost, reqhost );
1974 *url = '/';
1975 }
1976
1977 if ( strcasecmp( method_str, httpd_method_str( METHOD_GET ) ) == 0 )
1978 hc->method = METHOD_GET;
1979 else if ( strcasecmp( method_str, httpd_method_str( METHOD_HEAD ) ) == 0 )
1980 hc->method = METHOD_HEAD;
1981 else if ( strcasecmp( method_str, httpd_method_str( METHOD_POST ) ) == 0 )
1982 hc->method = METHOD_POST;
1983 else
1984 {
1985 httpd_send_err( hc, 501, err501title, "", err501form, method_str );
1986 return -1;
1987 }
1988
1989 hc->encodedurl = url;
1990 httpd_realloc_str(
1991 &hc->decodedurl, &hc->maxdecodedurl, strlen( hc->encodedurl ) );
1992 strdecode( hc->decodedurl, hc->encodedurl );
1993
1994 de_dotdot( hc->decodedurl );
1995 if ( hc->decodedurl[0] != '/' || hc->decodedurl[1] == '/' ||
1996 ( hc->decodedurl[1] == '.' && hc->decodedurl[2] == '.' &&
1997 ( hc->decodedurl[3] == '\0' || hc->decodedurl[3] == '/' ) ) )
1998 {
1999 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
2000 return -1;
2001 }
2002
2003 hc->protocol = protocol;
2004
2005 httpd_realloc_str(
2006 &hc->origfilename, &hc->maxorigfilename, strlen( hc->decodedurl ) );
2007 (void) strcpy( hc->origfilename, &hc->decodedurl[1] );
2008 /* Special case for top-level URL. */
2009 if ( hc->origfilename[0] == '\0' )
2010 (void) strcpy( hc->origfilename, "." );
2011
2012 /* Extract query string from encoded URL. */
2013 cp = strchr( hc->encodedurl, '?' );
2014 if ( cp != (char*) 0 )
2015 {
2016 ++cp;
2017 httpd_realloc_str( &hc->query, &hc->maxquery, strlen( cp ) );
2018 (void) strcpy( hc->query, cp );
2019 }
2020 /* And remove query from filename. */
2021 cp = strchr( hc->origfilename, '?' );
2022 if ( cp != (char*) 0 )
2023 *cp = '\0';
2024
2025 if ( hc->mime_flag )
2026 {
2027 /* Read the MIME headers. */
2028 while ( ( buf = bufgets( hc ) ) != (char*) 0 )
2029 {
2030 if ( buf[0] == '\0' )
2031 break;
2032 if ( strncasecmp( buf, "Referer:", 8 ) == 0 )
2033 {
2034 cp = &buf[8];
2035 cp += strspn( cp, " \t" );
2036 hc->referer = cp;
2037 }
2038 else if ( strncasecmp( buf, "User-Agent:", 11 ) == 0 )
2039 {
2040 cp = &buf[11];
2041 cp += strspn( cp, " \t" );
2042 hc->useragent = cp;
2043 }
2044 else if ( strncasecmp( buf, "Host:", 5 ) == 0 )
2045 {
2046 cp = &buf[5];
2047 cp += strspn( cp, " \t" );
2048 hc->hdrhost = cp;
2049 cp = strchr( hc->hdrhost, ':' );
2050 if ( cp != (char*) 0 )
2051 *cp = '\0';
2052 }
2053 else if ( strncasecmp( buf, "Accept:", 7 ) == 0 )
2054 {
2055 cp = &buf[7];
2056 cp += strspn( cp, " \t" );
2057 if ( hc->accept[0] != '\0' )
2058 {
2059 if ( strlen( hc->accept ) > 5000 )
2060 {
2061 syslog(
2062 LOG_ERR, "%.80s way too much Accept: data",
2063 httpd_ntoa( &hc->client_addr ) );
2064 continue;
2065 }
2066 httpd_realloc_str(
2067 &hc->accept, &hc->maxaccept,
2068 strlen( hc->accept ) + 2 + strlen( cp ) );
2069 (void) strcat( hc->accept, ", " );
2070 }
2071 else
2072 httpd_realloc_str(
2073 &hc->accept, &hc->maxaccept, strlen( cp ) );
2074 (void) strcat( hc->accept, cp );
2075 }
2076 else if ( strncasecmp( buf, "Accept-Encoding:", 16 ) == 0 )
2077 {
2078 cp = &buf[16];
2079 cp += strspn( cp, " \t" );
2080 if ( hc->accepte[0] != '\0' )
2081 {
2082 if ( strlen( hc->accepte ) > 5000 )
2083 {
2084 syslog(
2085 LOG_ERR, "%.80s way too much Accept-Encoding: data",
2086 httpd_ntoa( &hc->client_addr ) );
2087 continue;
2088 }
2089 httpd_realloc_str(
2090 &hc->accepte, &hc->maxaccepte,
2091 strlen( hc->accepte ) + 2 + strlen( cp ) );
2092 (void) strcat( hc->accepte, ", " );
2093 }
2094 else
2095 httpd_realloc_str(
2096 &hc->accepte, &hc->maxaccepte, strlen( cp ) );
2097 (void) strcpy( hc->accepte, cp );
2098 }
2099 else if ( strncasecmp( buf, "Accept-Language:", 16 ) == 0 )
2100 {
2101 cp = &buf[16];
2102 cp += strspn( cp, " \t" );
2103 hc->acceptl = cp;
2104 }
2105 else if ( strncasecmp( buf, "If-Modified-Since:", 18 ) == 0 )
2106 {
2107 cp = &buf[18];
2108 hc->if_modified_since = tdate_parse( cp );
2109 if ( hc->if_modified_since == (time_t) -1 )
2110 syslog( LOG_DEBUG, "unparsable time: %.80s", cp );
2111 }
2112 else if ( strncasecmp( buf, "Cookie:", 7 ) == 0 )
2113 {
2114 cp = &buf[7];
2115 cp += strspn( cp, " \t" );
2116 hc->cookie = cp;
2117 }
2118 else if ( strncasecmp( buf, "Range:", 6 ) == 0 )
2119 {
2120 /* Only support %d- and %d-%d, not %d-%d,%d-%d or -%d. */
2121 if ( strchr( buf, ',' ) == (char*) 0 )
2122 {
2123 char* cp_dash;
2124 cp = strpbrk( buf, "=" );
2125 if ( cp != (char*) 0 )
2126 {
2127 cp_dash = strchr( cp + 1, '-' );
2128 if ( cp_dash != (char*) 0 && cp_dash != cp + 1 )
2129 {
2130 *cp_dash = '\0';
2131 hc->got_range = 1;
2132 hc->init_byte_loc = atol( cp + 1 );
2133 if ( isdigit( (int) cp_dash[1] ) )
2134 hc->end_byte_loc = atol( cp_dash + 1 );
2135 }
2136 }
2137 }
2138 }
2139 else if ( strncasecmp( buf, "Range-If:", 9 ) == 0 ||
2140 strncasecmp( buf, "If-Range:", 9 ) == 0 )
2141 {
2142 cp = &buf[9];
2143 hc->range_if = tdate_parse( cp );
2144 if ( hc->range_if == (time_t) -1 )
2145 syslog( LOG_DEBUG, "unparsable time: %.80s", cp );
2146 }
2147 else if ( strncasecmp( buf, "Content-Type:", 13 ) == 0 )
2148 {
2149 cp = &buf[13];
2150 cp += strspn( cp, " \t" );
2151 hc->contenttype = cp;
2152 }
2153 else if ( strncasecmp( buf, "Content-Length:", 15 ) == 0 )
2154 {
2155 cp = &buf[15];
2156 hc->contentlength = atol( cp );
2157 }
2158 else if ( strncasecmp( buf, "Authorization:", 14 ) == 0 )
2159 {
2160 cp = &buf[14];
2161 cp += strspn( cp, " \t" );
2162 hc->authorization = cp;
2163 }
2164 else if ( strncasecmp( buf, "Connection:", 11 ) == 0 )
2165 {
2166 cp = &buf[11];
2167 cp += strspn( cp, " \t" );
2168 if ( strcasecmp( cp, "keep-alive" ) == 0 )
2169 hc->keep_alive = 1;
2170 }
2171 #ifdef LOG_UNKNOWN_HEADERS
2172 else if ( strncasecmp( buf, "Accept-Charset:", 15 ) == 0 ||
2173 strncasecmp( buf, "Accept-Language:", 16 ) == 0 ||
2174 strncasecmp( buf, "Agent:", 6 ) == 0 ||
2175 strncasecmp( buf, "Cache-Control:", 14 ) == 0 ||
2176 strncasecmp( buf, "Cache-Info:", 11 ) == 0 ||
2177 strncasecmp( buf, "Charge-To:", 10 ) == 0 ||
2178 strncasecmp( buf, "Client-IP:", 10 ) == 0 ||
2179 strncasecmp( buf, "Date:", 5 ) == 0 ||
2180 strncasecmp( buf, "Extension:", 10 ) == 0 ||
2181 strncasecmp( buf, "Forwarded:", 10 ) == 0 ||
2182 strncasecmp( buf, "From:", 5 ) == 0 ||
2183 strncasecmp( buf, "HTTP-Version:", 13 ) == 0 ||
2184 strncasecmp( buf, "Max-Forwards:", 13 ) == 0 ||
2185 strncasecmp( buf, "Message-Id:", 11 ) == 0 ||
2186 strncasecmp( buf, "MIME-Version:", 13 ) == 0 ||
2187 strncasecmp( buf, "Negotiate:", 10 ) == 0 ||
2188 strncasecmp( buf, "Pragma:", 7 ) == 0 ||
2189 strncasecmp( buf, "Proxy-Agent:", 12 ) == 0 ||
2190 strncasecmp( buf, "Proxy-Connection:", 17 ) == 0 ||
2191 strncasecmp( buf, "Security-Scheme:", 16 ) == 0 ||
2192 strncasecmp( buf, "Session-Id:", 11 ) == 0 ||
2193 strncasecmp( buf, "UA-Color:", 9 ) == 0 ||
2194 strncasecmp( buf, "UA-CPU:", 7 ) == 0 ||
2195 strncasecmp( buf, "UA-Disp:", 8 ) == 0 ||
2196 strncasecmp( buf, "UA-OS:", 6 ) == 0 ||
2197 strncasecmp( buf, "UA-Pixels:", 10 ) == 0 ||
2198 strncasecmp( buf, "User:", 5 ) == 0 ||
2199 strncasecmp( buf, "Via:", 4 ) == 0 ||
2200 strncasecmp( buf, "X-", 2 ) == 0 )
2201 ; /* ignore */
2202 else
2203 syslog( LOG_DEBUG, "unknown request header: %.80s", buf );
2204 #endif /* LOG_UNKNOWN_HEADERS */
2205 }
2206 }
2207
2208 if ( hc->one_one )
2209 {
2210 /* Check that HTTP/1.1 requests specify a host, as required. */
2211 if ( hc->reqhost[0] == '\0' && hc->hdrhost[0] == '\0' )
2212 {
2213 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
2214 return -1;
2215 }
2216
2217 /* If the client wants to do keep-alives, it might also be doing
2218 ** pipelining. There's no way for us to tell. Since we don't
2219 ** implement keep-alives yet, if we close such a connection there
2220 ** might be unread pipelined requests waiting. So, we have to
2221 ** do a lingering close.
2222 */
2223 if ( hc->keep_alive )
2224 hc->should_linger = 1;
2225 }
2226
2227 /* Ok, the request has been parsed. Now we resolve stuff that
2228 ** may require the entire request.
2229 */
2230
2231 /* Copy original filename to expanded filename. */
2232 httpd_realloc_str(
2233 &hc->expnfilename, &hc->maxexpnfilename, strlen( hc->origfilename ) );
2234 (void) strcpy( hc->expnfilename, hc->origfilename );
2235
2236 /* Tilde mapping. */
2237 if ( hc->expnfilename[0] == '~' )
2238 {
2239 #ifdef TILDE_MAP_1
2240 if ( ! tilde_map_1( hc ) )
2241 {
2242 httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
2243 return -1;
2244 }
2245 #endif /* TILDE_MAP_1 */
2246 #ifdef TILDE_MAP_2
2247 if ( ! tilde_map_2( hc ) )
2248 {
2249 httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
2250 return -1;
2251 }
2252 #endif /* TILDE_MAP_2 */
2253 }
2254
2255 /* Virtual host mapping. */
2256 if ( hc->hs->vhost )
2257 if ( ! vhost_map( hc ) )
2258 {
2259 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
2260 return -1;
2261 }
2262
2263 /* Expand all symbolic links in the filename. This also gives us
2264 ** any trailing non-existing components, for pathinfo.
2265 */
2266 cp = expand_symlinks( hc->expnfilename, &pi, hc->hs->no_symlink, hc->tildemapped );
2267 if ( cp == (char*) 0 )
2268 {
2269 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
2270 return -1;
2271 }
2272 httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, strlen( cp ) );
2273 (void) strcpy( hc->expnfilename, cp );
2274 httpd_realloc_str( &hc->pathinfo, &hc->maxpathinfo, strlen( pi ) );
2275 (void) strcpy( hc->pathinfo, pi );
2276
2277 /* Remove pathinfo stuff from the original filename too. */
2278 if ( hc->pathinfo[0] != '\0' )
2279 {
2280 int i;
2281 i = strlen( hc->origfilename ) - strlen( hc->pathinfo );
2282 if ( i > 0 && strcmp( &hc->origfilename[i], hc->pathinfo ) == 0 )
2283 hc->origfilename[i - 1] = '\0';
2284 }
2285
2286 /* If the expanded filename is an absolute path, check that it's still
2287 ** within the current directory or the alternate directory.
2288 */
2289 if ( hc->expnfilename[0] == '/' )
2290 {
2291 if ( strncmp(
2292 hc->expnfilename, hc->hs->cwd, strlen( hc->hs->cwd ) ) == 0 )
2293 {
2294 /* Elide the current directory. */
2295 (void) strcpy(
2296 hc->expnfilename, &hc->expnfilename[strlen( hc->hs->cwd )] );
2297 }
2298 #ifdef TILDE_MAP_2
2299 else if ( hc->altdir[0] != '\0' &&
2300 ( strncmp(
2301 hc->expnfilename, hc->altdir,
2302 strlen( hc->altdir ) ) == 0 &&
2303 ( hc->expnfilename[strlen( hc->altdir )] == '\0' ||
2304 hc->expnfilename[strlen( hc->altdir )] == '/' ) ) )
2305 {}
2306 #endif /* TILDE_MAP_2 */
2307 else
2308 {
2309 syslog(
2310 LOG_NOTICE, "%.80s URL \"%.80s\" goes outside the web tree",
2311 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
2312 httpd_send_err(
2313 hc, 403, err403title, "",
2314 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file outside the permitted web server directory tree.\n" ),
2315 hc->encodedurl );
2316 return -1;
2317 }
2318 }
2319
2320 return 0;
2321 }
2322
2323
2324 static char*
2325 bufgets( httpd_conn* hc )
2326 {
2327 int i;
2328 char c;
2329
2330 for ( i = hc->checked_idx; hc->checked_idx < hc->read_idx; ++hc->checked_idx )
2331 {
2332 c = hc->read_buf[hc->checked_idx];
2333 if ( c == '\n' || c == '\r' )
2334 {
2335 hc->read_buf[hc->checked_idx] = '\0';
2336 ++hc->checked_idx;
2337 if ( c == '\r' && hc->checked_idx < hc->read_idx &&
2338 hc->read_buf[hc->checked_idx] == '\n' )
2339 {
2340 hc->read_buf[hc->checked_idx] = '\0';
2341 ++hc->checked_idx;
2342 }
2343 return &(hc->read_buf[i]);
2344 }
2345 }
2346 return (char*) 0;
2347 }
2348
2349
2350 static void
2351 de_dotdot( char* file )
2352 {
2353 char* cp;
2354 char* cp2;
2355 int l;
2356
2357 /* Collapse any multiple / sequences. */
2358 while ( ( cp = strstr( file, "//") ) != (char*) 0 )
2359 {
2360 for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 )
2361 continue;
2362 (void) strcpy( cp + 1, cp2 );
2363 }
2364
2365 /* Elide any xxx/../ sequences. */
2366 while ( ( cp = strstr( file, "/../" ) ) != (char*) 0 )
2367 {
2368 for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
2369 continue;
2370 if ( cp2 < file )
2371 break;
2372 (void) strcpy( cp2, cp + 3 );
2373 }
2374
2375 /* Also elide any xxx/.. at the end. */
2376 while ( ( l = strlen( file ) ) > 3 &&
2377 strcmp( ( cp = file + l - 3 ), "/.." ) == 0 )
2378 {
2379 for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
2380 continue;
2381 if ( cp2 < file )
2382 break;
2383 *cp2 = '\0';
2384 }
2385 }
2386
2387
2388 void
2389 httpd_close_conn( httpd_conn* hc, struct timeval* nowP )
2390 {
2391 make_log_entry( hc, nowP );
2392
2393 #ifdef MMAP_MAX
2394 if ( hc->file_fd >= 0)
2395 {
2396 (void) close( hc->file_fd );
2397 hc->file_fd = -1;
2398 }
2399 if ( hc->write_buf )
2400 (void) free (hc->write_buf);
2401 #endif
2402 if ( hc->file_address != (char*) 0 )
2403 {
2404 mmc_unmap( hc->file_address, &(hc->sb), nowP );
2405 hc->file_address = (char*) 0;
2406 }
2407 if ( hc->conn_fd >= 0 )
2408 {
2409 (void) close( hc->conn_fd );
2410 hc->conn_fd = -1;
2411 }
2412 }
2413
2414 void
2415 httpd_destroy_conn( httpd_conn* hc )
2416 {
2417 if ( hc->initialized )
2418 {
2419 free( (void*) hc->read_buf );
2420 free( (void*) hc->decodedurl );
2421 free( (void*) hc->origfilename );
2422 free( (void*) hc->expnfilename );
2423 free( (void*) hc->encodings );
2424 free( (void*) hc->pathinfo );
2425 free( (void*) hc->query );
2426 free( (void*) hc->accept );
2427 free( (void*) hc->accepte );
2428 free( (void*) hc->reqhost );
2429 free( (void*) hc->hostdir );
2430 free( (void*) hc->remoteuser );
2431 free( (void*) hc->response );
2432 #ifdef TILDE_MAP_2
2433 free( (void*) hc->altdir );
2434 #endif /* TILDE_MAP_2 */
2435 hc->initialized = 0;
2436 }
2437 }
2438
2439
2440 /* Figures out MIME encodings and type based on the filename. Multiple
2441 ** encodings are separated by semicolons.
2442 */
2443 static void
2444 figure_mime( httpd_conn* hc )
2445 {
2446 int i, j, k, l;
2447 int got_enc;
2448 struct table {
2449 char* ext;
2450 char* val;
2451 };
2452 static struct table enc_tab[] = {
2453 #include "mime_encodings.h"
2454 };
2455 static struct table typ_tab[] = {
2456 #include "mime_types.h"
2457 };
2458
2459 /* Look at the extensions on hc->expnfilename from the back forwards. */
2460 i = strlen( hc->expnfilename );
2461 for (;;)
2462 {
2463 j = i;
2464 for (;;)
2465 {
2466 --i;
2467 if ( i <= 0 )
2468 {
2469 /* No extensions left. */
2470 hc->type = "text/plain; charset=%s";
2471 return;
2472 }
2473 if ( hc->expnfilename[i] == '.' )
2474 break;
2475 }
2476 /* Found an extension. */
2477 got_enc = 0;
2478 for ( k = 0; k < sizeof(enc_tab)/sizeof(*enc_tab); ++k )
2479 {
2480 l = strlen( enc_tab[k].ext );
2481 if ( l == j - i - 1 &&
2482 strncasecmp( &hc->expnfilename[i+1], enc_tab[k].ext, l ) == 0 )
2483 {
2484 httpd_realloc_str(
2485 &hc->encodings, &hc->maxencodings,
2486 strlen( enc_tab[k].val ) + 1 );
2487 if ( hc->encodings[0] != '\0' )
2488 (void) strcat( hc->encodings, ";" );
2489 (void) strcat( hc->encodings, enc_tab[k].val );
2490 got_enc = 1;
2491 }
2492 }
2493 if ( ! got_enc )
2494 {
2495 /* No encoding extension found - time to try type extensions. */
2496 for ( k = 0; k < sizeof(typ_tab)/sizeof(*typ_tab); ++k )
2497 {
2498 l = strlen( typ_tab[k].ext );
2499 if ( l == j - i - 1 &&
2500 strncasecmp(
2501 &hc->expnfilename[i+1], typ_tab[k].ext, l ) == 0 )
2502 {
2503 hc->type = typ_tab[k].val;
2504 return;
2505 }
2506 }
2507 /* No recognized type extension found - return default. */
2508 hc->type = "text/plain; charset=%s";
2509 return;
2510 }
2511 }
2512 }
2513
2514
2515 #ifdef CGI_TIMELIMIT
2516 static void
2517 cgi_kill2( ClientData client_data, struct timeval* nowP )
2518 {
2519 pid_t pid;
2520
2521 /* Before trying to kill the CGI process, reap any zombie processes.
2522 ** That may get rid of the CGI process.
2523 */
2524 (void) do_reap();
2525
2526 pid = (pid_t) client_data.i;
2527 if ( kill( pid, SIGKILL ) == 0 )
2528 syslog( LOG_ERR, "hard-killed CGI process %d", pid );
2529 }
2530
2531 static void
2532 cgi_kill( ClientData client_data, struct timeval* nowP )
2533 {
2534 pid_t pid;
2535
2536 /* Before trying to kill the CGI process, reap any zombie processes.
2537 ** That may get rid of the CGI process.
2538 */
2539 (void) do_reap();
2540
2541 pid = (pid_t) client_data.i;
2542 if ( kill( pid, SIGINT ) == 0 )
2543 {
2544 syslog( LOG_ERR, "killed CGI process %d", pid );
2545 /* In case this isn't enough, schedule an uncatchable kill. */
2546 if ( tmr_create( nowP, cgi_kill2, client_data, 5 * 1000L, 0 ) == (Timer*) 0 )
2547 {
2548 syslog( LOG_CRIT, "tmr_create(cgi_kill2) failed" );
2549 exit( 1 );
2550 }
2551 }
2552 }
2553 #endif /* CGI_TIMELIMIT */
2554
2555
2556 #ifdef GENERATE_INDEXES
2557
2558 /* qsort comparison routine - declared old-style on purpose, for portability. */
2559 static int
2560 name_compare( a, b )
2561 char** a;
2562 char** b;
2563 {
2564 return strcmp( *a, *b );
2565 }
2566
2567
2568 static off_t
2569 ls( httpd_conn* hc )
2570 {
2571 DIR* dirp;
2572 struct dirent* de;
2573 int namlen;
2574 static int maxnames = 0;
2575 int nnames;
2576 static char* names;
2577 static char** nameptrs;
2578 static char* name;
2579 static int maxname = 0;
2580 static char* rname;
2581 static int maxrname = 0;
2582 static char* encrname;
2583 static int maxencrname = 0;
2584 FILE* fp;
2585 int i, r;
2586 struct stat sb;
2587 struct stat lsb;
2588 char modestr[20];
2589 char* linkprefix;
2590 char link[MAXPATHLEN];
2591 int linklen;
2592 char* fileclass;
2593 time_t now;
2594 char* timestr;
2595 ClientData client_data;
2596
2597 dirp = opendir( hc->expnfilename );
2598 if ( dirp == (DIR*) 0 )
2599 {
2600 syslog( LOG_ERR, "opendir %.80s - %m", hc->expnfilename );
2601 httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
2602 return -1;
2603 }
2604
2605 send_mime( hc, 200, ok200title, "", "", "text/html", -1, hc->sb.st_mtime );
2606 if ( hc->method == METHOD_HEAD )
2607 closedir( dirp );
2608 else if ( hc->method == METHOD_GET )
2609 {
2610 httpd_write_response( hc );
2611 r = fork( );
2612 if ( r < 0 )
2613 {
2614 syslog( LOG_ERR, "fork - %m" );
2615 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
2616 return -1;
2617 }
2618 if ( r == 0 )
2619 {
2620 /* Child process. */
2621 unlisten( hc->hs );
2622
2623 #ifdef CGI_NICE
2624 /* Set priority. */
2625 (void) nice( CGI_NICE );
2626 #endif /* CGI_NICE */
2627
2628 /* Open a stdio stream so that we can use fprintf, which is more
2629 ** efficient than a bunch of separate write()s. We don't have
2630 ** to worry about double closes or file descriptor leaks cause
2631 ** we're in a subprocess.
2632 */
2633 fp = fdopen( hc->conn_fd, "w" );
2634 if ( fp == (FILE*) 0 )
2635 {
2636 syslog( LOG_ERR, "fdopen - %m" );
2637 httpd_send_err(
2638 hc, 500, err500title, "", err500form, hc->encodedurl );
2639 closedir( dirp );
2640 exit( 1 );
2641 }
2642
2643 (void) fprintf( fp, "\
2644 <HTML><HEAD><TITLE>Index of %.80s</TITLE></HEAD>\n\
2645 <BODY BGCOLOR=\"#99cc99\">\n\
2646 <H2>Index of %.80s</H2>\n\
2647 <PRE>\n\
2648 mode links bytes last-changed name\n\
2649 <HR>",
2650 hc->encodedurl, hc->encodedurl );
2651
2652 /* Read in names. */
2653 nnames = 0;
2654 while ( ( de = readdir( dirp ) ) != 0 ) /* dirent or direct */
2655 {
2656 if ( nnames >= maxnames )
2657 {
2658 if ( maxnames == 0 )
2659 {
2660 maxnames = 100;
2661 names = NEW( char, maxnames * MAXPATHLEN );
2662 nameptrs = NEW( char*, maxnames );
2663 }
2664 else
2665 {
2666 maxnames *= 2;
2667 names = RENEW( names, char, maxnames * MAXPATHLEN );
2668 nameptrs = RENEW( nameptrs, char*, maxnames );
2669 }
2670 if ( names == (char*) 0 || nameptrs == (char**) 0 )
2671 {
2672 syslog( LOG_ERR, "out of memory reallocating directory names" );
2673 exit( 1 );
2674 }
2675 for ( i = 0; i < maxnames; ++i )
2676 nameptrs[i] = &names[i * MAXPATHLEN];
2677 }
2678 namlen = NAMLEN(de);
2679 (void) strncpy( nameptrs[nnames], de->d_name, namlen );
2680 nameptrs[nnames][namlen] = '\0';
2681 ++nnames;
2682 }
2683 closedir( dirp );
2684
2685 /* Sort the names. */
2686 qsort( nameptrs, nnames, sizeof(*nameptrs), name_compare );
2687
2688 /* Generate output. */
2689 for ( i = 0; i < nnames; ++i )
2690 {
2691 httpd_realloc_str(
2692 &name, &maxname,
2693 strlen( hc->expnfilename ) + 1 + strlen( nameptrs[i] ) );
2694 httpd_realloc_str(
2695 &rname, &maxrname,
2696 strlen( hc->origfilename ) + 1 + strlen( nameptrs[i] ) );
2697 if ( hc->expnfilename[0] == '\0' ||
2698 strcmp( hc->expnfilename, "." ) == 0 )
2699 {
2700 (void) strcpy( name, nameptrs[i] );
2701 (void) strcpy( rname, nameptrs[i] );
2702 }
2703 else
2704 {
2705 (void) my_snprintf( name, maxname,
2706 "%s/%s", hc->expnfilename, nameptrs[i] );
2707 if ( strcmp( hc->origfilename, "." ) == 0 )
2708 (void) my_snprintf( rname, maxrname,
2709 "%s", nameptrs[i] );
2710 else
2711 (void) my_snprintf( rname, maxrname,
2712 "%s%s", hc->origfilename, nameptrs[i] );
2713 }
2714 httpd_realloc_str(
2715 &encrname, &maxencrname, 3 * strlen( rname ) + 1 );
2716 strencode( encrname, maxencrname, rname );
2717
2718 if ( stat( name, &sb ) < 0 || lstat( name, &lsb ) < 0 )
2719 continue;
2720
2721 linkprefix = "";
2722 link[0] = '\0';
2723 /* Break down mode word. First the file type. */
2724 switch ( lsb.st_mode & S_IFMT )
2725 {
2726 case S_IFIFO: modestr[0] = 'p'; break;
2727 case S_IFCHR: modestr[0] = 'c'; break;
2728 case S_IFDIR: modestr[0] = 'd'; break;
2729 case S_IFBLK: modestr[0] = 'b'; break;
2730 case S_IFREG: modestr[0] = '-'; break;
2731 case S_IFSOCK: modestr[0] = 's'; break;
2732 case S_IFLNK: modestr[0] = 'l';
2733 linklen = readlink( name, link, sizeof(link) );
2734 if ( linklen != -1 )
2735 {
2736 link[linklen] = '\0';
2737 linkprefix = " -> ";
2738 }
2739 break;
2740 default: modestr[0] = '?'; break;
2741 }
2742 /* Now the world permissions. Owner and group permissions
2743 ** are not of interest to web clients.
2744 */
2745 modestr[1] = ( lsb.st_mode & S_IROTH ) ? 'r' : '-';
2746 modestr[2] = ( lsb.st_mode & S_IWOTH ) ? 'w' : '-';
2747 modestr[3] = ( lsb.st_mode & S_IXOTH ) ? 'x' : '-';
2748 modestr[4] = '\0';
2749
2750 /* We also leave out the owner and group name, they are
2751 ** also not of interest to web clients. Plus if we're
2752 ** running under chroot(), they would require a copy
2753 ** of /etc/passwd and /etc/group, which we want to avoid.
2754 */
2755
2756 /* Get time string. */
2757 now = time( (time_t*) 0 );
2758 timestr = ctime( &lsb.st_mtime );
2759 timestr[ 0] = timestr[ 4];
2760 timestr[ 1] = timestr[ 5];
2761 timestr[ 2] = timestr[ 6];
2762 timestr[ 3] = ' ';
2763 timestr[ 4] = timestr[ 8];
2764 timestr[ 5] = timestr[ 9];
2765 timestr[ 6] = ' ';
2766 if ( now - lsb.st_mtime > 60*60*24*182 ) /* 1/2 year */
2767 {
2768 timestr[ 7] = ' ';
2769 timestr[ 8] = timestr[20];
2770 timestr[ 9] = timestr[21];
2771 timestr[10] = timestr[22];
2772 timestr[11] = timestr[23];
2773 }
2774 else
2775 {
2776 timestr[ 7] = timestr[11];
2777 timestr[ 8] = timestr[12];
2778 timestr[ 9] = ':';
2779 timestr[10] = timestr[14];
2780 timestr[11] = timestr[15];
2781 }
2782 timestr[12] = '\0';
2783
2784 /* The ls -F file class. */
2785 switch ( sb.st_mode & S_IFMT )
2786 {
2787 case S_IFDIR: fileclass = "/"; break;
2788 case S_IFSOCK: fileclass = "="; break;
2789 case S_IFLNK: fileclass = "@"; break;
2790 default:
2791 fileclass = ( sb.st_mode & S_IXOTH ) ? "*" : "";
2792 break;
2793 }
2794
2795 /* And print. */
2796 (void) fprintf( fp,
2797 "%s %3ld %8ld %s <A HREF=\"/%.500s%s\">%.80s</A>%s%s%s\n",
2798 modestr, (long) lsb.st_nlink, (long) lsb.st_size, timestr,
2799 encrname, S_ISDIR(sb.st_mode) ? "/" : "",
2800 nameptrs[i], linkprefix, link, fileclass );
2801 }
2802
2803 (void) fprintf( fp, "</PRE></BODY></HTML>\n" );
2804 (void) fclose( fp );
2805 exit( 0 );
2806 }
2807
2808 /* Parent process. */
2809 closedir( dirp );
2810 syslog( LOG_INFO, "spawned indexing process %d for directory '%.200s'", r, hc->expnfilename );
2811 #ifdef CGI_TIMELIMIT
2812 /* Schedule a kill for the child process, in case it runs too long */
2813 client_data.i = r;
2814 if ( tmr_create( (struct timeval*) 0, cgi_kill, client_data, CGI_TIMELIMIT * 1000L, 0 ) == (Timer*) 0 )
2815 {
2816 syslog( LOG_CRIT, "tmr_create(cgi_kill) failed" );
2817 exit( 1 );
2818 }
2819 #endif /* CGI_TIMELIMIT */
2820 hc->status = 200;
2821 hc->bytes_sent = CGI_BYTECOUNT;
2822 hc->should_linger = 0;
2823 }
2824 else
2825 {
2826 httpd_send_err(
2827 hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) );
2828 return -1;
2829 }
2830
2831 return 0;
2832 }
2833
2834 #endif /* GENERATE_INDEXES */
2835
2836
2837 static char*
2838 build_env( char* fmt, char* arg )
2839 {
2840 char* cp;
2841 int size;
2842 static char* buf;
2843 static int maxbuf = 0;
2844
2845 size = strlen( fmt ) + strlen( arg );
2846 if ( size > maxbuf )
2847 httpd_realloc_str( &buf, &maxbuf, size );
2848 (void) my_snprintf( buf, maxbuf,
2849 fmt, arg );
2850 cp = strdup( buf );
2851 if ( cp == (char*) 0 )
2852 {
2853 syslog( LOG_ERR, "out of memory copying environment variable" );
2854 exit( 1 );
2855 }
2856 return cp;
2857 }
2858
2859
2860 #ifdef SERVER_NAME_LIST
2861 static char*
2862 hostname_map( char* hostname )
2863 {
2864 int len, n;
2865 static char* list[] = { SERVER_NAME_LIST };
2866
2867 len = strlen( hostname );
2868 for ( n = sizeof(list) / sizeof(*list) - 1; n >= 0; --n )
2869 if ( strncasecmp( hostname, list[n], len ) == 0 )
2870 if ( list[n][len] == '/' ) /* check in case of a substring match */
2871 return &list[n][len + 1];
2872 return (char*) 0;
2873 }
2874 #endif /* SERVER_NAME_LIST */
2875
2876
2877 /* Set up environment variables. Be real careful here to avoid
2878 ** letting malicious clients overrun a buffer. We don't have
2879 ** to worry about freeing stuff since we're a sub-process.
2880 */
2881 static char**
2882 make_envp( httpd_conn* hc )
2883 {
2884 static char* envp[50];
2885 int envn;
2886 char* cp;
2887 char buf[256];
2888
2889 envn = 0;
2890 envp[envn++] = build_env( "PATH=%s", CGI_PATH );
2891 #ifdef CGI_LD_LIBRARY_PATH
2892 envp[envn++] = build_env( "LD_LIBRARY_PATH=%s", CGI_LD_LIBRARY_PATH );
2893 #endif /* CGI_LD_LIBRARY_PATH */
2894 envp[envn++] = build_env( "SERVER_SOFTWARE=%s", SERVER_SOFTWARE );
2895 /* If vhosting, use that server-name here. */
2896 if ( hc->hs->vhost && hc->hostname != (char*) 0 )
2897 cp = hc->hostname;
2898 else
2899 cp = hc->hs->server_hostname;
2900 if ( cp != (char*) 0 )
2901 envp[envn++] = build_env( "SERVER_NAME=%s", cp );
2902 envp[envn++] = "GATEWAY_INTERFACE=CGI/1.1";
2903 envp[envn++] = build_env("SERVER_PROTOCOL=%s", hc->protocol);
2904 (void) my_snprintf( buf, sizeof(buf),
2905 "%d", hc->hs->port );
2906 envp[envn++] = build_env( "SERVER_PORT=%s", buf );
2907 envp[envn++] = build_env(
2908 "REQUEST_METHOD=%s", httpd_method_str( hc->method ) );
2909 if ( hc->pathinfo[0] != '\0' )
2910 {
2911 char* cp2;
2912 int l;
2913 envp[envn++] = build_env( "PATH_INFO=/%s", hc->pathinfo );
2914 l = strlen( hc->hs->cwd ) + strlen( hc->pathinfo ) + 1;
2915 cp2 = NEW( char, l );
2916 if ( cp2 != (char*) 0 )
2917 {
2918 (void) my_snprintf( cp2, l,
2919 "%s%s", hc->hs->cwd, hc->pathinfo );
2920 envp[envn++] = build_env( "PATH_TRANSLATED=%s", cp2 );
2921 }
2922 }
2923 envp[envn++] = build_env(
2924 "SCRIPT_NAME=/%s", strcmp( hc->origfilename, "." ) == 0 ?
2925 "" : hc->origfilename );
2926 if ( hc->query[0] != '\0')
2927 envp[envn++] = build_env( "QUERY_STRING=%s", hc->query );
2928 envp[envn++] = build_env(
2929 "REMOTE_ADDR=%s", httpd_ntoa( &hc->client_addr ) );
2930 if ( hc->referer[0] != '\0' )
2931 envp[envn++] = build_env( "HTTP_REFERER=%s", hc->referer );
2932 if ( hc->useragent[0] != '\0' )
2933 envp[envn++] = build_env( "HTTP_USER_AGENT=%s", hc->useragent );
2934 if ( hc->accept[0] != '\0' )
2935 envp[envn++] = build_env( "HTTP_ACCEPT=%s", hc->accept );
2936 if ( hc->accepte[0] != '\0' )
2937 envp[envn++] = build_env( "HTTP_ACCEPT_ENCODING=%s", hc->accepte );
2938 if ( hc->acceptl[0] != '\0' )
2939 envp[envn++] = build_env( "HTTP_ACCEPT_LANGUAGE=%s", hc->acceptl );
2940 if ( hc->cookie[0] != '\0' )
2941 envp[envn++] = build_env( "HTTP_COOKIE=%s", hc->cookie );
2942 if ( hc->contenttype[0] != '\0' )
2943 envp[envn++] = build_env( "CONTENT_TYPE=%s", hc->contenttype );
2944 if ( hc->hdrhost[0] != '\0' )
2945 envp[envn++] = build_env( "HTTP_HOST=%s", hc->hdrhost );
2946 if ( hc->contentlength != -1 )
2947 {
2948 (void) my_snprintf( buf, sizeof(buf),
2949 "%ld", (long) hc->contentlength );
2950 envp[envn++] = build_env( "CONTENT_LENGTH=%s", buf );
2951 }
2952 if ( hc->remoteuser[0] != '\0' )
2953 envp[envn++] = build_env( "REMOTE_USER=%s", hc->remoteuser );
2954 if ( hc->authorization[0] == '\0' )
2955 envp[envn++] = build_env( "AUTH_TYPE=%s", "Basic" );
2956 /* We only support Basic auth at the moment. */
2957 if ( getenv( "TZ" ) != (char*) 0 )
2958 envp[envn++] = build_env( "TZ=%s", getenv( "TZ" ) );
2959 envp[envn++] = build_env( "CGI_PATTERN=%s", hc->hs->cgi_pattern );
2960
2961 envp[envn] = (char*) 0;
2962 return envp;
2963 }
2964
2965
2966 /* Set up argument vector. Again, we don't have to worry about freeing stuff
2967 ** since we're a sub-process. This gets done after make_envp() because we
2968 ** scribble on hc->query.
2969 */
2970 static char**
2971 make_argp( httpd_conn* hc )
2972 {
2973 char** argp;
2974 int argn;
2975 char* cp1;
2976 char* cp2;
2977
2978 /* By allocating an arg slot for every character in the query, plus
2979 ** one for the filename and one for the NULL, we are guaranteed to
2980 ** have enough. We could actually use strlen/2.
2981 */
2982 argp = NEW( char*, strlen( hc->query ) + 2 );
2983 if ( argp == (char**) 0 )
2984 return (char**) 0;
2985
2986 argp[0] = strrchr( hc->expnfilename, '/' );
2987 if ( argp[0] != (char*) 0 )
2988 ++argp[0];
2989 else
2990 argp[0] = hc->expnfilename;
2991
2992 argn = 1;
2993 /* According to the CGI spec at http://hoohoo.ncsa.uiuc.edu/cgi/cl.html,
2994 ** "The server should search the query information for a non-encoded =
2995 ** character to determine if the command line is to be used, if it finds
2996 ** one, the command line is not to be used."
2997 */
2998 if ( strchr( hc->query, '=' ) == (char*) 0 )
2999 {
3000 for ( cp1 = cp2 = hc->query; *cp2 != '\0'; ++cp2 )
3001 {
3002 if ( *cp2 == '+' )
3003 {
3004 *cp2 = '\0';
3005 strdecode( cp1, cp1 );
3006 argp[argn++] = cp1;
3007 cp1 = cp2 + 1;
3008 }
3009 }
3010 if ( cp2 != cp1 )
3011 {
3012 strdecode( cp1, cp1 );
3013 argp[argn++] = cp1;
3014 }
3015 }
3016
3017 argp[argn] = (char*) 0;
3018 return argp;
3019 }
3020
3021
3022 /* This routine is used only for POST requests. It reads the data
3023 ** from the request and sends it to the child process. The only reason
3024 ** we need to do it this way instead of just letting the child read
3025 ** directly is that we have already read part of the data into our
3026 ** buffer.
3027 */
3028 static void
3029 cgi_interpose_input( httpd_conn* hc, int wfd )
3030 {
3031 int c, r;
3032 char buf[1024];
3033
3034 c = hc->read_idx - hc->checked_idx;
3035 if ( c > 0 )
3036 {
3037 if ( write( wfd, &(hc->read_buf[hc->checked_idx]), c ) != c )
3038 return;
3039 }
3040 while ( c < hc->contentlength )
3041 {
3042 r = read( hc->conn_fd, buf, MIN( sizeof(buf), hc->contentlength - c ) );
3043 if ( r == 0 )
3044 sleep( 1 );
3045 else if ( r < 0 )
3046 {
3047 if ( errno == EAGAIN )
3048 sleep( 1 );
3049 else
3050 return;
3051 }
3052 else
3053 {
3054 if ( write( wfd, buf, r ) != r )
3055 return;
3056 c += r;
3057 }
3058 }
3059 post_post_garbage_hack( hc );
3060 }
3061
3062
3063 /* Special hack to deal with broken browsers that send a LF or CRLF
3064 ** after POST data, causing TCP resets - we just read and discard up
3065 ** to 2 bytes. Unfortunately this doesn't fix the problem for CGIs
3066 ** which avoid the interposer process due to their POST data being
3067 ** short. Creating an interposer process for all POST CGIs is
3068 ** unacceptably expensive. The eventual fix will come when interposing
3069 ** gets integrated into the main loop as a tasklet instead of a process.
3070 */
3071 static void
3072 post_post_garbage_hack( httpd_conn* hc )
3073 {
3074 char buf[2];
3075 int r;
3076
3077 r = recv( hc->conn_fd, buf, sizeof(buf), MSG_PEEK );
3078 if ( r > 0 )
3079 (void) read( hc->conn_fd, buf, r );
3080 }
3081
3082
3083 /* This routine is used for parsed-header CGIs. The idea here is that the
3084 ** CGI can return special headers such as "Status:" and "Location:" which
3085 ** change the return status of the response. Since the return status has to
3086 ** be the very first line written out, we have to accumulate all the headers
3087 ** and check for the special ones before writing the status. Then we write
3088 ** out the saved headers and proceed to echo the rest of the response.
3089 */
3090 static void
3091 cgi_interpose_output( httpd_conn* hc, int rfd )
3092 {
3093 int r;
3094 char buf[1024];
3095 int headers_size, headers_len;
3096 char* headers;
3097 char* br;
3098 int status;
3099 char* title;
3100 char* cp;
3101
3102 /* Slurp in all headers. */
3103 headers_size = 0;
3104 httpd_realloc_str( &headers, &headers_size, 500 );
3105 headers_len = 0;
3106 for (;;)
3107 {
3108 r = read( rfd, buf, sizeof(buf) );
3109 if ( r <= 0 )
3110 {
3111 br = &(headers[headers_len]);
3112 break;
3113 }
3114 httpd_realloc_str( &headers, &headers_size, headers_len + r );
3115 (void) memcpy( &(headers[headers_len]), buf, r );
3116 headers_len += r;
3117 headers[headers_len] = '\0';
3118 if ( ( br = strstr( headers, "\r\n\r\n" ) ) != (char*) 0 ||
3119 ( br = strstr( headers, "\n\n" ) ) != (char*) 0 )
3120 break;
3121 }
3122
3123 /* Figure out the status. */
3124 status = 200;
3125 if ( ( cp = strstr( headers, "Status:" ) ) != (char*) 0 &&
3126 cp < br &&
3127 ( cp == headers || *(cp-1) == '\n' ) )
3128 {
3129 cp += 7;
3130 cp += strspn( cp, " \t" );
3131 status = atoi( cp );
3132 }
3133 if ( ( cp = strstr( headers, "Location:" ) ) != (char*) 0 &&
3134 cp < br &&
3135 ( cp == headers || *(cp-1) == '\n' ) )
3136 status = 302;
3137
3138 /* Write the status line. */
3139 switch ( status )
3140 {
3141 case 200: title = ok200title; break;
3142 case 302: title = err302title; break;
3143 case 304: title = err304title; break;
3144 case 400: title = httpd_err400title; break;
3145 #ifdef AUTH_FILE
3146 case 401: title = err401title; break;
3147 #endif /* AUTH_FILE */
3148 case 403: title = err403title; break;
3149 case 404: title = err404title; break;
3150 case 408: title = httpd_err408title; break;
3151 case 500: title = err500title; break;
3152 case 501: title = err501title; break;
3153 case 503: title = httpd_err503title; break;
3154 default: title = "Something"; break;
3155 }
3156 (void) my_snprintf( buf, sizeof(buf), "HTTP/1.0 %d %s\r\n", status, title );
3157 (void) write( hc->conn_fd, buf, strlen( buf ) );
3158
3159 /* Write the saved headers. */
3160 (void) write( hc->conn_fd, headers, headers_len );
3161
3162 /* Echo the rest of the output. */
3163 for (;;)
3164 {
3165 r = read( rfd, buf, sizeof(buf) );
3166 if ( r <= 0 )
3167 return;
3168 if ( write( hc->conn_fd, buf, r ) != r )
3169 return;
3170 }
3171 }
3172
3173
3174 /* CGI child process. */
3175 static void
3176 cgi_child( httpd_conn* hc, char* exefilename )
3177 {
3178 int r;
3179 char** argp;
3180 char** envp;
3181 char* binary;
3182 char* directory;
3183
3184 /* Unset close-on-exec flag for this socket. This actually shouldn't
3185 ** be necessary, according to POSIX a dup()'d file descriptor does
3186 ** *not* inherit the close-on-exec flag, its flag is always clear.
3187 ** However, Linux messes this up and does copy the flag to the
3188 ** dup()'d descriptor, so we have to clear it. This could be
3189 ** ifdeffed for Linux only.
3190 */
3191 (void) fcntl( hc->conn_fd, F_SETFD, 0 );
3192
3193 /* Close the syslog descriptor so that the CGI program can't
3194 ** mess with it. All other open descriptors should be either
3195 ** the listen socket(s), sockets from accept(), or the file-logging
3196 ** fd, and all of those are set to close-on-exec, so we don't
3197 ** have to close anything else.
3198 */
3199 closelog();
3200
3201 /* If the socket happens to be using one of the stdin/stdout/stderr
3202 ** descriptors, move it to another descriptor so that the dup2 calls
3203 ** below don't screw things up.
3204 */
3205 if ( hc->conn_fd == STDIN_FILENO || hc->conn_fd == STDOUT_FILENO || hc->conn_fd == STDERR_FILENO )
3206 {
3207 int newfd = dup( hc->conn_fd );
3208 if ( newfd >= 0 )
3209 hc->conn_fd = newfd;
3210 /* If the dup fails, shrug. We'll just take our chances.
3211 ** Shouldn't happen though.
3212 **
3213 ** If the dup happens to produce an fd that is still one of
3214 ** the standard ones, we should be ok - I think it can be
3215 ** fd 2, stderr, but can never show up as 0 or 1 since at
3216 ** least two file descriptors are always in use. Because
3217 ** of the order in which we dup2 things below - stderr is
3218 ** always done last - it's actually ok for the socket to
3219 ** be fd 2. It'll just get dup2'd onto itself.
3220 */
3221 }
3222
3223 /* Make the environment vector. */
3224 envp = make_envp( hc );
3225
3226 /* Make the argument vector. */
3227 argp = make_argp( hc );
3228
3229 /* Set up stdin. For POSTs we may have to set up a pipe from an
3230 ** interposer process, depending on if we've read some of the data
3231 ** into our buffer.
3232 */
3233 if ( hc->method == METHOD_POST && hc->read_idx > hc->checked_idx )
3234 {
3235 int p[2];
3236
3237 if ( pipe( p ) < 0 )
3238 {
3239 syslog( LOG_ERR, "pipe - %m" );
3240 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3241 exit( 1 );
3242 }
3243 r = fork( );
3244 if ( r < 0 )
3245 {
3246 syslog( LOG_ERR, "fork - %m" );
3247 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3248 exit( 1 );
3249 }
3250 if ( r == 0 )
3251 {
3252 /* Interposer process. */
3253 (void) close( p[0] );
3254 cgi_interpose_input( hc, p[1] );
3255 exit( 0 );
3256 }
3257 (void) close( p[1] );
3258 (void) dup2( p[0], STDIN_FILENO );
3259 (void) close( p[0] );
3260 }
3261 else
3262 {
3263 /* Otherwise, the request socket is stdin. */
3264 (void) dup2( hc->conn_fd, STDIN_FILENO );
3265 }
3266
3267 /* Set up stdout/stderr. If we're doing CGI header parsing,
3268 ** we need an output interposer too.
3269 */
3270 if ( strncmp( argp[0], "nph-", 4 ) != 0 && hc->mime_flag )
3271 {
3272 int p[2];
3273
3274 if ( pipe( p ) < 0 )
3275 {
3276 syslog( LOG_ERR, "pipe - %m" );
3277 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3278 exit( 1 );
3279 }
3280 r = fork( );
3281 if ( r < 0 )
3282 {
3283 syslog( LOG_ERR, "fork - %m" );
3284 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3285 exit( 1 );
3286 }
3287 if ( r == 0 )
3288 {
3289 /* Interposer process. */
3290 (void) close( p[1] );
3291 cgi_interpose_output( hc, p[0] );
3292 exit( 0 );
3293 }
3294 (void) close( p[0] );
3295 (void) dup2( p[1], STDOUT_FILENO );
3296 (void) dup2( p[1], STDERR_FILENO );
3297 (void) close( p[1] );
3298 }
3299 else
3300 {
3301 /* Otherwise, the request socket is stdout/stderr. */
3302 (void) dup2( hc->conn_fd, STDOUT_FILENO );
3303 (void) dup2( hc->conn_fd, STDERR_FILENO );
3304 }
3305
3306 /* At this point we would like to set close-on-exec again for hc->conn_fd
3307 ** (see previous comments on Linux's broken behavior re: close-on-exec
3308 ** and dup.) Unfortunately there seems to be another Linux problem, or
3309 ** perhaps a different aspect of the same problem - if we do this
3310 ** close-on-exec in Linux, the socket stays open but stderr gets
3311 ** closed - the last fd duped from the socket. What a mess. So we'll
3312 ** just leave the socket as is, which under other OSs means an extra
3313 ** file descriptor gets passed to the child process. Since the child
3314 ** probably already has that file open via stdin stdout and/or stderr,
3315 ** this is not a problem.
3316 */
3317 /* (void) fcntl( hc->conn_fd, F_SETFD, 1 ); */
3318
3319 #ifdef CGI_NICE
3320 /* Set priority. */
3321 (void) nice( CGI_NICE );
3322 #endif /* CGI_NICE */
3323
3324 /* Split the program into directory and binary, so we can chdir()
3325 ** to the program's own directory. This isn't in the CGI 1.1
3326 ** spec, but it's what other HTTP servers do.
3327 */
3328 if (exefilename)
3329 binary = exefilename;
3330 else
3331 {
3332 directory = strdup( exefilename ? exefilename : hc->expnfilename );
3333 if ( directory == (char*) 0 )
3334 binary = exefilename; /* ignore errors */
3335 else
3336 {
3337 binary = strrchr( directory, '/' );
3338 if ( binary == (char*) 0 )
3339 binary = exefilename;
3340 else
3341 {
3342 *binary++ = '\0';
3343 (void) chdir( directory ); /* ignore errors */
3344 }
3345 }
3346 }
3347
3348 /* Default behavior for SIGPIPE. */
3349 (void) signal( SIGPIPE, SIG_DFL );
3350
3351 /* Run the program. */
3352 (void) execve( binary, argp, envp );
3353
3354 /* Something went wrong. */
3355 syslog( LOG_ERR, "execve %.80s - %m", hc->expnfilename );
3356 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3357 exit( 1 );
3358 }
3359
3360
3361 static off_t
3362 cgi( httpd_conn* hc, char* exefilename )
3363 {
3364 int r;
3365 ClientData client_data;
3366
3367 if ( hc->method == METHOD_GET || hc->method == METHOD_POST )
3368 {
3369 httpd_clear_ndelay( hc->conn_fd );
3370 r = fork( );
3371 if ( r < 0 )
3372 {
3373 syslog( LOG_ERR, "fork - %m" );
3374 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3375 return -1;
3376 }
3377 if ( r == 0 )
3378 {
3379 unlisten( hc->hs );
3380 cgi_child( hc, exefilename );
3381 }
3382
3383 /* Parent process. */
3384 syslog( LOG_INFO, "spawned CGI process %d for file '%.200s'", r, hc->expnfilename );
3385 #ifdef CGI_TIMELIMIT
3386 /* Schedule a kill for the child process, in case it runs too long */
3387 client_data.i = r;
3388 if ( tmr_create( (struct timeval*) 0, cgi_kill, client_data, CGI_TIMELIMIT * 1000L, 0 ) == (Timer*) 0 )
3389 {
3390 syslog( LOG_CRIT, "tmr_create(cgi_kill) failed" );
3391 exit( 1 );
3392 }
3393 #endif /* CGI_TIMELIMIT */
3394 hc->status = 200;
3395 hc->bytes_sent = CGI_BYTECOUNT;
3396 hc->should_linger = 0;
3397 }
3398 else
3399 {
3400 httpd_send_err(
3401 hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) );
3402 return -1;
3403 }
3404
3405 return 0;
3406 }
3407
3408
3409 static int
3410 really_start_request( httpd_conn* hc, struct timeval* nowP )
3411 {
3412 static char* indexname;
3413 static int maxindexname = 0;
3414 static const char* index_names[] = { INDEX_NAMES };
3415 int i;
3416 #ifdef AUTH_FILE
3417 static char* dirname;
3418 static int maxdirname = 0;
3419 #endif /* AUTH_FILE */
3420 int expnlen, indxlen;
3421 char* cp;
3422 char* pi;
3423
3424 expnlen = strlen( hc->expnfilename );
3425
3426 if ( hc->method != METHOD_GET && hc->method != METHOD_HEAD &&
3427 hc->method != METHOD_POST )
3428 {
3429 httpd_send_err(
3430 hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) );
3431 return -1;
3432 }
3433
3434 /* Stat the file. */
3435 if ( stat( hc->expnfilename, &hc->sb ) < 0 )
3436 {
3437 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3438 return -1;
3439 }
3440
3441 /* Is it world-readable or world-executable? We check explicitly instead
3442 ** of just trying to open it, so that no one ever gets surprised by
3443 ** a file that's not set world-readable and yet somehow is
3444 ** readable by the HTTP server and therefore the *whole* world.
3445 */
3446 if ( ! ( hc->sb.st_mode & ( S_IROTH | S_IXOTH ) ) )
3447 {
3448 syslog(
3449 LOG_INFO,
3450 "%.80s URL \"%.80s\" resolves to a non world-readable file",
3451 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3452 httpd_send_err(
3453 hc, 403, err403title, "",
3454 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file that is not world-readable.\n" ),
3455 hc->encodedurl );
3456 return -1;
3457 }
3458
3459 /* Is it a directory? */
3460 if ( S_ISDIR(hc->sb.st_mode) )
3461 {
3462 /* If there's pathinfo, it's just a non-existent file. */
3463 if ( hc->pathinfo[0] != '\0' )
3464 {
3465 httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
3466 return -1;
3467 }
3468
3469 /* Special handling for directory URLs that don't end in a slash.
3470 ** We send back an explicit redirect with the slash, because
3471 ** otherwise many clients can't build relative URLs properly.
3472 */
3473 if ( hc->decodedurl[strlen( hc->decodedurl ) - 1] != '/' )
3474 {
3475 send_dirredirect( hc );
3476 return -1;
3477 }
3478
3479 /* Check for an index file. */
3480 for ( i = 0; i < sizeof(index_names) / sizeof(char*); ++i )
3481 {
3482 httpd_realloc_str(
3483 &indexname, &maxindexname,
3484 expnlen + 1 + strlen( index_names[i] ) );
3485 (void) strcpy( indexname, hc->expnfilename );
3486 indxlen = strlen( indexname );
3487 if ( indxlen == 0 || indexname[indxlen - 1] != '/' )
3488 (void) strcat( indexname, "/" );
3489 if ( strcmp( indexname, "./" ) == 0 )
3490 indexname[0] = '\0';
3491 (void) strcat( indexname, index_names[i] );
3492 if ( stat( indexname, &hc->sb ) >= 0 )
3493 goto got_one;
3494 }
3495
3496 /* Nope, no index file, so it's an actual directory request. */
3497 #ifdef GENERATE_INDEXES
3498 /* Directories must be readable for indexing. */
3499 if ( ! ( hc->sb.st_mode & S_IROTH ) )
3500 {
3501 syslog(
3502 LOG_INFO,
3503 "%.80s URL \"%.80s\" tried to index a directory with indexing disabled",
3504 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3505 httpd_send_err(
3506 hc, 403, err403title, "",
3507 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a directory that has indexing disabled.\n" ),
3508 hc->encodedurl );
3509 return -1;
3510 }
3511 #ifdef AUTH_FILE
3512 /* Check authorization for this directory. */
3513 if ( auth_check( hc, hc->expnfilename ) == -1 )
3514 return -1;
3515 #endif /* AUTH_FILE */
3516 /* Referer check. */
3517 if ( ! check_referer( hc ) )
3518 return -1;
3519 /* Ok, generate an index. */
3520 return hc->hs->autoindex_prog ? cgi( hc, hc->hs->autoindex_prog) : ls( hc );
3521 #else /* GENERATE_INDEXES */
3522 syslog(
3523 LOG_INFO, "%.80s URL \"%.80s\" tried to index a directory",
3524 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3525 httpd_send_err(
3526 hc, 403, err403title, "",
3527 ERROR_FORM( err403form, "The requested URL '%.80s' is a directory, and directory indexing is disabled on this server.\n" ),
3528 hc->encodedurl );
3529 return -1;
3530 #endif /* GENERATE_INDEXES */
3531
3532 got_one: ;
3533 /* Got an index file. Expand symlinks again. More pathinfo means
3534 ** something went wrong.
3535 */
3536 cp = expand_symlinks( indexname, &pi, hc->hs->no_symlink, hc->tildemapped );
3537 if ( cp == (char*) 0 || pi[0] != '\0' )
3538 {
3539 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3540 return -1;
3541 }
3542 expnlen = strlen( cp );
3543 httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, expnlen );
3544 (void) strcpy( hc->expnfilename, cp );
3545
3546 /* Now, is the index version world-readable or world-executable? */
3547 if ( ! ( hc->sb.st_mode & ( S_IROTH | S_IXOTH ) ) )
3548 {
3549 syslog(
3550 LOG_INFO,
3551 "%.80s URL \"%.80s\" resolves to a non-world-readable index file",
3552 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3553 httpd_send_err(
3554 hc, 403, err403title, "",
3555 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to an index file that is not world-readable.\n" ),
3556 hc->encodedurl );
3557 return -1;
3558 }
3559 }
3560
3561 #ifdef AUTH_FILE
3562 /* Check authorization for this directory. */
3563 httpd_realloc_str( &dirname, &maxdirname, expnlen );
3564 (void) strcpy( dirname, hc->expnfilename );
3565 cp = strrchr( dirname, '/' );
3566 if ( cp == (char*) 0 )
3567 (void) strcpy( dirname, "." );
3568 else
3569 *cp = '\0';
3570 if ( auth_check( hc, dirname ) == -1 )
3571 return -1;
3572
3573 /* Check if the filename is the AUTH_FILE itself - that's verboten. */
3574 if ( expnlen == sizeof(AUTH_FILE) - 1 )
3575 {
3576 if ( strcmp( hc->expnfilename, AUTH_FILE ) == 0 )
3577 {
3578 syslog(
3579 LOG_NOTICE,
3580 "%.80s URL \"%.80s\" tried to retrieve an auth file",
3581 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3582 httpd_send_err(
3583 hc, 403, err403title, "",
3584 ERROR_FORM( err403form, "The requested URL '%.80s' is an authorization file, retrieving it is not permitted.\n" ),
3585 hc->encodedurl );
3586 return -1;
3587 }
3588 }
3589 else if ( expnlen >= sizeof(AUTH_FILE) &&
3590 strcmp( &(hc->expnfilename[expnlen - sizeof(AUTH_FILE) + 1]), AUTH_FILE ) == 0 &&
3591 hc->expnfilename[expnlen - sizeof(AUTH_FILE)] == '/' )
3592 {
3593 syslog(
3594 LOG_NOTICE,
3595 "%.80s URL \"%.80s\" tried to retrieve an auth file",
3596 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3597 httpd_send_err(
3598 hc, 403, err403title, "",
3599 ERROR_FORM( err403form, "The requested URL '%.80s' is an authorization file, retrieving it is not permitted.\n" ),
3600 hc->encodedurl );
3601 return -1;
3602 }
3603 #endif /* AUTH_FILE */
3604
3605 /* Referer check. */
3606 if ( ! check_referer( hc ) )
3607 return -1;
3608
3609 /* Is it world-executable and in the CGI area? */
3610 if ( hc->hs->cgi_pattern != (char*) 0 &&
3611 ( hc->sb.st_mode & S_IXOTH ) &&
3612 match( hc->hs->cgi_pattern, hc->expnfilename ) )
3613 return cgi( hc, 0 );
3614
3615 /* It's not CGI. If it's executable or there's pathinfo, someone's
3616 ** trying to either serve or run a non-CGI file as CGI. Either case
3617 ** is prohibited.
3618 */
3619 if ( hc->sb.st_mode & S_IXOTH )
3620 {
3621 syslog(
3622 LOG_NOTICE, "%.80s URL \"%.80s\" is executable but isn't CGI",
3623 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3624 httpd_send_err(
3625 hc, 403, err403title, "",
3626 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file which is marked executable but is not a CGI file; retrieving it is forbidden.\n" ),
3627 hc->encodedurl );
3628 return -1;
3629 }
3630 if ( hc->pathinfo[0] != '\0' )
3631 {
3632 syslog(
3633 LOG_INFO, "%.80s URL \"%.80s\" has pathinfo but isn't CGI",
3634 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3635 httpd_send_err(
3636 hc, 403, err403title, "",
3637 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file plus CGI-style pathinfo, but the file is not a valid CGI file.\n" ),
3638 hc->encodedurl );
3639 return -1;
3640 }
3641
3642 /* Fill in end_byte_loc, if necessary. */
3643 if ( hc->got_range &&
3644 ( hc->end_byte_loc == -1 || hc->end_byte_loc >= hc->sb.st_size ) )
3645 hc->end_byte_loc = hc->sb.st_size - 1;
3646
3647 figure_mime( hc );
3648
3649 if ( hc->method == METHOD_HEAD )
3650 {
3651 send_mime(
3652 hc, 200, ok200title, hc->encodings, "", hc->type, hc->sb.st_size,
3653 hc->sb.st_mtime );
3654 }
3655 else if ( hc->if_modified_since != (time_t) -1 &&
3656 hc->if_modified_since >= hc->sb.st_mtime )
3657 {
3658 hc->method = METHOD_HEAD;
3659 send_mime(
3660 hc, 304, err304title, hc->encodings, "", hc->type, hc->sb.st_size,
3661 hc->sb.st_mtime );
3662 }
3663 else
3664 {
3665 #ifdef MMAP_MAX
3666 if ( hc->sb.st_size < MMAP_MAX)
3667 #endif
3668 hc->file_address = mmc_map( hc->expnfilename, &(hc->sb), nowP );
3669 if ( hc->file_address == (char*) 0 )
3670 {
3671 #ifdef MMAP_MAX
3672 hc->file_fd = open ( hc->expnfilename, O_RDONLY);
3673 hc->write_buf = malloc (WRITE_BUFFER);
3674 hc->write_ofs = WRITE_BUFFER;
3675 if ( hc->file_fd < 0 || !hc->write_buf )
3676 #endif
3677 {
3678 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3679 return -1;
3680 }
3681 }
3682 send_mime(
3683 hc, 200, ok200title, hc->encodings, "", hc->type, hc->sb.st_size,
3684 hc->sb.st_mtime );
3685 }
3686
3687 return 0;
3688 }
3689
3690
3691 int
3692 httpd_start_request( httpd_conn* hc, struct timeval* nowP )
3693 {
3694 int r;
3695
3696 /* Really start the request. */
3697 r = really_start_request( hc, nowP );
3698
3699 /* And return the status. */
3700 return r;
3701 }
3702
3703
3704 static void
3705 make_log_entry( httpd_conn* hc, struct timeval* nowP )
3706 {
3707 char* ru;
3708 char url[305];
3709 char bytes[40];
3710
3711 if ( hc->hs->no_log )
3712 return;
3713
3714 /* This is straight CERN Combined Log Format - the only tweak
3715 ** being that if we're using syslog() we leave out the date, because
3716 ** syslogd puts it in. The included syslogtocern script turns the
3717 ** results into true CERN format.
3718 */
3719
3720 /* Format remote user. */
3721 if ( hc->remoteuser[0] != '\0' )
3722 ru = hc->remoteuser;
3723 else
3724 ru = "-";
3725 /* If we're vhosting, prepend the hostname to the url. This is
3726 ** a little weird, perhaps writing separate log files for
3727 ** each vhost would make more sense.
3728 */
3729 if ( hc->hs->vhost && ! hc->tildemapped )
3730 (void) my_snprintf( url, sizeof(url),
3731 "/%.100s%.200s",
3732 hc->hostname == (char*) 0 ? hc->hs->server_hostname : hc->hostname,
3733 hc->encodedurl );
3734 else
3735 (void) my_snprintf( url, sizeof(url),
3736 "%.200s", hc->encodedurl );
3737 /* Format the bytes. */
3738 if ( (long) hc->bytes_sent >= 0 )
3739 (void) my_snprintf( bytes, sizeof(bytes),
3740 "%ld", (long) hc->bytes_sent );
3741 else
3742 (void) strcpy( bytes, "-" );
3743
3744 /* Logfile or syslog? */
3745 if ( hc->hs->logfp != (FILE*) 0 )
3746 {
3747 time_t now;
3748 struct tm* t;
3749 const char* cernfmt_nozone = "%d/%b/%Y:%H:%M:%S";
3750 char date_nozone[100];
3751 int zone;
3752 char sign;
3753 char date[100];
3754
3755 /* Get the current time, if necessary. */
3756 if ( nowP != (struct timeval*) 0 )
3757 now = nowP->tv_sec;
3758 else
3759 now = time( (time_t*) 0 );
3760 /* Format the time, forcing a numeric timezone (some log analyzers
3761 ** are stoooopid about this).
3762 */
3763 t = localtime( &now );
3764 (void) strftime( date_nozone, sizeof(date_nozone), cernfmt_nozone, t );
3765 #ifdef HAVE_TM_GMTOFF
3766 zone = t->tm_gmtoff / 60L;
3767 #else
3768 zone = -timezone / 60L;
3769 /* Probably have to add something about daylight time here. */
3770 #endif
3771 if ( zone >= 0 )
3772 sign = '+';
3773 else
3774 {
3775 sign = '-';
3776 zone = -zone;
3777 }
3778 zone = ( zone / 60 ) * 100 + zone % 60;
3779 (void) my_snprintf( date, sizeof(date),
3780 "%s %c%04d", date_nozone, sign, zone );
3781 /* And write the log entry. */
3782 (void) fprintf( hc->hs->logfp,
3783 "%.80s - %.80s [%s] \"%.80s %.300s %.80s\" %d %s \"%.200s\" \"%.80s\"\n",
3784 httpd_ntoa( &hc->client_addr ), ru, date,
3785 httpd_method_str( hc->method ), url, hc->protocol,
3786 hc->status, bytes, hc->referer, hc->useragent );
3787 (void) fflush( hc->hs->logfp ); /* don't need to flush every time */
3788 }
3789 else
3790 syslog( LOG_INFO,
3791 "%.80s - %.80s \"%.80s %.200s %.80s\" %d %s \"%.200s\" \"%.80s\"",
3792 httpd_ntoa( &hc->client_addr ), ru,
3793 httpd_method_str( hc->method ), url, hc->protocol,
3794 hc->status, bytes, hc->referer, hc->useragent );
3795 }
3796
3797
3798 /* Returns 1 if ok to serve the url, 0 if not. */
3799 static int
3800 check_referer( httpd_conn* hc )
3801 {
3802 int r;
3803
3804 /* Are we doing referer checking at all? */
3805 if ( hc->hs->url_pattern == (char*) 0 )
3806 return 1;
3807
3808 r = really_check_referer( hc );
3809
3810 if ( ! r )
3811 {
3812 syslog(
3813 LOG_INFO, "%.80s non-local referer \"%.80s\" \"%.80s\"",
3814 httpd_ntoa( &hc->client_addr ), hc->encodedurl,
3815 hc->referer );
3816 httpd_send_err(
3817 hc, 403, err403title, "",
3818 ERROR_FORM( err403form, "You must supply a local referer to get URL '%.80s' from this server.\n" ),
3819 hc->encodedurl );
3820 }
3821 return r;
3822 }
3823
3824
3825 /* Returns 1 if ok to serve the url, 0 if not. */
3826 static int
3827 really_check_referer( httpd_conn* hc )
3828 {
3829 httpd_server* hs;
3830 char* cp1;
3831 char* cp2;
3832 char* cp3;
3833 static char* refhost = (char*) 0;
3834 static int refhost_size = 0;
3835 char *lp;
3836
3837 hs = hc->hs;
3838
3839 /* Check for an empty referer. */
3840 if ( hc->referer == (char*) 0 || hc->referer[0] == '\0' ||
3841 ( cp1 = strstr( hc->referer, "//" ) ) == (char*) 0 )
3842 {
3843 /* Disallow if we require a referer and the url matches. */
3844 if ( hs->no_empty_referers && match( hs->url_pattern, hc->decodedurl ) )
3845 return 0;
3846 /* Otherwise ok. */
3847 return 1;
3848 }
3849
3850 /* Extract referer host. */
3851 cp1 += 2;
3852 for ( cp2 = cp1; *cp2 != '/' && *cp2 != ':' && *cp2 != '\0'; ++cp2 )
3853 continue;
3854 httpd_realloc_str( &refhost, &refhost_size, cp2 - cp1 );
3855 for ( cp3 = refhost; cp1 < cp2; ++cp1, ++cp3 )
3856 if ( isupper(*cp1) )
3857 *cp3 = tolower(*cp1);
3858 else
3859 *cp3 = *cp1;
3860 *cp3 = '\0';
3861
3862 /* Local pattern? */
3863 if ( hs->local_pattern != (char*) 0 )
3864 lp = hs->local_pattern;
3865 else
3866 {
3867 /* No local pattern. What's our hostname? */
3868 if ( ! hs->vhost )
3869 {
3870 /* Not vhosting, use the server name. */
3871 lp = hs->server_hostname;
3872 if ( lp == (char*) 0 )
3873 /* Couldn't figure out local hostname - give up. */
3874 return 1;
3875 }
3876 else
3877 {
3878 /* We are vhosting, use the hostname on this connection. */
3879 lp = hc->hostname;
3880 if ( lp == (char*) 0 )
3881 /* Oops, no hostname. Maybe it's an old browser that
3882 ** doesn't send a Host: header. We could figure out
3883 ** the default hostname for this IP address, but it's
3884 ** not worth it for the few requests like this.
3885 */
3886 return 1;
3887 }
3888 }
3889
3890 /* If the referer host doesn't match the local host pattern, and
3891 ** the URL does match the url pattern, it's an illegal reference.
3892 */
3893 if ( ! match( lp, refhost ) && match( hs->url_pattern, hc->decodedurl ) )
3894 return 0;
3895 /* Otherwise ok. */
3896 return 1;
3897 }
3898
3899
3900 char*
3901 httpd_ntoa( httpd_sockaddr* saP )
3902 {
3903 #ifdef HAVE_GETNAMEINFO
3904 static char str[200];
3905
3906 if ( getnameinfo( &saP->sa, sockaddr_len( saP ), str, sizeof(str), 0, 0, NI_NUMERICHOST ) != 0 )
3907 {
3908 str[0] = '?';
3909 str[1] = '\0';
3910 }
3911 return str;
3912
3913 #else /* HAVE_GETNAMEINFO */
3914
3915 return inet_ntoa( saP->sa_in.sin_addr );
3916
3917 #endif /* HAVE_GETNAMEINFO */
3918 }
3919
3920
3921 static int
3922 sockaddr_check( httpd_sockaddr* saP )
3923 {
3924 switch ( saP->sa.sa_family )
3925 {
3926 case AF_INET: return 1;
3927 #if defined(AF_INET6) && defined(HAVE_SOCKADDR_IN6)
3928 case AF_INET6: return 1;
3929 #endif /* AF_INET6 && HAVE_SOCKADDR_IN6 */
3930 default:
3931 return 0;
3932 }
3933 }
3934
3935
3936 static size_t
3937 sockaddr_len( httpd_sockaddr* saP )
3938 {
3939 switch ( saP->sa.sa_family )
3940 {
3941 case AF_INET: return sizeof(struct sockaddr_in);
3942 #if defined(AF_INET6) && defined(HAVE_SOCKADDR_IN6)
3943 case AF_INET6: return sizeof(struct sockaddr_in6);
3944 #endif /* AF_INET6 && HAVE_SOCKADDR_IN6 */
3945 default:
3946 return 0; /* shouldn't happen */
3947 }
3948 }
3949
3950
3951 /* Some systems don't have snprintf(), so we make our own that uses
3952 ** either vsnprintf() or vsprintf(). If your system doesn't have
3953 ** vsnprintf(), it is probably vulnerable to buffer overruns.
3954 ** Upgrade!
3955 */
3956 static int
3957 my_snprintf( char* str, size_t size, const char* format, ... )
3958 {
3959 va_list ap;
3960 int r;
3961
3962 va_start( ap, format );
3963 #ifdef HAVE_VSNPRINTF
3964 r = vsnprintf( str, size, format, ap );
3965 #else /* HAVE_VSNPRINTF */
3966 r = vsprintf( str, format, ap );
3967 #endif /* HAVE_VSNPRINTF */
3968 va_end( ap );
3969 return r;
3970 }
3971
3972
3973 /* Generate debugging statistics syslog message. */
3974 void
3975 httpd_logstats( long secs )
3976 {
3977 syslog( LOG_NOTICE,
3978 " libhttpd - %d strings allocated, %ld bytes (%g bytes/str)",
3979 str_alloc_count, str_alloc_size,
3980 (float) str_alloc_size / str_alloc_count );
3981 }