ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/thttpd/libhttpd.c
Revision: 1.1.4.1
Committed: Mon Jun 18 21:21:43 2001 UTC (23 years ago) by root
Content type: text/plain
Branch: connpatch
Changes since 1.1: +31 -0 lines
Log Message:
*** empty log message ***

File Contents

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