ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/thttpd/libhttpd.c
Revision: 1.1.2.2
Committed: Sat Jun 30 00:36:31 2001 UTC (25 years, 3 months ago) by root
Content type: text/plain
Branch: dirpatch
CVS Tags: dp_j
Changes since 1.1.2.1: +1 -1 lines
Log Message:
*** empty log message ***

File Contents

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