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