ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/thttpd/libhttpd.c
Revision: 1.1
Committed: Mon Jun 18 21:11:56 2001 UTC (23 years ago) by root
Content type: text/plain
Branch: MAIN
Branch point for: connpatch, dirpatch, mmapppatch
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 return GC_OK;
1707 }
1708
1709
1710 /* Checks hc->read_buf to see whether a complete request has been read so far;
1711 ** either the first line has two words (an HTTP/0.9 request), or the first
1712 ** line has three words and there's a blank line present.
1713 **
1714 ** hc->read_idx is how much has been read in; hc->checked_idx is how much we
1715 ** have checked so far; and hc->checked_state is the current state of the
1716 ** finite state machine.
1717 */
1718 int
1719 httpd_got_request( httpd_conn* hc )
1720 {
1721 char c;
1722
1723 for ( ; hc->checked_idx < hc->read_idx; ++hc->checked_idx )
1724 {
1725 c = hc->read_buf[hc->checked_idx];
1726 switch ( hc->checked_state )
1727 {
1728 case CHST_FIRSTWORD:
1729 switch ( c )
1730 {
1731 case ' ': case '\t':
1732 hc->checked_state = CHST_FIRSTWS;
1733 break;
1734 case '\n': case '\r':
1735 hc->checked_state = CHST_BOGUS;
1736 return GR_BAD_REQUEST;
1737 }
1738 break;
1739 case CHST_FIRSTWS:
1740 switch ( c )
1741 {
1742 case ' ': case '\t':
1743 break;
1744 case '\n': case '\r':
1745 hc->checked_state = CHST_BOGUS;
1746 return GR_BAD_REQUEST;
1747 default:
1748 hc->checked_state = CHST_SECONDWORD;
1749 break;
1750 }
1751 break;
1752 case CHST_SECONDWORD:
1753 switch ( c )
1754 {
1755 case ' ': case '\t':
1756 hc->checked_state = CHST_SECONDWS;
1757 break;
1758 case '\n': case '\r':
1759 /* The first line has only two words - an HTTP/0.9 request. */
1760 return GR_GOT_REQUEST;
1761 }
1762 break;
1763 case CHST_SECONDWS:
1764 switch ( c )
1765 {
1766 case ' ': case '\t':
1767 break;
1768 case '\n': case '\r':
1769 hc->checked_state = CHST_BOGUS;
1770 return GR_BAD_REQUEST;
1771 default:
1772 hc->checked_state = CHST_THIRDWORD;
1773 break;
1774 }
1775 break;
1776 case CHST_THIRDWORD:
1777 switch ( c )
1778 {
1779 case ' ': case '\t':
1780 hc->checked_state = CHST_THIRDWS;
1781 break;
1782 case '\n':
1783 hc->checked_state = CHST_LF;
1784 break;
1785 case '\r':
1786 hc->checked_state = CHST_CR;
1787 break;
1788 }
1789 break;
1790 case CHST_THIRDWS:
1791 switch ( c )
1792 {
1793 case ' ': case '\t':
1794 break;
1795 case '\n':
1796 hc->checked_state = CHST_LF;
1797 break;
1798 case '\r':
1799 hc->checked_state = CHST_CR;
1800 break;
1801 default:
1802 hc->checked_state = CHST_BOGUS;
1803 return GR_BAD_REQUEST;
1804 }
1805 break;
1806 case CHST_LINE:
1807 switch ( c )
1808 {
1809 case '\n':
1810 hc->checked_state = CHST_LF;
1811 break;
1812 case '\r':
1813 hc->checked_state = CHST_CR;
1814 break;
1815 }
1816 break;
1817 case CHST_LF:
1818 switch ( c )
1819 {
1820 case '\n':
1821 /* Two newlines in a row - a blank line - end of request. */
1822 return GR_GOT_REQUEST;
1823 case '\r':
1824 hc->checked_state = CHST_CR;
1825 break;
1826 default:
1827 hc->checked_state = CHST_LINE;
1828 break;
1829 }
1830 break;
1831 case CHST_CR:
1832 switch ( c )
1833 {
1834 case '\n':
1835 hc->checked_state = CHST_CRLF;
1836 break;
1837 case '\r':
1838 /* Two returns in a row - end of request. */
1839 return GR_GOT_REQUEST;
1840 default:
1841 hc->checked_state = CHST_LINE;
1842 break;
1843 }
1844 break;
1845 case CHST_CRLF:
1846 switch ( c )
1847 {
1848 case '\n':
1849 /* Two newlines in a row - end of request. */
1850 return GR_GOT_REQUEST;
1851 case '\r':
1852 hc->checked_state = CHST_CRLFCR;
1853 break;
1854 default:
1855 hc->checked_state = CHST_LINE;
1856 break;
1857 }
1858 break;
1859 case CHST_CRLFCR:
1860 switch ( c )
1861 {
1862 case '\n': case '\r':
1863 /* Two CRLFs or two CRs in a row - end of request. */
1864 return GR_GOT_REQUEST;
1865 default:
1866 hc->checked_state = CHST_LINE;
1867 break;
1868 }
1869 break;
1870 case CHST_BOGUS:
1871 return GR_BAD_REQUEST;
1872 }
1873 }
1874 return GR_NO_REQUEST;
1875 }
1876
1877
1878 int
1879 httpd_parse_request( httpd_conn* hc )
1880 {
1881 char* buf;
1882 char* method_str;
1883 char* url;
1884 char* protocol;
1885 char* reqhost;
1886 char* eol;
1887 char* cp;
1888 char* pi;
1889
1890 hc->checked_idx = 0; /* reset */
1891 method_str = bufgets( hc );
1892 url = strpbrk( method_str, " \t\n\r" );
1893 if ( url == (char*) 0 )
1894 {
1895 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
1896 return -1;
1897 }
1898 *url++ = '\0';
1899 url += strspn( url, " \t\n\r" );
1900 protocol = strpbrk( url, " \t\n\r" );
1901 if ( protocol == (char*) 0 )
1902 {
1903 protocol = "HTTP/0.9";
1904 hc->mime_flag = 0;
1905 }
1906 else
1907 {
1908 *protocol++ = '\0';
1909 protocol += strspn( protocol, " \t\n\r" );
1910 if ( *protocol != '\0' )
1911 {
1912 eol = strpbrk( protocol, " \t\n\r" );
1913 if ( eol != (char*) 0 )
1914 *eol = '\0';
1915 if ( strcasecmp( protocol, "HTTP/1.0" ) != 0 )
1916 hc->one_one = 1;
1917 }
1918 }
1919 /* Check for HTTP/1.1 absolute URL. */
1920 if ( strncasecmp( url, "http://", 7 ) == 0 )
1921 {
1922 if ( ! hc->one_one )
1923 {
1924 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
1925 return -1;
1926 }
1927 reqhost = url + 7;
1928 url = strchr( reqhost, '/' );
1929 if ( url == (char*) 0 )
1930 {
1931 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
1932 return -1;
1933 }
1934 *url = '\0';
1935 httpd_realloc_str( &hc->reqhost, &hc->maxreqhost, strlen( reqhost ) );
1936 (void) strcpy( hc->reqhost, reqhost );
1937 *url = '/';
1938 }
1939
1940 if ( strcasecmp( method_str, httpd_method_str( METHOD_GET ) ) == 0 )
1941 hc->method = METHOD_GET;
1942 else if ( strcasecmp( method_str, httpd_method_str( METHOD_HEAD ) ) == 0 )
1943 hc->method = METHOD_HEAD;
1944 else if ( strcasecmp( method_str, httpd_method_str( METHOD_POST ) ) == 0 )
1945 hc->method = METHOD_POST;
1946 else
1947 {
1948 httpd_send_err( hc, 501, err501title, "", err501form, method_str );
1949 return -1;
1950 }
1951
1952 hc->encodedurl = url;
1953 httpd_realloc_str(
1954 &hc->decodedurl, &hc->maxdecodedurl, strlen( hc->encodedurl ) );
1955 strdecode( hc->decodedurl, hc->encodedurl );
1956
1957 de_dotdot( hc->decodedurl );
1958 if ( hc->decodedurl[0] != '/' || hc->decodedurl[1] == '/' ||
1959 ( hc->decodedurl[1] == '.' && hc->decodedurl[2] == '.' &&
1960 ( hc->decodedurl[3] == '\0' || hc->decodedurl[3] == '/' ) ) )
1961 {
1962 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
1963 return -1;
1964 }
1965
1966 hc->protocol = protocol;
1967
1968 httpd_realloc_str(
1969 &hc->origfilename, &hc->maxorigfilename, strlen( hc->decodedurl ) );
1970 (void) strcpy( hc->origfilename, &hc->decodedurl[1] );
1971 /* Special case for top-level URL. */
1972 if ( hc->origfilename[0] == '\0' )
1973 (void) strcpy( hc->origfilename, "." );
1974
1975 /* Extract query string from encoded URL. */
1976 cp = strchr( hc->encodedurl, '?' );
1977 if ( cp != (char*) 0 )
1978 {
1979 ++cp;
1980 httpd_realloc_str( &hc->query, &hc->maxquery, strlen( cp ) );
1981 (void) strcpy( hc->query, cp );
1982 }
1983 /* And remove query from filename. */
1984 cp = strchr( hc->origfilename, '?' );
1985 if ( cp != (char*) 0 )
1986 *cp = '\0';
1987
1988 if ( hc->mime_flag )
1989 {
1990 /* Read the MIME headers. */
1991 while ( ( buf = bufgets( hc ) ) != (char*) 0 )
1992 {
1993 if ( buf[0] == '\0' )
1994 break;
1995 if ( strncasecmp( buf, "Referer:", 8 ) == 0 )
1996 {
1997 cp = &buf[8];
1998 cp += strspn( cp, " \t" );
1999 hc->referer = cp;
2000 }
2001 else if ( strncasecmp( buf, "User-Agent:", 11 ) == 0 )
2002 {
2003 cp = &buf[11];
2004 cp += strspn( cp, " \t" );
2005 hc->useragent = cp;
2006 }
2007 else if ( strncasecmp( buf, "Host:", 5 ) == 0 )
2008 {
2009 cp = &buf[5];
2010 cp += strspn( cp, " \t" );
2011 hc->hdrhost = cp;
2012 cp = strchr( hc->hdrhost, ':' );
2013 if ( cp != (char*) 0 )
2014 *cp = '\0';
2015 }
2016 else if ( strncasecmp( buf, "Accept:", 7 ) == 0 )
2017 {
2018 cp = &buf[7];
2019 cp += strspn( cp, " \t" );
2020 if ( hc->accept[0] != '\0' )
2021 {
2022 if ( strlen( hc->accept ) > 5000 )
2023 {
2024 syslog(
2025 LOG_ERR, "%.80s way too much Accept: data",
2026 httpd_ntoa( &hc->client_addr ) );
2027 continue;
2028 }
2029 httpd_realloc_str(
2030 &hc->accept, &hc->maxaccept,
2031 strlen( hc->accept ) + 2 + strlen( cp ) );
2032 (void) strcat( hc->accept, ", " );
2033 }
2034 else
2035 httpd_realloc_str(
2036 &hc->accept, &hc->maxaccept, strlen( cp ) );
2037 (void) strcat( hc->accept, cp );
2038 }
2039 else if ( strncasecmp( buf, "Accept-Encoding:", 16 ) == 0 )
2040 {
2041 cp = &buf[16];
2042 cp += strspn( cp, " \t" );
2043 if ( hc->accepte[0] != '\0' )
2044 {
2045 if ( strlen( hc->accepte ) > 5000 )
2046 {
2047 syslog(
2048 LOG_ERR, "%.80s way too much Accept-Encoding: data",
2049 httpd_ntoa( &hc->client_addr ) );
2050 continue;
2051 }
2052 httpd_realloc_str(
2053 &hc->accepte, &hc->maxaccepte,
2054 strlen( hc->accepte ) + 2 + strlen( cp ) );
2055 (void) strcat( hc->accepte, ", " );
2056 }
2057 else
2058 httpd_realloc_str(
2059 &hc->accepte, &hc->maxaccepte, strlen( cp ) );
2060 (void) strcpy( hc->accepte, cp );
2061 }
2062 else if ( strncasecmp( buf, "Accept-Language:", 16 ) == 0 )
2063 {
2064 cp = &buf[16];
2065 cp += strspn( cp, " \t" );
2066 hc->acceptl = cp;
2067 }
2068 else if ( strncasecmp( buf, "If-Modified-Since:", 18 ) == 0 )
2069 {
2070 cp = &buf[18];
2071 hc->if_modified_since = tdate_parse( cp );
2072 if ( hc->if_modified_since == (time_t) -1 )
2073 syslog( LOG_DEBUG, "unparsable time: %.80s", cp );
2074 }
2075 else if ( strncasecmp( buf, "Cookie:", 7 ) == 0 )
2076 {
2077 cp = &buf[7];
2078 cp += strspn( cp, " \t" );
2079 hc->cookie = cp;
2080 }
2081 else if ( strncasecmp( buf, "Range:", 6 ) == 0 )
2082 {
2083 /* Only support %d- and %d-%d, not %d-%d,%d-%d or -%d. */
2084 if ( strchr( buf, ',' ) == (char*) 0 )
2085 {
2086 char* cp_dash;
2087 cp = strpbrk( buf, "=" );
2088 if ( cp != (char*) 0 )
2089 {
2090 cp_dash = strchr( cp + 1, '-' );
2091 if ( cp_dash != (char*) 0 && cp_dash != cp + 1 )
2092 {
2093 *cp_dash = '\0';
2094 hc->got_range = 1;
2095 hc->init_byte_loc = atol( cp + 1 );
2096 if ( isdigit( (int) cp_dash[1] ) )
2097 hc->end_byte_loc = atol( cp_dash + 1 );
2098 }
2099 }
2100 }
2101 }
2102 else if ( strncasecmp( buf, "Range-If:", 9 ) == 0 ||
2103 strncasecmp( buf, "If-Range:", 9 ) == 0 )
2104 {
2105 cp = &buf[9];
2106 hc->range_if = tdate_parse( cp );
2107 if ( hc->range_if == (time_t) -1 )
2108 syslog( LOG_DEBUG, "unparsable time: %.80s", cp );
2109 }
2110 else if ( strncasecmp( buf, "Content-Type:", 13 ) == 0 )
2111 {
2112 cp = &buf[13];
2113 cp += strspn( cp, " \t" );
2114 hc->contenttype = cp;
2115 }
2116 else if ( strncasecmp( buf, "Content-Length:", 15 ) == 0 )
2117 {
2118 cp = &buf[15];
2119 hc->contentlength = atol( cp );
2120 }
2121 else if ( strncasecmp( buf, "Authorization:", 14 ) == 0 )
2122 {
2123 cp = &buf[14];
2124 cp += strspn( cp, " \t" );
2125 hc->authorization = cp;
2126 }
2127 else if ( strncasecmp( buf, "Connection:", 11 ) == 0 )
2128 {
2129 cp = &buf[11];
2130 cp += strspn( cp, " \t" );
2131 if ( strcasecmp( cp, "keep-alive" ) == 0 )
2132 hc->keep_alive = 1;
2133 }
2134 #ifdef LOG_UNKNOWN_HEADERS
2135 else if ( strncasecmp( buf, "Accept-Charset:", 15 ) == 0 ||
2136 strncasecmp( buf, "Accept-Language:", 16 ) == 0 ||
2137 strncasecmp( buf, "Agent:", 6 ) == 0 ||
2138 strncasecmp( buf, "Cache-Control:", 14 ) == 0 ||
2139 strncasecmp( buf, "Cache-Info:", 11 ) == 0 ||
2140 strncasecmp( buf, "Charge-To:", 10 ) == 0 ||
2141 strncasecmp( buf, "Client-IP:", 10 ) == 0 ||
2142 strncasecmp( buf, "Date:", 5 ) == 0 ||
2143 strncasecmp( buf, "Extension:", 10 ) == 0 ||
2144 strncasecmp( buf, "Forwarded:", 10 ) == 0 ||
2145 strncasecmp( buf, "From:", 5 ) == 0 ||
2146 strncasecmp( buf, "HTTP-Version:", 13 ) == 0 ||
2147 strncasecmp( buf, "Max-Forwards:", 13 ) == 0 ||
2148 strncasecmp( buf, "Message-Id:", 11 ) == 0 ||
2149 strncasecmp( buf, "MIME-Version:", 13 ) == 0 ||
2150 strncasecmp( buf, "Negotiate:", 10 ) == 0 ||
2151 strncasecmp( buf, "Pragma:", 7 ) == 0 ||
2152 strncasecmp( buf, "Proxy-Agent:", 12 ) == 0 ||
2153 strncasecmp( buf, "Proxy-Connection:", 17 ) == 0 ||
2154 strncasecmp( buf, "Security-Scheme:", 16 ) == 0 ||
2155 strncasecmp( buf, "Session-Id:", 11 ) == 0 ||
2156 strncasecmp( buf, "UA-Color:", 9 ) == 0 ||
2157 strncasecmp( buf, "UA-CPU:", 7 ) == 0 ||
2158 strncasecmp( buf, "UA-Disp:", 8 ) == 0 ||
2159 strncasecmp( buf, "UA-OS:", 6 ) == 0 ||
2160 strncasecmp( buf, "UA-Pixels:", 10 ) == 0 ||
2161 strncasecmp( buf, "User:", 5 ) == 0 ||
2162 strncasecmp( buf, "Via:", 4 ) == 0 ||
2163 strncasecmp( buf, "X-", 2 ) == 0 )
2164 ; /* ignore */
2165 else
2166 syslog( LOG_DEBUG, "unknown request header: %.80s", buf );
2167 #endif /* LOG_UNKNOWN_HEADERS */
2168 }
2169 }
2170
2171 if ( hc->one_one )
2172 {
2173 /* Check that HTTP/1.1 requests specify a host, as required. */
2174 if ( hc->reqhost[0] == '\0' && hc->hdrhost[0] == '\0' )
2175 {
2176 httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
2177 return -1;
2178 }
2179
2180 /* If the client wants to do keep-alives, it might also be doing
2181 ** pipelining. There's no way for us to tell. Since we don't
2182 ** implement keep-alives yet, if we close such a connection there
2183 ** might be unread pipelined requests waiting. So, we have to
2184 ** do a lingering close.
2185 */
2186 if ( hc->keep_alive )
2187 hc->should_linger = 1;
2188 }
2189
2190 /* Ok, the request has been parsed. Now we resolve stuff that
2191 ** may require the entire request.
2192 */
2193
2194 /* Copy original filename to expanded filename. */
2195 httpd_realloc_str(
2196 &hc->expnfilename, &hc->maxexpnfilename, strlen( hc->origfilename ) );
2197 (void) strcpy( hc->expnfilename, hc->origfilename );
2198
2199 /* Tilde mapping. */
2200 if ( hc->expnfilename[0] == '~' )
2201 {
2202 #ifdef TILDE_MAP_1
2203 if ( ! tilde_map_1( hc ) )
2204 {
2205 httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
2206 return -1;
2207 }
2208 #endif /* TILDE_MAP_1 */
2209 #ifdef TILDE_MAP_2
2210 if ( ! tilde_map_2( hc ) )
2211 {
2212 httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
2213 return -1;
2214 }
2215 #endif /* TILDE_MAP_2 */
2216 }
2217
2218 /* Virtual host mapping. */
2219 if ( hc->hs->vhost )
2220 if ( ! vhost_map( hc ) )
2221 {
2222 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
2223 return -1;
2224 }
2225
2226 /* Expand all symbolic links in the filename. This also gives us
2227 ** any trailing non-existing components, for pathinfo.
2228 */
2229 cp = expand_symlinks( hc->expnfilename, &pi, hc->hs->no_symlink, hc->tildemapped );
2230 if ( cp == (char*) 0 )
2231 {
2232 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
2233 return -1;
2234 }
2235 httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, strlen( cp ) );
2236 (void) strcpy( hc->expnfilename, cp );
2237 httpd_realloc_str( &hc->pathinfo, &hc->maxpathinfo, strlen( pi ) );
2238 (void) strcpy( hc->pathinfo, pi );
2239
2240 /* Remove pathinfo stuff from the original filename too. */
2241 if ( hc->pathinfo[0] != '\0' )
2242 {
2243 int i;
2244 i = strlen( hc->origfilename ) - strlen( hc->pathinfo );
2245 if ( i > 0 && strcmp( &hc->origfilename[i], hc->pathinfo ) == 0 )
2246 hc->origfilename[i - 1] = '\0';
2247 }
2248
2249 /* If the expanded filename is an absolute path, check that it's still
2250 ** within the current directory or the alternate directory.
2251 */
2252 if ( hc->expnfilename[0] == '/' )
2253 {
2254 if ( strncmp(
2255 hc->expnfilename, hc->hs->cwd, strlen( hc->hs->cwd ) ) == 0 )
2256 {
2257 /* Elide the current directory. */
2258 (void) strcpy(
2259 hc->expnfilename, &hc->expnfilename[strlen( hc->hs->cwd )] );
2260 }
2261 #ifdef TILDE_MAP_2
2262 else if ( hc->altdir[0] != '\0' &&
2263 ( strncmp(
2264 hc->expnfilename, hc->altdir,
2265 strlen( hc->altdir ) ) == 0 &&
2266 ( hc->expnfilename[strlen( hc->altdir )] == '\0' ||
2267 hc->expnfilename[strlen( hc->altdir )] == '/' ) ) )
2268 {}
2269 #endif /* TILDE_MAP_2 */
2270 else
2271 {
2272 syslog(
2273 LOG_NOTICE, "%.80s URL \"%.80s\" goes outside the web tree",
2274 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
2275 httpd_send_err(
2276 hc, 403, err403title, "",
2277 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file outside the permitted web server directory tree.\n" ),
2278 hc->encodedurl );
2279 return -1;
2280 }
2281 }
2282
2283 return 0;
2284 }
2285
2286
2287 static char*
2288 bufgets( httpd_conn* hc )
2289 {
2290 int i;
2291 char c;
2292
2293 for ( i = hc->checked_idx; hc->checked_idx < hc->read_idx; ++hc->checked_idx )
2294 {
2295 c = hc->read_buf[hc->checked_idx];
2296 if ( c == '\n' || c == '\r' )
2297 {
2298 hc->read_buf[hc->checked_idx] = '\0';
2299 ++hc->checked_idx;
2300 if ( c == '\r' && hc->checked_idx < hc->read_idx &&
2301 hc->read_buf[hc->checked_idx] == '\n' )
2302 {
2303 hc->read_buf[hc->checked_idx] = '\0';
2304 ++hc->checked_idx;
2305 }
2306 return &(hc->read_buf[i]);
2307 }
2308 }
2309 return (char*) 0;
2310 }
2311
2312
2313 static void
2314 de_dotdot( char* file )
2315 {
2316 char* cp;
2317 char* cp2;
2318 int l;
2319
2320 /* Collapse any multiple / sequences. */
2321 while ( ( cp = strstr( file, "//") ) != (char*) 0 )
2322 {
2323 for ( cp2 = cp + 2; *cp2 == '/'; ++cp2 )
2324 continue;
2325 (void) strcpy( cp + 1, cp2 );
2326 }
2327
2328 /* Elide any xxx/../ sequences. */
2329 while ( ( cp = strstr( file, "/../" ) ) != (char*) 0 )
2330 {
2331 for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
2332 continue;
2333 if ( cp2 < file )
2334 break;
2335 (void) strcpy( cp2, cp + 3 );
2336 }
2337
2338 /* Also elide any xxx/.. at the end. */
2339 while ( ( l = strlen( file ) ) > 3 &&
2340 strcmp( ( cp = file + l - 3 ), "/.." ) == 0 )
2341 {
2342 for ( cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2 )
2343 continue;
2344 if ( cp2 < file )
2345 break;
2346 *cp2 = '\0';
2347 }
2348 }
2349
2350
2351 void
2352 httpd_close_conn( httpd_conn* hc, struct timeval* nowP )
2353 {
2354 make_log_entry( hc, nowP );
2355
2356 if ( hc->file_address != (char*) 0 )
2357 {
2358 mmc_unmap( hc->file_address, &(hc->sb), nowP );
2359 hc->file_address = (char*) 0;
2360 }
2361 if ( hc->conn_fd >= 0 )
2362 {
2363 (void) close( hc->conn_fd );
2364 hc->conn_fd = -1;
2365 }
2366 }
2367
2368 void
2369 httpd_destroy_conn( httpd_conn* hc )
2370 {
2371 if ( hc->initialized )
2372 {
2373 free( (void*) hc->read_buf );
2374 free( (void*) hc->decodedurl );
2375 free( (void*) hc->origfilename );
2376 free( (void*) hc->expnfilename );
2377 free( (void*) hc->encodings );
2378 free( (void*) hc->pathinfo );
2379 free( (void*) hc->query );
2380 free( (void*) hc->accept );
2381 free( (void*) hc->accepte );
2382 free( (void*) hc->reqhost );
2383 free( (void*) hc->hostdir );
2384 free( (void*) hc->remoteuser );
2385 free( (void*) hc->response );
2386 #ifdef TILDE_MAP_2
2387 free( (void*) hc->altdir );
2388 #endif /* TILDE_MAP_2 */
2389 hc->initialized = 0;
2390 }
2391 }
2392
2393
2394 /* Figures out MIME encodings and type based on the filename. Multiple
2395 ** encodings are separated by semicolons.
2396 */
2397 static void
2398 figure_mime( httpd_conn* hc )
2399 {
2400 int i, j, k, l;
2401 int got_enc;
2402 struct table {
2403 char* ext;
2404 char* val;
2405 };
2406 static struct table enc_tab[] = {
2407 #include "mime_encodings.h"
2408 };
2409 static struct table typ_tab[] = {
2410 #include "mime_types.h"
2411 };
2412
2413 /* Look at the extensions on hc->expnfilename from the back forwards. */
2414 i = strlen( hc->expnfilename );
2415 for (;;)
2416 {
2417 j = i;
2418 for (;;)
2419 {
2420 --i;
2421 if ( i <= 0 )
2422 {
2423 /* No extensions left. */
2424 hc->type = "text/plain; charset=%s";
2425 return;
2426 }
2427 if ( hc->expnfilename[i] == '.' )
2428 break;
2429 }
2430 /* Found an extension. */
2431 got_enc = 0;
2432 for ( k = 0; k < sizeof(enc_tab)/sizeof(*enc_tab); ++k )
2433 {
2434 l = strlen( enc_tab[k].ext );
2435 if ( l == j - i - 1 &&
2436 strncasecmp( &hc->expnfilename[i+1], enc_tab[k].ext, l ) == 0 )
2437 {
2438 httpd_realloc_str(
2439 &hc->encodings, &hc->maxencodings,
2440 strlen( enc_tab[k].val ) + 1 );
2441 if ( hc->encodings[0] != '\0' )
2442 (void) strcat( hc->encodings, ";" );
2443 (void) strcat( hc->encodings, enc_tab[k].val );
2444 got_enc = 1;
2445 }
2446 }
2447 if ( ! got_enc )
2448 {
2449 /* No encoding extension found - time to try type extensions. */
2450 for ( k = 0; k < sizeof(typ_tab)/sizeof(*typ_tab); ++k )
2451 {
2452 l = strlen( typ_tab[k].ext );
2453 if ( l == j - i - 1 &&
2454 strncasecmp(
2455 &hc->expnfilename[i+1], typ_tab[k].ext, l ) == 0 )
2456 {
2457 hc->type = typ_tab[k].val;
2458 return;
2459 }
2460 }
2461 /* No recognized type extension found - return default. */
2462 hc->type = "text/plain; charset=%s";
2463 return;
2464 }
2465 }
2466 }
2467
2468
2469 #ifdef CGI_TIMELIMIT
2470 static void
2471 cgi_kill2( ClientData client_data, struct timeval* nowP )
2472 {
2473 pid_t pid;
2474
2475 /* Before trying to kill the CGI process, reap any zombie processes.
2476 ** That may get rid of the CGI process.
2477 */
2478 (void) do_reap();
2479
2480 pid = (pid_t) client_data.i;
2481 if ( kill( pid, SIGKILL ) == 0 )
2482 syslog( LOG_ERR, "hard-killed CGI process %d", pid );
2483 }
2484
2485 static void
2486 cgi_kill( ClientData client_data, struct timeval* nowP )
2487 {
2488 pid_t pid;
2489
2490 /* Before trying to kill the CGI process, reap any zombie processes.
2491 ** That may get rid of the CGI process.
2492 */
2493 (void) do_reap();
2494
2495 pid = (pid_t) client_data.i;
2496 if ( kill( pid, SIGINT ) == 0 )
2497 {
2498 syslog( LOG_ERR, "killed CGI process %d", pid );
2499 /* In case this isn't enough, schedule an uncatchable kill. */
2500 if ( tmr_create( nowP, cgi_kill2, client_data, 5 * 1000L, 0 ) == (Timer*) 0 )
2501 {
2502 syslog( LOG_CRIT, "tmr_create(cgi_kill2) failed" );
2503 exit( 1 );
2504 }
2505 }
2506 }
2507 #endif /* CGI_TIMELIMIT */
2508
2509
2510 #ifdef GENERATE_INDEXES
2511
2512 /* qsort comparison routine - declared old-style on purpose, for portability. */
2513 static int
2514 name_compare( a, b )
2515 char** a;
2516 char** b;
2517 {
2518 return strcmp( *a, *b );
2519 }
2520
2521
2522 static off_t
2523 ls( httpd_conn* hc )
2524 {
2525 DIR* dirp;
2526 struct dirent* de;
2527 int namlen;
2528 static int maxnames = 0;
2529 int nnames;
2530 static char* names;
2531 static char** nameptrs;
2532 static char* name;
2533 static int maxname = 0;
2534 static char* rname;
2535 static int maxrname = 0;
2536 static char* encrname;
2537 static int maxencrname = 0;
2538 FILE* fp;
2539 int i, r;
2540 struct stat sb;
2541 struct stat lsb;
2542 char modestr[20];
2543 char* linkprefix;
2544 char link[MAXPATHLEN];
2545 int linklen;
2546 char* fileclass;
2547 time_t now;
2548 char* timestr;
2549 ClientData client_data;
2550
2551 dirp = opendir( hc->expnfilename );
2552 if ( dirp == (DIR*) 0 )
2553 {
2554 syslog( LOG_ERR, "opendir %.80s - %m", hc->expnfilename );
2555 httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
2556 return -1;
2557 }
2558
2559 send_mime( hc, 200, ok200title, "", "", "text/html", -1, hc->sb.st_mtime );
2560 if ( hc->method == METHOD_HEAD )
2561 closedir( dirp );
2562 else if ( hc->method == METHOD_GET )
2563 {
2564 httpd_write_response( hc );
2565 r = fork( );
2566 if ( r < 0 )
2567 {
2568 syslog( LOG_ERR, "fork - %m" );
2569 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
2570 return -1;
2571 }
2572 if ( r == 0 )
2573 {
2574 /* Child process. */
2575 unlisten( hc->hs );
2576
2577 #ifdef CGI_NICE
2578 /* Set priority. */
2579 (void) nice( CGI_NICE );
2580 #endif /* CGI_NICE */
2581
2582 /* Open a stdio stream so that we can use fprintf, which is more
2583 ** efficient than a bunch of separate write()s. We don't have
2584 ** to worry about double closes or file descriptor leaks cause
2585 ** we're in a subprocess.
2586 */
2587 fp = fdopen( hc->conn_fd, "w" );
2588 if ( fp == (FILE*) 0 )
2589 {
2590 syslog( LOG_ERR, "fdopen - %m" );
2591 httpd_send_err(
2592 hc, 500, err500title, "", err500form, hc->encodedurl );
2593 closedir( dirp );
2594 exit( 1 );
2595 }
2596
2597 (void) fprintf( fp, "\
2598 <HTML><HEAD><TITLE>Index of %.80s</TITLE></HEAD>\n\
2599 <BODY BGCOLOR=\"#99cc99\">\n\
2600 <H2>Index of %.80s</H2>\n\
2601 <PRE>\n\
2602 mode links bytes last-changed name\n\
2603 <HR>",
2604 hc->encodedurl, hc->encodedurl );
2605
2606 /* Read in names. */
2607 nnames = 0;
2608 while ( ( de = readdir( dirp ) ) != 0 ) /* dirent or direct */
2609 {
2610 if ( nnames >= maxnames )
2611 {
2612 if ( maxnames == 0 )
2613 {
2614 maxnames = 100;
2615 names = NEW( char, maxnames * MAXPATHLEN );
2616 nameptrs = NEW( char*, maxnames );
2617 }
2618 else
2619 {
2620 maxnames *= 2;
2621 names = RENEW( names, char, maxnames * MAXPATHLEN );
2622 nameptrs = RENEW( nameptrs, char*, maxnames );
2623 }
2624 if ( names == (char*) 0 || nameptrs == (char**) 0 )
2625 {
2626 syslog( LOG_ERR, "out of memory reallocating directory names" );
2627 exit( 1 );
2628 }
2629 for ( i = 0; i < maxnames; ++i )
2630 nameptrs[i] = &names[i * MAXPATHLEN];
2631 }
2632 namlen = NAMLEN(de);
2633 (void) strncpy( nameptrs[nnames], de->d_name, namlen );
2634 nameptrs[nnames][namlen] = '\0';
2635 ++nnames;
2636 }
2637 closedir( dirp );
2638
2639 /* Sort the names. */
2640 qsort( nameptrs, nnames, sizeof(*nameptrs), name_compare );
2641
2642 /* Generate output. */
2643 for ( i = 0; i < nnames; ++i )
2644 {
2645 httpd_realloc_str(
2646 &name, &maxname,
2647 strlen( hc->expnfilename ) + 1 + strlen( nameptrs[i] ) );
2648 httpd_realloc_str(
2649 &rname, &maxrname,
2650 strlen( hc->origfilename ) + 1 + strlen( nameptrs[i] ) );
2651 if ( hc->expnfilename[0] == '\0' ||
2652 strcmp( hc->expnfilename, "." ) == 0 )
2653 {
2654 (void) strcpy( name, nameptrs[i] );
2655 (void) strcpy( rname, nameptrs[i] );
2656 }
2657 else
2658 {
2659 (void) my_snprintf( name, maxname,
2660 "%s/%s", hc->expnfilename, nameptrs[i] );
2661 if ( strcmp( hc->origfilename, "." ) == 0 )
2662 (void) my_snprintf( rname, maxrname,
2663 "%s", nameptrs[i] );
2664 else
2665 (void) my_snprintf( rname, maxrname,
2666 "%s%s", hc->origfilename, nameptrs[i] );
2667 }
2668 httpd_realloc_str(
2669 &encrname, &maxencrname, 3 * strlen( rname ) + 1 );
2670 strencode( encrname, maxencrname, rname );
2671
2672 if ( stat( name, &sb ) < 0 || lstat( name, &lsb ) < 0 )
2673 continue;
2674
2675 linkprefix = "";
2676 link[0] = '\0';
2677 /* Break down mode word. First the file type. */
2678 switch ( lsb.st_mode & S_IFMT )
2679 {
2680 case S_IFIFO: modestr[0] = 'p'; break;
2681 case S_IFCHR: modestr[0] = 'c'; break;
2682 case S_IFDIR: modestr[0] = 'd'; break;
2683 case S_IFBLK: modestr[0] = 'b'; break;
2684 case S_IFREG: modestr[0] = '-'; break;
2685 case S_IFSOCK: modestr[0] = 's'; break;
2686 case S_IFLNK: modestr[0] = 'l';
2687 linklen = readlink( name, link, sizeof(link) );
2688 if ( linklen != -1 )
2689 {
2690 link[linklen] = '\0';
2691 linkprefix = " -> ";
2692 }
2693 break;
2694 default: modestr[0] = '?'; break;
2695 }
2696 /* Now the world permissions. Owner and group permissions
2697 ** are not of interest to web clients.
2698 */
2699 modestr[1] = ( lsb.st_mode & S_IROTH ) ? 'r' : '-';
2700 modestr[2] = ( lsb.st_mode & S_IWOTH ) ? 'w' : '-';
2701 modestr[3] = ( lsb.st_mode & S_IXOTH ) ? 'x' : '-';
2702 modestr[4] = '\0';
2703
2704 /* We also leave out the owner and group name, they are
2705 ** also not of interest to web clients. Plus if we're
2706 ** running under chroot(), they would require a copy
2707 ** of /etc/passwd and /etc/group, which we want to avoid.
2708 */
2709
2710 /* Get time string. */
2711 now = time( (time_t*) 0 );
2712 timestr = ctime( &lsb.st_mtime );
2713 timestr[ 0] = timestr[ 4];
2714 timestr[ 1] = timestr[ 5];
2715 timestr[ 2] = timestr[ 6];
2716 timestr[ 3] = ' ';
2717 timestr[ 4] = timestr[ 8];
2718 timestr[ 5] = timestr[ 9];
2719 timestr[ 6] = ' ';
2720 if ( now - lsb.st_mtime > 60*60*24*182 ) /* 1/2 year */
2721 {
2722 timestr[ 7] = ' ';
2723 timestr[ 8] = timestr[20];
2724 timestr[ 9] = timestr[21];
2725 timestr[10] = timestr[22];
2726 timestr[11] = timestr[23];
2727 }
2728 else
2729 {
2730 timestr[ 7] = timestr[11];
2731 timestr[ 8] = timestr[12];
2732 timestr[ 9] = ':';
2733 timestr[10] = timestr[14];
2734 timestr[11] = timestr[15];
2735 }
2736 timestr[12] = '\0';
2737
2738 /* The ls -F file class. */
2739 switch ( sb.st_mode & S_IFMT )
2740 {
2741 case S_IFDIR: fileclass = "/"; break;
2742 case S_IFSOCK: fileclass = "="; break;
2743 case S_IFLNK: fileclass = "@"; break;
2744 default:
2745 fileclass = ( sb.st_mode & S_IXOTH ) ? "*" : "";
2746 break;
2747 }
2748
2749 /* And print. */
2750 (void) fprintf( fp,
2751 "%s %3ld %8ld %s <A HREF=\"/%.500s%s\">%.80s</A>%s%s%s\n",
2752 modestr, (long) lsb.st_nlink, (long) lsb.st_size, timestr,
2753 encrname, S_ISDIR(sb.st_mode) ? "/" : "",
2754 nameptrs[i], linkprefix, link, fileclass );
2755 }
2756
2757 (void) fprintf( fp, "</PRE></BODY></HTML>\n" );
2758 (void) fclose( fp );
2759 exit( 0 );
2760 }
2761
2762 /* Parent process. */
2763 closedir( dirp );
2764 syslog( LOG_INFO, "spawned indexing process %d for directory '%.200s'", r, hc->expnfilename );
2765 #ifdef CGI_TIMELIMIT
2766 /* Schedule a kill for the child process, in case it runs too long */
2767 client_data.i = r;
2768 if ( tmr_create( (struct timeval*) 0, cgi_kill, client_data, CGI_TIMELIMIT * 1000L, 0 ) == (Timer*) 0 )
2769 {
2770 syslog( LOG_CRIT, "tmr_create(cgi_kill) failed" );
2771 exit( 1 );
2772 }
2773 #endif /* CGI_TIMELIMIT */
2774 hc->status = 200;
2775 hc->bytes_sent = CGI_BYTECOUNT;
2776 hc->should_linger = 0;
2777 }
2778 else
2779 {
2780 httpd_send_err(
2781 hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) );
2782 return -1;
2783 }
2784
2785 return 0;
2786 }
2787
2788 #endif /* GENERATE_INDEXES */
2789
2790
2791 static char*
2792 build_env( char* fmt, char* arg )
2793 {
2794 char* cp;
2795 int size;
2796 static char* buf;
2797 static int maxbuf = 0;
2798
2799 size = strlen( fmt ) + strlen( arg );
2800 if ( size > maxbuf )
2801 httpd_realloc_str( &buf, &maxbuf, size );
2802 (void) my_snprintf( buf, maxbuf,
2803 fmt, arg );
2804 cp = strdup( buf );
2805 if ( cp == (char*) 0 )
2806 {
2807 syslog( LOG_ERR, "out of memory copying environment variable" );
2808 exit( 1 );
2809 }
2810 return cp;
2811 }
2812
2813
2814 #ifdef SERVER_NAME_LIST
2815 static char*
2816 hostname_map( char* hostname )
2817 {
2818 int len, n;
2819 static char* list[] = { SERVER_NAME_LIST };
2820
2821 len = strlen( hostname );
2822 for ( n = sizeof(list) / sizeof(*list) - 1; n >= 0; --n )
2823 if ( strncasecmp( hostname, list[n], len ) == 0 )
2824 if ( list[n][len] == '/' ) /* check in case of a substring match */
2825 return &list[n][len + 1];
2826 return (char*) 0;
2827 }
2828 #endif /* SERVER_NAME_LIST */
2829
2830
2831 /* Set up environment variables. Be real careful here to avoid
2832 ** letting malicious clients overrun a buffer. We don't have
2833 ** to worry about freeing stuff since we're a sub-process.
2834 */
2835 static char**
2836 make_envp( httpd_conn* hc )
2837 {
2838 static char* envp[50];
2839 int envn;
2840 char* cp;
2841 char buf[256];
2842
2843 envn = 0;
2844 envp[envn++] = build_env( "PATH=%s", CGI_PATH );
2845 #ifdef CGI_LD_LIBRARY_PATH
2846 envp[envn++] = build_env( "LD_LIBRARY_PATH=%s", CGI_LD_LIBRARY_PATH );
2847 #endif /* CGI_LD_LIBRARY_PATH */
2848 envp[envn++] = build_env( "SERVER_SOFTWARE=%s", SERVER_SOFTWARE );
2849 /* If vhosting, use that server-name here. */
2850 if ( hc->hs->vhost && hc->hostname != (char*) 0 )
2851 cp = hc->hostname;
2852 else
2853 cp = hc->hs->server_hostname;
2854 if ( cp != (char*) 0 )
2855 envp[envn++] = build_env( "SERVER_NAME=%s", cp );
2856 envp[envn++] = "GATEWAY_INTERFACE=CGI/1.1";
2857 envp[envn++] = build_env("SERVER_PROTOCOL=%s", hc->protocol);
2858 (void) my_snprintf( buf, sizeof(buf),
2859 "%d", hc->hs->port );
2860 envp[envn++] = build_env( "SERVER_PORT=%s", buf );
2861 envp[envn++] = build_env(
2862 "REQUEST_METHOD=%s", httpd_method_str( hc->method ) );
2863 if ( hc->pathinfo[0] != '\0' )
2864 {
2865 char* cp2;
2866 int l;
2867 envp[envn++] = build_env( "PATH_INFO=/%s", hc->pathinfo );
2868 l = strlen( hc->hs->cwd ) + strlen( hc->pathinfo ) + 1;
2869 cp2 = NEW( char, l );
2870 if ( cp2 != (char*) 0 )
2871 {
2872 (void) my_snprintf( cp2, l,
2873 "%s%s", hc->hs->cwd, hc->pathinfo );
2874 envp[envn++] = build_env( "PATH_TRANSLATED=%s", cp2 );
2875 }
2876 }
2877 envp[envn++] = build_env(
2878 "SCRIPT_NAME=/%s", strcmp( hc->origfilename, "." ) == 0 ?
2879 "" : hc->origfilename );
2880 if ( hc->query[0] != '\0')
2881 envp[envn++] = build_env( "QUERY_STRING=%s", hc->query );
2882 envp[envn++] = build_env(
2883 "REMOTE_ADDR=%s", httpd_ntoa( &hc->client_addr ) );
2884 if ( hc->referer[0] != '\0' )
2885 envp[envn++] = build_env( "HTTP_REFERER=%s", hc->referer );
2886 if ( hc->useragent[0] != '\0' )
2887 envp[envn++] = build_env( "HTTP_USER_AGENT=%s", hc->useragent );
2888 if ( hc->accept[0] != '\0' )
2889 envp[envn++] = build_env( "HTTP_ACCEPT=%s", hc->accept );
2890 if ( hc->accepte[0] != '\0' )
2891 envp[envn++] = build_env( "HTTP_ACCEPT_ENCODING=%s", hc->accepte );
2892 if ( hc->acceptl[0] != '\0' )
2893 envp[envn++] = build_env( "HTTP_ACCEPT_LANGUAGE=%s", hc->acceptl );
2894 if ( hc->cookie[0] != '\0' )
2895 envp[envn++] = build_env( "HTTP_COOKIE=%s", hc->cookie );
2896 if ( hc->contenttype[0] != '\0' )
2897 envp[envn++] = build_env( "CONTENT_TYPE=%s", hc->contenttype );
2898 if ( hc->hdrhost[0] != '\0' )
2899 envp[envn++] = build_env( "HTTP_HOST=%s", hc->hdrhost );
2900 if ( hc->contentlength != -1 )
2901 {
2902 (void) my_snprintf( buf, sizeof(buf),
2903 "%ld", (long) hc->contentlength );
2904 envp[envn++] = build_env( "CONTENT_LENGTH=%s", buf );
2905 }
2906 if ( hc->remoteuser[0] != '\0' )
2907 envp[envn++] = build_env( "REMOTE_USER=%s", hc->remoteuser );
2908 if ( hc->authorization[0] == '\0' )
2909 envp[envn++] = build_env( "AUTH_TYPE=%s", "Basic" );
2910 /* We only support Basic auth at the moment. */
2911 if ( getenv( "TZ" ) != (char*) 0 )
2912 envp[envn++] = build_env( "TZ=%s", getenv( "TZ" ) );
2913 envp[envn++] = build_env( "CGI_PATTERN=%s", hc->hs->cgi_pattern );
2914
2915 envp[envn] = (char*) 0;
2916 return envp;
2917 }
2918
2919
2920 /* Set up argument vector. Again, we don't have to worry about freeing stuff
2921 ** since we're a sub-process. This gets done after make_envp() because we
2922 ** scribble on hc->query.
2923 */
2924 static char**
2925 make_argp( httpd_conn* hc )
2926 {
2927 char** argp;
2928 int argn;
2929 char* cp1;
2930 char* cp2;
2931
2932 /* By allocating an arg slot for every character in the query, plus
2933 ** one for the filename and one for the NULL, we are guaranteed to
2934 ** have enough. We could actually use strlen/2.
2935 */
2936 argp = NEW( char*, strlen( hc->query ) + 2 );
2937 if ( argp == (char**) 0 )
2938 return (char**) 0;
2939
2940 argp[0] = strrchr( hc->expnfilename, '/' );
2941 if ( argp[0] != (char*) 0 )
2942 ++argp[0];
2943 else
2944 argp[0] = hc->expnfilename;
2945
2946 argn = 1;
2947 /* According to the CGI spec at http://hoohoo.ncsa.uiuc.edu/cgi/cl.html,
2948 ** "The server should search the query information for a non-encoded =
2949 ** character to determine if the command line is to be used, if it finds
2950 ** one, the command line is not to be used."
2951 */
2952 if ( strchr( hc->query, '=' ) == (char*) 0 )
2953 {
2954 for ( cp1 = cp2 = hc->query; *cp2 != '\0'; ++cp2 )
2955 {
2956 if ( *cp2 == '+' )
2957 {
2958 *cp2 = '\0';
2959 strdecode( cp1, cp1 );
2960 argp[argn++] = cp1;
2961 cp1 = cp2 + 1;
2962 }
2963 }
2964 if ( cp2 != cp1 )
2965 {
2966 strdecode( cp1, cp1 );
2967 argp[argn++] = cp1;
2968 }
2969 }
2970
2971 argp[argn] = (char*) 0;
2972 return argp;
2973 }
2974
2975
2976 /* This routine is used only for POST requests. It reads the data
2977 ** from the request and sends it to the child process. The only reason
2978 ** we need to do it this way instead of just letting the child read
2979 ** directly is that we have already read part of the data into our
2980 ** buffer.
2981 */
2982 static void
2983 cgi_interpose_input( httpd_conn* hc, int wfd )
2984 {
2985 int c, r;
2986 char buf[1024];
2987
2988 c = hc->read_idx - hc->checked_idx;
2989 if ( c > 0 )
2990 {
2991 if ( write( wfd, &(hc->read_buf[hc->checked_idx]), c ) != c )
2992 return;
2993 }
2994 while ( c < hc->contentlength )
2995 {
2996 r = read( hc->conn_fd, buf, MIN( sizeof(buf), hc->contentlength - c ) );
2997 if ( r == 0 )
2998 sleep( 1 );
2999 else if ( r < 0 )
3000 {
3001 if ( errno == EAGAIN )
3002 sleep( 1 );
3003 else
3004 return;
3005 }
3006 else
3007 {
3008 if ( write( wfd, buf, r ) != r )
3009 return;
3010 c += r;
3011 }
3012 }
3013 post_post_garbage_hack( hc );
3014 }
3015
3016
3017 /* Special hack to deal with broken browsers that send a LF or CRLF
3018 ** after POST data, causing TCP resets - we just read and discard up
3019 ** to 2 bytes. Unfortunately this doesn't fix the problem for CGIs
3020 ** which avoid the interposer process due to their POST data being
3021 ** short. Creating an interposer process for all POST CGIs is
3022 ** unacceptably expensive. The eventual fix will come when interposing
3023 ** gets integrated into the main loop as a tasklet instead of a process.
3024 */
3025 static void
3026 post_post_garbage_hack( httpd_conn* hc )
3027 {
3028 char buf[2];
3029 int r;
3030
3031 r = recv( hc->conn_fd, buf, sizeof(buf), MSG_PEEK );
3032 if ( r > 0 )
3033 (void) read( hc->conn_fd, buf, r );
3034 }
3035
3036
3037 /* This routine is used for parsed-header CGIs. The idea here is that the
3038 ** CGI can return special headers such as "Status:" and "Location:" which
3039 ** change the return status of the response. Since the return status has to
3040 ** be the very first line written out, we have to accumulate all the headers
3041 ** and check for the special ones before writing the status. Then we write
3042 ** out the saved headers and proceed to echo the rest of the response.
3043 */
3044 static void
3045 cgi_interpose_output( httpd_conn* hc, int rfd )
3046 {
3047 int r;
3048 char buf[1024];
3049 int headers_size, headers_len;
3050 char* headers;
3051 char* br;
3052 int status;
3053 char* title;
3054 char* cp;
3055
3056 /* Slurp in all headers. */
3057 headers_size = 0;
3058 httpd_realloc_str( &headers, &headers_size, 500 );
3059 headers_len = 0;
3060 for (;;)
3061 {
3062 r = read( rfd, buf, sizeof(buf) );
3063 if ( r <= 0 )
3064 {
3065 br = &(headers[headers_len]);
3066 break;
3067 }
3068 httpd_realloc_str( &headers, &headers_size, headers_len + r );
3069 (void) memcpy( &(headers[headers_len]), buf, r );
3070 headers_len += r;
3071 headers[headers_len] = '\0';
3072 if ( ( br = strstr( headers, "\r\n\r\n" ) ) != (char*) 0 ||
3073 ( br = strstr( headers, "\n\n" ) ) != (char*) 0 )
3074 break;
3075 }
3076
3077 /* Figure out the status. */
3078 status = 200;
3079 if ( ( cp = strstr( headers, "Status:" ) ) != (char*) 0 &&
3080 cp < br &&
3081 ( cp == headers || *(cp-1) == '\n' ) )
3082 {
3083 cp += 7;
3084 cp += strspn( cp, " \t" );
3085 status = atoi( cp );
3086 }
3087 if ( ( cp = strstr( headers, "Location:" ) ) != (char*) 0 &&
3088 cp < br &&
3089 ( cp == headers || *(cp-1) == '\n' ) )
3090 status = 302;
3091
3092 /* Write the status line. */
3093 switch ( status )
3094 {
3095 case 200: title = ok200title; break;
3096 case 302: title = err302title; break;
3097 case 304: title = err304title; break;
3098 case 400: title = httpd_err400title; break;
3099 #ifdef AUTH_FILE
3100 case 401: title = err401title; break;
3101 #endif /* AUTH_FILE */
3102 case 403: title = err403title; break;
3103 case 404: title = err404title; break;
3104 case 408: title = httpd_err408title; break;
3105 case 500: title = err500title; break;
3106 case 501: title = err501title; break;
3107 case 503: title = httpd_err503title; break;
3108 default: title = "Something"; break;
3109 }
3110 (void) my_snprintf( buf, sizeof(buf), "HTTP/1.0 %d %s\r\n", status, title );
3111 (void) write( hc->conn_fd, buf, strlen( buf ) );
3112
3113 /* Write the saved headers. */
3114 (void) write( hc->conn_fd, headers, headers_len );
3115
3116 /* Echo the rest of the output. */
3117 for (;;)
3118 {
3119 r = read( rfd, buf, sizeof(buf) );
3120 if ( r <= 0 )
3121 return;
3122 if ( write( hc->conn_fd, buf, r ) != r )
3123 return;
3124 }
3125 }
3126
3127
3128 /* CGI child process. */
3129 static void
3130 cgi_child( httpd_conn* hc )
3131 {
3132 int r;
3133 char** argp;
3134 char** envp;
3135 char* binary;
3136 char* directory;
3137
3138 /* Unset close-on-exec flag for this socket. This actually shouldn't
3139 ** be necessary, according to POSIX a dup()'d file descriptor does
3140 ** *not* inherit the close-on-exec flag, its flag is always clear.
3141 ** However, Linux messes this up and does copy the flag to the
3142 ** dup()'d descriptor, so we have to clear it. This could be
3143 ** ifdeffed for Linux only.
3144 */
3145 (void) fcntl( hc->conn_fd, F_SETFD, 0 );
3146
3147 /* Close the syslog descriptor so that the CGI program can't
3148 ** mess with it. All other open descriptors should be either
3149 ** the listen socket(s), sockets from accept(), or the file-logging
3150 ** fd, and all of those are set to close-on-exec, so we don't
3151 ** have to close anything else.
3152 */
3153 closelog();
3154
3155 /* If the socket happens to be using one of the stdin/stdout/stderr
3156 ** descriptors, move it to another descriptor so that the dup2 calls
3157 ** below don't screw things up.
3158 */
3159 if ( hc->conn_fd == STDIN_FILENO || hc->conn_fd == STDOUT_FILENO || hc->conn_fd == STDERR_FILENO )
3160 {
3161 int newfd = dup( hc->conn_fd );
3162 if ( newfd >= 0 )
3163 hc->conn_fd = newfd;
3164 /* If the dup fails, shrug. We'll just take our chances.
3165 ** Shouldn't happen though.
3166 **
3167 ** If the dup happens to produce an fd that is still one of
3168 ** the standard ones, we should be ok - I think it can be
3169 ** fd 2, stderr, but can never show up as 0 or 1 since at
3170 ** least two file descriptors are always in use. Because
3171 ** of the order in which we dup2 things below - stderr is
3172 ** always done last - it's actually ok for the socket to
3173 ** be fd 2. It'll just get dup2'd onto itself.
3174 */
3175 }
3176
3177 /* Make the environment vector. */
3178 envp = make_envp( hc );
3179
3180 /* Make the argument vector. */
3181 argp = make_argp( hc );
3182
3183 /* Set up stdin. For POSTs we may have to set up a pipe from an
3184 ** interposer process, depending on if we've read some of the data
3185 ** into our buffer.
3186 */
3187 if ( hc->method == METHOD_POST && hc->read_idx > hc->checked_idx )
3188 {
3189 int p[2];
3190
3191 if ( pipe( p ) < 0 )
3192 {
3193 syslog( LOG_ERR, "pipe - %m" );
3194 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3195 exit( 1 );
3196 }
3197 r = fork( );
3198 if ( r < 0 )
3199 {
3200 syslog( LOG_ERR, "fork - %m" );
3201 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3202 exit( 1 );
3203 }
3204 if ( r == 0 )
3205 {
3206 /* Interposer process. */
3207 (void) close( p[0] );
3208 cgi_interpose_input( hc, p[1] );
3209 exit( 0 );
3210 }
3211 (void) close( p[1] );
3212 (void) dup2( p[0], STDIN_FILENO );
3213 (void) close( p[0] );
3214 }
3215 else
3216 {
3217 /* Otherwise, the request socket is stdin. */
3218 (void) dup2( hc->conn_fd, STDIN_FILENO );
3219 }
3220
3221 /* Set up stdout/stderr. If we're doing CGI header parsing,
3222 ** we need an output interposer too.
3223 */
3224 if ( strncmp( argp[0], "nph-", 4 ) != 0 && hc->mime_flag )
3225 {
3226 int p[2];
3227
3228 if ( pipe( p ) < 0 )
3229 {
3230 syslog( LOG_ERR, "pipe - %m" );
3231 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3232 exit( 1 );
3233 }
3234 r = fork( );
3235 if ( r < 0 )
3236 {
3237 syslog( LOG_ERR, "fork - %m" );
3238 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3239 exit( 1 );
3240 }
3241 if ( r == 0 )
3242 {
3243 /* Interposer process. */
3244 (void) close( p[1] );
3245 cgi_interpose_output( hc, p[0] );
3246 exit( 0 );
3247 }
3248 (void) close( p[0] );
3249 (void) dup2( p[1], STDOUT_FILENO );
3250 (void) dup2( p[1], STDERR_FILENO );
3251 (void) close( p[1] );
3252 }
3253 else
3254 {
3255 /* Otherwise, the request socket is stdout/stderr. */
3256 (void) dup2( hc->conn_fd, STDOUT_FILENO );
3257 (void) dup2( hc->conn_fd, STDERR_FILENO );
3258 }
3259
3260 /* At this point we would like to set close-on-exec again for hc->conn_fd
3261 ** (see previous comments on Linux's broken behavior re: close-on-exec
3262 ** and dup.) Unfortunately there seems to be another Linux problem, or
3263 ** perhaps a different aspect of the same problem - if we do this
3264 ** close-on-exec in Linux, the socket stays open but stderr gets
3265 ** closed - the last fd duped from the socket. What a mess. So we'll
3266 ** just leave the socket as is, which under other OSs means an extra
3267 ** file descriptor gets passed to the child process. Since the child
3268 ** probably already has that file open via stdin stdout and/or stderr,
3269 ** this is not a problem.
3270 */
3271 /* (void) fcntl( hc->conn_fd, F_SETFD, 1 ); */
3272
3273 #ifdef CGI_NICE
3274 /* Set priority. */
3275 (void) nice( CGI_NICE );
3276 #endif /* CGI_NICE */
3277
3278 /* Split the program into directory and binary, so we can chdir()
3279 ** to the program's own directory. This isn't in the CGI 1.1
3280 ** spec, but it's what other HTTP servers do.
3281 */
3282 directory = strdup( hc->expnfilename );
3283 if ( directory == (char*) 0 )
3284 binary = hc->expnfilename; /* ignore errors */
3285 else
3286 {
3287 binary = strrchr( directory, '/' );
3288 if ( binary == (char*) 0 )
3289 binary = hc->expnfilename;
3290 else
3291 {
3292 *binary++ = '\0';
3293 (void) chdir( directory ); /* ignore errors */
3294 }
3295 }
3296
3297 /* Default behavior for SIGPIPE. */
3298 (void) signal( SIGPIPE, SIG_DFL );
3299
3300 /* Run the program. */
3301 (void) execve( binary, argp, envp );
3302
3303 /* Something went wrong. */
3304 syslog( LOG_ERR, "execve %.80s - %m", hc->expnfilename );
3305 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3306 exit( 1 );
3307 }
3308
3309
3310 static off_t
3311 cgi( httpd_conn* hc )
3312 {
3313 int r;
3314 ClientData client_data;
3315
3316 if ( hc->method == METHOD_GET || hc->method == METHOD_POST )
3317 {
3318 httpd_clear_ndelay( hc->conn_fd );
3319 r = fork( );
3320 if ( r < 0 )
3321 {
3322 syslog( LOG_ERR, "fork - %m" );
3323 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3324 return -1;
3325 }
3326 if ( r == 0 )
3327 {
3328 unlisten( hc->hs );
3329 cgi_child( hc );
3330 }
3331
3332 /* Parent process. */
3333 syslog( LOG_INFO, "spawned CGI process %d for file '%.200s'", r, hc->expnfilename );
3334 #ifdef CGI_TIMELIMIT
3335 /* Schedule a kill for the child process, in case it runs too long */
3336 client_data.i = r;
3337 if ( tmr_create( (struct timeval*) 0, cgi_kill, client_data, CGI_TIMELIMIT * 1000L, 0 ) == (Timer*) 0 )
3338 {
3339 syslog( LOG_CRIT, "tmr_create(cgi_kill) failed" );
3340 exit( 1 );
3341 }
3342 #endif /* CGI_TIMELIMIT */
3343 hc->status = 200;
3344 hc->bytes_sent = CGI_BYTECOUNT;
3345 hc->should_linger = 0;
3346 }
3347 else
3348 {
3349 httpd_send_err(
3350 hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) );
3351 return -1;
3352 }
3353
3354 return 0;
3355 }
3356
3357
3358 static int
3359 really_start_request( httpd_conn* hc, struct timeval* nowP )
3360 {
3361 static char* indexname;
3362 static int maxindexname = 0;
3363 static const char* index_names[] = { INDEX_NAMES };
3364 int i;
3365 #ifdef AUTH_FILE
3366 static char* dirname;
3367 static int maxdirname = 0;
3368 #endif /* AUTH_FILE */
3369 int expnlen, indxlen;
3370 char* cp;
3371 char* pi;
3372
3373 expnlen = strlen( hc->expnfilename );
3374
3375 if ( hc->method != METHOD_GET && hc->method != METHOD_HEAD &&
3376 hc->method != METHOD_POST )
3377 {
3378 httpd_send_err(
3379 hc, 501, err501title, "", err501form, httpd_method_str( hc->method ) );
3380 return -1;
3381 }
3382
3383 /* Stat the file. */
3384 if ( stat( hc->expnfilename, &hc->sb ) < 0 )
3385 {
3386 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3387 return -1;
3388 }
3389
3390 /* Is it world-readable or world-executable? We check explicitly instead
3391 ** of just trying to open it, so that no one ever gets surprised by
3392 ** a file that's not set world-readable and yet somehow is
3393 ** readable by the HTTP server and therefore the *whole* world.
3394 */
3395 if ( ! ( hc->sb.st_mode & ( S_IROTH | S_IXOTH ) ) )
3396 {
3397 syslog(
3398 LOG_INFO,
3399 "%.80s URL \"%.80s\" resolves to a non world-readable file",
3400 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3401 httpd_send_err(
3402 hc, 403, err403title, "",
3403 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a file that is not world-readable.\n" ),
3404 hc->encodedurl );
3405 return -1;
3406 }
3407
3408 /* Is it a directory? */
3409 if ( S_ISDIR(hc->sb.st_mode) )
3410 {
3411 /* If there's pathinfo, it's just a non-existent file. */
3412 if ( hc->pathinfo[0] != '\0' )
3413 {
3414 httpd_send_err( hc, 404, err404title, "", err404form, hc->encodedurl );
3415 return -1;
3416 }
3417
3418 /* Special handling for directory URLs that don't end in a slash.
3419 ** We send back an explicit redirect with the slash, because
3420 ** otherwise many clients can't build relative URLs properly.
3421 */
3422 if ( hc->decodedurl[strlen( hc->decodedurl ) - 1] != '/' )
3423 {
3424 send_dirredirect( hc );
3425 return -1;
3426 }
3427
3428 /* Check for an index file. */
3429 for ( i = 0; i < sizeof(index_names) / sizeof(char*); ++i )
3430 {
3431 httpd_realloc_str(
3432 &indexname, &maxindexname,
3433 expnlen + 1 + strlen( index_names[i] ) );
3434 (void) strcpy( indexname, hc->expnfilename );
3435 indxlen = strlen( indexname );
3436 if ( indxlen == 0 || indexname[indxlen - 1] != '/' )
3437 (void) strcat( indexname, "/" );
3438 if ( strcmp( indexname, "./" ) == 0 )
3439 indexname[0] = '\0';
3440 (void) strcat( indexname, index_names[i] );
3441 if ( stat( indexname, &hc->sb ) >= 0 )
3442 goto got_one;
3443 }
3444
3445 /* Nope, no index file, so it's an actual directory request. */
3446 #ifdef GENERATE_INDEXES
3447 /* Directories must be readable for indexing. */
3448 if ( ! ( hc->sb.st_mode & S_IROTH ) )
3449 {
3450 syslog(
3451 LOG_INFO,
3452 "%.80s URL \"%.80s\" tried to index a directory with indexing disabled",
3453 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3454 httpd_send_err(
3455 hc, 403, err403title, "",
3456 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to a directory that has indexing disabled.\n" ),
3457 hc->encodedurl );
3458 return -1;
3459 }
3460 #ifdef AUTH_FILE
3461 /* Check authorization for this directory. */
3462 if ( auth_check( hc, hc->expnfilename ) == -1 )
3463 return -1;
3464 #endif /* AUTH_FILE */
3465 /* Referer check. */
3466 if ( ! check_referer( hc ) )
3467 return -1;
3468 /* Ok, generate an index. */
3469 return ls( hc );
3470 #else /* GENERATE_INDEXES */
3471 syslog(
3472 LOG_INFO, "%.80s URL \"%.80s\" tried to index a directory",
3473 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3474 httpd_send_err(
3475 hc, 403, err403title, "",
3476 ERROR_FORM( err403form, "The requested URL '%.80s' is a directory, and directory indexing is disabled on this server.\n" ),
3477 hc->encodedurl );
3478 return -1;
3479 #endif /* GENERATE_INDEXES */
3480
3481 got_one: ;
3482 /* Got an index file. Expand symlinks again. More pathinfo means
3483 ** something went wrong.
3484 */
3485 cp = expand_symlinks( indexname, &pi, hc->hs->no_symlink, hc->tildemapped );
3486 if ( cp == (char*) 0 || pi[0] != '\0' )
3487 {
3488 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3489 return -1;
3490 }
3491 expnlen = strlen( cp );
3492 httpd_realloc_str( &hc->expnfilename, &hc->maxexpnfilename, expnlen );
3493 (void) strcpy( hc->expnfilename, cp );
3494
3495 /* Now, is the index version world-readable or world-executable? */
3496 if ( ! ( hc->sb.st_mode & ( S_IROTH | S_IXOTH ) ) )
3497 {
3498 syslog(
3499 LOG_INFO,
3500 "%.80s URL \"%.80s\" resolves to a non-world-readable index file",
3501 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3502 httpd_send_err(
3503 hc, 403, err403title, "",
3504 ERROR_FORM( err403form, "The requested URL '%.80s' resolves to an index file that is not world-readable.\n" ),
3505 hc->encodedurl );
3506 return -1;
3507 }
3508 }
3509
3510 #ifdef AUTH_FILE
3511 /* Check authorization for this directory. */
3512 httpd_realloc_str( &dirname, &maxdirname, expnlen );
3513 (void) strcpy( dirname, hc->expnfilename );
3514 cp = strrchr( dirname, '/' );
3515 if ( cp == (char*) 0 )
3516 (void) strcpy( dirname, "." );
3517 else
3518 *cp = '\0';
3519 if ( auth_check( hc, dirname ) == -1 )
3520 return -1;
3521
3522 /* Check if the filename is the AUTH_FILE itself - that's verboten. */
3523 if ( expnlen == sizeof(AUTH_FILE) - 1 )
3524 {
3525 if ( strcmp( hc->expnfilename, AUTH_FILE ) == 0 )
3526 {
3527 syslog(
3528 LOG_NOTICE,
3529 "%.80s URL \"%.80s\" tried to retrieve an auth file",
3530 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3531 httpd_send_err(
3532 hc, 403, err403title, "",
3533 ERROR_FORM( err403form, "The requested URL '%.80s' is an authorization file, retrieving it is not permitted.\n" ),
3534 hc->encodedurl );
3535 return -1;
3536 }
3537 }
3538 else if ( expnlen >= sizeof(AUTH_FILE) &&
3539 strcmp( &(hc->expnfilename[expnlen - sizeof(AUTH_FILE) + 1]), AUTH_FILE ) == 0 &&
3540 hc->expnfilename[expnlen - sizeof(AUTH_FILE)] == '/' )
3541 {
3542 syslog(
3543 LOG_NOTICE,
3544 "%.80s URL \"%.80s\" tried to retrieve an auth file",
3545 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3546 httpd_send_err(
3547 hc, 403, err403title, "",
3548 ERROR_FORM( err403form, "The requested URL '%.80s' is an authorization file, retrieving it is not permitted.\n" ),
3549 hc->encodedurl );
3550 return -1;
3551 }
3552 #endif /* AUTH_FILE */
3553
3554 /* Referer check. */
3555 if ( ! check_referer( hc ) )
3556 return -1;
3557
3558 /* Is it world-executable and in the CGI area? */
3559 if ( hc->hs->cgi_pattern != (char*) 0 &&
3560 ( hc->sb.st_mode & S_IXOTH ) &&
3561 match( hc->hs->cgi_pattern, hc->expnfilename ) )
3562 return cgi( hc );
3563
3564 /* It's not CGI. If it's executable or there's pathinfo, someone's
3565 ** trying to either serve or run a non-CGI file as CGI. Either case
3566 ** is prohibited.
3567 */
3568 if ( hc->sb.st_mode & S_IXOTH )
3569 {
3570 syslog(
3571 LOG_NOTICE, "%.80s URL \"%.80s\" is executable but isn't CGI",
3572 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3573 httpd_send_err(
3574 hc, 403, err403title, "",
3575 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" ),
3576 hc->encodedurl );
3577 return -1;
3578 }
3579 if ( hc->pathinfo[0] != '\0' )
3580 {
3581 syslog(
3582 LOG_INFO, "%.80s URL \"%.80s\" has pathinfo but isn't CGI",
3583 httpd_ntoa( &hc->client_addr ), hc->encodedurl );
3584 httpd_send_err(
3585 hc, 403, err403title, "",
3586 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" ),
3587 hc->encodedurl );
3588 return -1;
3589 }
3590
3591 /* Fill in end_byte_loc, if necessary. */
3592 if ( hc->got_range &&
3593 ( hc->end_byte_loc == -1 || hc->end_byte_loc >= hc->sb.st_size ) )
3594 hc->end_byte_loc = hc->sb.st_size - 1;
3595
3596 figure_mime( hc );
3597
3598 if ( hc->method == METHOD_HEAD )
3599 {
3600 send_mime(
3601 hc, 200, ok200title, hc->encodings, "", hc->type, hc->sb.st_size,
3602 hc->sb.st_mtime );
3603 }
3604 else if ( hc->if_modified_since != (time_t) -1 &&
3605 hc->if_modified_since >= hc->sb.st_mtime )
3606 {
3607 hc->method = METHOD_HEAD;
3608 send_mime(
3609 hc, 304, err304title, hc->encodings, "", hc->type, hc->sb.st_size,
3610 hc->sb.st_mtime );
3611 }
3612 else
3613 {
3614 hc->file_address = mmc_map( hc->expnfilename, &(hc->sb), nowP );
3615 if ( hc->file_address == (char*) 0 )
3616 {
3617 httpd_send_err( hc, 500, err500title, "", err500form, hc->encodedurl );
3618 return -1;
3619 }
3620 send_mime(
3621 hc, 200, ok200title, hc->encodings, "", hc->type, hc->sb.st_size,
3622 hc->sb.st_mtime );
3623 }
3624
3625 return 0;
3626 }
3627
3628
3629 int
3630 httpd_start_request( httpd_conn* hc, struct timeval* nowP )
3631 {
3632 int r;
3633
3634 /* Really start the request. */
3635 r = really_start_request( hc, nowP );
3636
3637 /* And return the status. */
3638 return r;
3639 }
3640
3641
3642 static void
3643 make_log_entry( httpd_conn* hc, struct timeval* nowP )
3644 {
3645 char* ru;
3646 char url[305];
3647 char bytes[40];
3648
3649 if ( hc->hs->no_log )
3650 return;
3651
3652 /* This is straight CERN Combined Log Format - the only tweak
3653 ** being that if we're using syslog() we leave out the date, because
3654 ** syslogd puts it in. The included syslogtocern script turns the
3655 ** results into true CERN format.
3656 */
3657
3658 /* Format remote user. */
3659 if ( hc->remoteuser[0] != '\0' )
3660 ru = hc->remoteuser;
3661 else
3662 ru = "-";
3663 /* If we're vhosting, prepend the hostname to the url. This is
3664 ** a little weird, perhaps writing separate log files for
3665 ** each vhost would make more sense.
3666 */
3667 if ( hc->hs->vhost && ! hc->tildemapped )
3668 (void) my_snprintf( url, sizeof(url),
3669 "/%.100s%.200s",
3670 hc->hostname == (char*) 0 ? hc->hs->server_hostname : hc->hostname,
3671 hc->encodedurl );
3672 else
3673 (void) my_snprintf( url, sizeof(url),
3674 "%.200s", hc->encodedurl );
3675 /* Format the bytes. */
3676 if ( (long) hc->bytes_sent >= 0 )
3677 (void) my_snprintf( bytes, sizeof(bytes),
3678 "%ld", (long) hc->bytes_sent );
3679 else
3680 (void) strcpy( bytes, "-" );
3681
3682 /* Logfile or syslog? */
3683 if ( hc->hs->logfp != (FILE*) 0 )
3684 {
3685 time_t now;
3686 struct tm* t;
3687 const char* cernfmt_nozone = "%d/%b/%Y:%H:%M:%S";
3688 char date_nozone[100];
3689 int zone;
3690 char sign;
3691 char date[100];
3692
3693 /* Get the current time, if necessary. */
3694 if ( nowP != (struct timeval*) 0 )
3695 now = nowP->tv_sec;
3696 else
3697 now = time( (time_t*) 0 );
3698 /* Format the time, forcing a numeric timezone (some log analyzers
3699 ** are stoooopid about this).
3700 */
3701 t = localtime( &now );
3702 (void) strftime( date_nozone, sizeof(date_nozone), cernfmt_nozone, t );
3703 #ifdef HAVE_TM_GMTOFF
3704 zone = t->tm_gmtoff / 60L;
3705 #else
3706 zone = -timezone / 60L;
3707 /* Probably have to add something about daylight time here. */
3708 #endif
3709 if ( zone >= 0 )
3710 sign = '+';
3711 else
3712 {
3713 sign = '-';
3714 zone = -zone;
3715 }
3716 zone = ( zone / 60 ) * 100 + zone % 60;
3717 (void) my_snprintf( date, sizeof(date),
3718 "%s %c%04d", date_nozone, sign, zone );
3719 /* And write the log entry. */
3720 (void) fprintf( hc->hs->logfp,
3721 "%.80s - %.80s [%s] \"%.80s %.300s %.80s\" %d %s \"%.200s\" \"%.80s\"\n",
3722 httpd_ntoa( &hc->client_addr ), ru, date,
3723 httpd_method_str( hc->method ), url, hc->protocol,
3724 hc->status, bytes, hc->referer, hc->useragent );
3725 (void) fflush( hc->hs->logfp ); /* don't need to flush every time */
3726 }
3727 else
3728 syslog( LOG_INFO,
3729 "%.80s - %.80s \"%.80s %.200s %.80s\" %d %s \"%.200s\" \"%.80s\"",
3730 httpd_ntoa( &hc->client_addr ), ru,
3731 httpd_method_str( hc->method ), url, hc->protocol,
3732 hc->status, bytes, hc->referer, hc->useragent );
3733 }
3734
3735
3736 /* Returns 1 if ok to serve the url, 0 if not. */
3737 static int
3738 check_referer( httpd_conn* hc )
3739 {
3740 int r;
3741
3742 /* Are we doing referer checking at all? */
3743 if ( hc->hs->url_pattern == (char*) 0 )
3744 return 1;
3745
3746 r = really_check_referer( hc );
3747
3748 if ( ! r )
3749 {
3750 syslog(
3751 LOG_INFO, "%.80s non-local referer \"%.80s\" \"%.80s\"",
3752 httpd_ntoa( &hc->client_addr ), hc->encodedurl,
3753 hc->referer );
3754 httpd_send_err(
3755 hc, 403, err403title, "",
3756 ERROR_FORM( err403form, "You must supply a local referer to get URL '%.80s' from this server.\n" ),
3757 hc->encodedurl );
3758 }
3759 return r;
3760 }
3761
3762
3763 /* Returns 1 if ok to serve the url, 0 if not. */
3764 static int
3765 really_check_referer( httpd_conn* hc )
3766 {
3767 httpd_server* hs;
3768 char* cp1;
3769 char* cp2;
3770 char* cp3;
3771 static char* refhost = (char*) 0;
3772 static int refhost_size = 0;
3773 char *lp;
3774
3775 hs = hc->hs;
3776
3777 /* Check for an empty referer. */
3778 if ( hc->referer == (char*) 0 || hc->referer[0] == '\0' ||
3779 ( cp1 = strstr( hc->referer, "//" ) ) == (char*) 0 )
3780 {
3781 /* Disallow if we require a referer and the url matches. */
3782 if ( hs->no_empty_referers && match( hs->url_pattern, hc->decodedurl ) )
3783 return 0;
3784 /* Otherwise ok. */
3785 return 1;
3786 }
3787
3788 /* Extract referer host. */
3789 cp1 += 2;
3790 for ( cp2 = cp1; *cp2 != '/' && *cp2 != ':' && *cp2 != '\0'; ++cp2 )
3791 continue;
3792 httpd_realloc_str( &refhost, &refhost_size, cp2 - cp1 );
3793 for ( cp3 = refhost; cp1 < cp2; ++cp1, ++cp3 )
3794 if ( isupper(*cp1) )
3795 *cp3 = tolower(*cp1);
3796 else
3797 *cp3 = *cp1;
3798 *cp3 = '\0';
3799
3800 /* Local pattern? */
3801 if ( hs->local_pattern != (char*) 0 )
3802 lp = hs->local_pattern;
3803 else
3804 {
3805 /* No local pattern. What's our hostname? */
3806 if ( ! hs->vhost )
3807 {
3808 /* Not vhosting, use the server name. */
3809 lp = hs->server_hostname;
3810 if ( lp == (char*) 0 )
3811 /* Couldn't figure out local hostname - give up. */
3812 return 1;
3813 }
3814 else
3815 {
3816 /* We are vhosting, use the hostname on this connection. */
3817 lp = hc->hostname;
3818 if ( lp == (char*) 0 )
3819 /* Oops, no hostname. Maybe it's an old browser that
3820 ** doesn't send a Host: header. We could figure out
3821 ** the default hostname for this IP address, but it's
3822 ** not worth it for the few requests like this.
3823 */
3824 return 1;
3825 }
3826 }
3827
3828 /* If the referer host doesn't match the local host pattern, and
3829 ** the URL does match the url pattern, it's an illegal reference.
3830 */
3831 if ( ! match( lp, refhost ) && match( hs->url_pattern, hc->decodedurl ) )
3832 return 0;
3833 /* Otherwise ok. */
3834 return 1;
3835 }
3836
3837
3838 char*
3839 httpd_ntoa( httpd_sockaddr* saP )
3840 {
3841 #ifdef HAVE_GETNAMEINFO
3842 static char str[200];
3843
3844 if ( getnameinfo( &saP->sa, sockaddr_len( saP ), str, sizeof(str), 0, 0, NI_NUMERICHOST ) != 0 )
3845 {
3846 str[0] = '?';
3847 str[1] = '\0';
3848 }
3849 return str;
3850
3851 #else /* HAVE_GETNAMEINFO */
3852
3853 return inet_ntoa( saP->sa_in.sin_addr );
3854
3855 #endif /* HAVE_GETNAMEINFO */
3856 }
3857
3858
3859 static int
3860 sockaddr_check( httpd_sockaddr* saP )
3861 {
3862 switch ( saP->sa.sa_family )
3863 {
3864 case AF_INET: return 1;
3865 #if defined(AF_INET6) && defined(HAVE_SOCKADDR_IN6)
3866 case AF_INET6: return 1;
3867 #endif /* AF_INET6 && HAVE_SOCKADDR_IN6 */
3868 default:
3869 return 0;
3870 }
3871 }
3872
3873
3874 static size_t
3875 sockaddr_len( httpd_sockaddr* saP )
3876 {
3877 switch ( saP->sa.sa_family )
3878 {
3879 case AF_INET: return sizeof(struct sockaddr_in);
3880 #if defined(AF_INET6) && defined(HAVE_SOCKADDR_IN6)
3881 case AF_INET6: return sizeof(struct sockaddr_in6);
3882 #endif /* AF_INET6 && HAVE_SOCKADDR_IN6 */
3883 default:
3884 return 0; /* shouldn't happen */
3885 }
3886 }
3887
3888
3889 /* Some systems don't have snprintf(), so we make our own that uses
3890 ** either vsnprintf() or vsprintf(). If your system doesn't have
3891 ** vsnprintf(), it is probably vulnerable to buffer overruns.
3892 ** Upgrade!
3893 */
3894 static int
3895 my_snprintf( char* str, size_t size, const char* format, ... )
3896 {
3897 va_list ap;
3898 int r;
3899
3900 va_start( ap, format );
3901 #ifdef HAVE_VSNPRINTF
3902 r = vsnprintf( str, size, format, ap );
3903 #else /* HAVE_VSNPRINTF */
3904 r = vsprintf( str, format, ap );
3905 #endif /* HAVE_VSNPRINTF */
3906 va_end( ap );
3907 return r;
3908 }
3909
3910
3911 /* Generate debugging statistics syslog message. */
3912 void
3913 httpd_logstats( long secs )
3914 {
3915 syslog( LOG_NOTICE,
3916 " libhttpd - %d strings allocated, %ld bytes (%g bytes/str)",
3917 str_alloc_count, str_alloc_size,
3918 (float) str_alloc_size / str_alloc_count );
3919 }