ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/thttpd/libhttpd.c
Revision: 1.1.6.2
Committed: Mon Jun 25 02:23:00 2001 UTC (23 years ago) by root
Content type: text/plain
Branch: mmapppatch
Changes since 1.1.6.1: +26 -3 lines
Log Message:
*** empty log message ***

File Contents

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