ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/thttpd/libhttpd.c
Revision: 1.1.4.4
Committed: Mon Jul 2 18:50:02 2001 UTC (23 years ago) by root
Content type: text/plain
Branch: connpatch
Changes since 1.1.4.3: +4 -0 lines
Log Message:
*** empty log message ***

File Contents

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