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