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