-
Notifications
You must be signed in to change notification settings - Fork 6
/
libhttpd.c
4280 lines (3905 loc) · 113 KB
/
libhttpd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* libhttpd.c - HTTP protocol library
**
** Copyright © 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@mail.acme.com>.
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
** SUCH DAMAGE.
*/
#include "config.h"
#include "version.h"
#ifdef SHOW_SERVER_VERSION
#define EXPOSED_SERVER_SOFTWARE SERVER_SOFTWARE
#else /* SHOW_SERVER_VERSION */
#define EXPOSED_SERVER_SOFTWARE "thttpd"
#endif /* SHOW_SERVER_VERSION */
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#ifdef HAVE_MEMORY_H
#include <memory.h>
#endif /* HAVE_MEMORY_H */
#include <pwd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <stdarg.h>
#ifdef HAVE_OSRELDATE_H
#include <osreldate.h>
#endif /* HAVE_OSRELDATE_H */
#ifdef HAVE_DIRENT_H
# include <dirent.h>
# define NAMLEN(dirent) strlen((dirent)->d_name)
#else
# define dirent direct
# define NAMLEN(dirent) (dirent)->d_namlen
# ifdef HAVE_SYS_NDIR_H
# include <sys/ndir.h>
# endif
# ifdef HAVE_SYS_DIR_H
# include <sys/dir.h>
# endif
# ifdef HAVE_NDIR_H
# include <ndir.h>
# endif
#endif
#include "libhttpd.h"
#include "mmc.h"
#include "timers.h"
#include "match.h"
#include "tdate_parse.h"
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif
#ifndef SHUT_WR
#define SHUT_WR 1
#endif
#ifndef HAVE_INT64T
typedef long long int64_t;
#endif
#ifndef HAVE_SOCKLENT
typedef int socklen_t;
#endif
#ifdef __CYGWIN__
#define timezone _timezone
#endif
#ifndef MAX
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#endif
#ifndef MIN
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
/* Forwards. */
static void check_options( void );
static void free_httpd_server( httpd_server* hs );
static int initialize_listen_socket( httpd_sockaddr* saP );
static void add_response( httpd_conn* hc, char* str );
static void send_mime( httpd_conn* hc, int status, char* title, char* encodings, char* extraheads, char* type, off_t length, time_t mod );
static void send_response( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg );
static void send_response_tail( httpd_conn* hc );
static void defang( char* str, char* dfstr, int dfsize );
#ifdef ERR_DIR
static int send_err_file( httpd_conn* hc, int status, char* title, char* extraheads, char* filename );
#endif /* ERR_DIR */
#ifdef AUTH_FILE
static void send_authenticate( httpd_conn* hc, char* realm );
static int b64_decode( const char* str, unsigned char* space, int size );
static int auth_check( httpd_conn* hc, char* dirname );
static int auth_check2( httpd_conn* hc, char* dirname );
#endif /* AUTH_FILE */
static void send_dirredirect( httpd_conn* hc );
static int hexit( char c );
static void strdecode( char* to, char* from );
#ifdef GENERATE_INDEXES
static void strencode( char* to, int tosize, char* from );
#endif /* GENERATE_INDEXES */
#ifdef TILDE_MAP_1
static int tilde_map_1( httpd_conn* hc );
#endif /* TILDE_MAP_1 */
#ifdef TILDE_MAP_2
static int tilde_map_2( httpd_conn* hc );
#endif /* TILDE_MAP_2 */
static int vhost_map( httpd_conn* hc );
static char* expand_symlinks( char* path, char** restP, int no_symlink_check, int tildemapped );
static char* bufgets( httpd_conn* hc );
static void de_dotdot( char* file );
static void init_mime( void );
static void figure_mime( httpd_conn* hc );
#ifdef CGI_TIMELIMIT
static void cgi_kill2( ClientData client_data, struct timeval* nowP );
static void cgi_kill( ClientData client_data, struct timeval* nowP );
#endif /* CGI_TIMELIMIT */
#ifdef GENERATE_INDEXES
static int ls( httpd_conn* hc );
#endif /* GENERATE_INDEXES */
static char* build_env( char* fmt, char* arg );
#ifdef SERVER_NAME_LIST
static char* hostname_map( char* hostname );
#endif /* SERVER_NAME_LIST */
static char** make_envp( httpd_conn* hc );
static char** make_argp( httpd_conn* hc );
static void cgi_interpose_input( httpd_conn* hc, int wfd );
static void post_post_garbage_hack( httpd_conn* hc );
static void cgi_interpose_output( httpd_conn* hc, int rfd );
static void cgi_child( httpd_conn* hc );
static int cgi( httpd_conn* hc );
static int really_start_request( httpd_conn* hc, struct timeval* nowP );
static void make_log_entry( httpd_conn* hc, struct timeval* nowP );
static int check_referrer( httpd_conn* hc );
static int really_check_referrer( httpd_conn* hc );
static int sockaddr_check( httpd_sockaddr* saP );
static size_t sockaddr_len( httpd_sockaddr* saP );
static int my_snprintf( char* str, size_t size, const char* format, ... );
#ifndef HAVE_ATOLL
static long long atoll( const char* str );
#endif /* HAVE_ATOLL */
/* This global keeps track of whether we are in the main process or a
** sub-process. The reason is that httpd_write_response() can get called
** in either context; when it is called from the main process it must use
** non-blocking I/O to avoid stalling the server, but when it is called
** from a sub-process it wants to use blocking I/O so that the whole
** response definitely gets written. So, it checks this variable. A bit
** of a hack but it seems to do the right thing.
*/
static int sub_process = 0;
static void
check_options( void )
{
#if defined(TILDE_MAP_1) && defined(TILDE_MAP_2)
syslog( LOG_CRIT, "both TILDE_MAP_1 and TILDE_MAP_2 are defined" );
exit( 1 );
#endif /* both */
}
static void
free_httpd_server( httpd_server* hs )
{
if ( hs->binding_hostname != (char*) 0 )
free( (void*) hs->binding_hostname );
if ( hs->cwd != (char*) 0 )
free( (void*) hs->cwd );
if ( hs->cgi_pattern != (char*) 0 )
free( (void*) hs->cgi_pattern );
if ( hs->charset != (char*) 0 )
free( (void*) hs->charset );
if ( hs->p3p != (char*) 0 )
free( (void*) hs->p3p );
if ( hs->url_pattern != (char*) 0 )
free( (void*) hs->url_pattern );
if ( hs->local_pattern != (char*) 0 )
free( (void*) hs->local_pattern );
free( (void*) hs );
}
httpd_server*
httpd_initialize(
char* hostname, httpd_sockaddr* sa4P, httpd_sockaddr* sa6P,
unsigned short port, char* cgi_pattern, int cgi_limit, char* charset,
char* p3p, int max_age, char* cwd, int no_log, FILE* logfp,
int no_symlink_check, int vhost, int global_passwd, char* url_pattern,
char* local_pattern, int no_empty_referrers )
{
httpd_server* hs;
static char ghnbuf[256];
char* cp;
check_options();
hs = NEW( httpd_server, 1 );
if ( hs == (httpd_server*) 0 )
{
syslog( LOG_CRIT, "out of memory allocating an httpd_server" );
return (httpd_server*) 0;
}
if ( hostname != (char*) 0 )
{
hs->binding_hostname = strdup( hostname );
if ( hs->binding_hostname == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying hostname" );
return (httpd_server*) 0;
}
hs->server_hostname = hs->binding_hostname;
}
else
{
hs->binding_hostname = (char*) 0;
hs->server_hostname = (char*) 0;
if ( gethostname( ghnbuf, sizeof(ghnbuf) ) < 0 )
ghnbuf[0] = '\0';
#ifdef SERVER_NAME_LIST
if ( ghnbuf[0] != '\0' )
hs->server_hostname = hostname_map( ghnbuf );
#endif /* SERVER_NAME_LIST */
if ( hs->server_hostname == (char*) 0 )
{
#ifdef SERVER_NAME
hs->server_hostname = SERVER_NAME;
#else /* SERVER_NAME */
if ( ghnbuf[0] != '\0' )
hs->server_hostname = ghnbuf;
#endif /* SERVER_NAME */
}
}
hs->port = port;
if ( cgi_pattern == (char*) 0 )
hs->cgi_pattern = (char*) 0;
else
{
/* Nuke any leading slashes. */
if ( cgi_pattern[0] == '/' )
++cgi_pattern;
hs->cgi_pattern = strdup( cgi_pattern );
if ( hs->cgi_pattern == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying cgi_pattern" );
return (httpd_server*) 0;
}
/* Nuke any leading slashes in the cgi pattern. */
while ( ( cp = strstr( hs->cgi_pattern, "|/" ) ) != (char*) 0 )
(void) strcpy( cp + 1, cp + 2 );
}
hs->cgi_limit = cgi_limit;
hs->cgi_count = 0;
hs->charset = strdup( charset );
hs->p3p = strdup( p3p );
hs->max_age = max_age;
hs->cwd = strdup( cwd );
if ( hs->cwd == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying cwd" );
return (httpd_server*) 0;
}
if ( url_pattern == (char*) 0 )
hs->url_pattern = (char*) 0;
else
{
hs->url_pattern = strdup( url_pattern );
if ( hs->url_pattern == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying url_pattern" );
return (httpd_server*) 0;
}
}
if ( local_pattern == (char*) 0 )
hs->local_pattern = (char*) 0;
else
{
hs->local_pattern = strdup( local_pattern );
if ( hs->local_pattern == (char*) 0 )
{
syslog( LOG_CRIT, "out of memory copying local_pattern" );
return (httpd_server*) 0;
}
}
hs->no_log = no_log;
hs->logfp = (FILE*) 0;
httpd_set_logfp( hs, logfp );
hs->no_symlink_check = no_symlink_check;
hs->vhost = vhost;
hs->global_passwd = global_passwd;
hs->no_empty_referrers = no_empty_referrers;
/* Initialize listen sockets. Try v6 first because of a Linux peculiarity;
** like some other systems, it has magical v6 sockets that also listen for
** v4, but in Linux if you bind a v4 socket first then the v6 bind fails.
*/
if ( sa6P == (httpd_sockaddr*) 0 )
hs->listen6_fd = -1;
else
hs->listen6_fd = initialize_listen_socket( sa6P );
if ( sa4P == (httpd_sockaddr*) 0 )
hs->listen4_fd = -1;
else
hs->listen4_fd = initialize_listen_socket( sa4P );
/* If we didn't get any valid sockets, fail. */
if ( hs->listen4_fd == -1 && hs->listen6_fd == -1 )
{
free_httpd_server( hs );
return (httpd_server*) 0;
}
init_mime();
/* Done initializing. */
if ( hs->binding_hostname == (char*) 0 )
syslog(
LOG_NOTICE, "%.80s starting on port %d", SERVER_SOFTWARE,
(int) hs->port );
else
syslog(
LOG_NOTICE, "%.80s starting on %.80s, port %d", SERVER_SOFTWARE,
httpd_ntoa( hs->listen4_fd != -1 ? sa4P : sa6P ),
(int) hs->port );
return hs;
}
static int
initialize_listen_socket( httpd_sockaddr* saP )
{
int listen_fd;
int on, flags;
/* Check sockaddr. */
if ( ! sockaddr_check( saP ) )
{
syslog( LOG_CRIT, "unknown sockaddr family on listen socket" );
return -1;
}
/* Create socket. */
listen_fd = socket( saP->sa.sa_family, SOCK_STREAM, 0 );
if ( listen_fd < 0 )
{
syslog( LOG_CRIT, "socket %.80s - %m", httpd_ntoa( saP ) );
return -1;
}
(void) fcntl( listen_fd, F_SETFD, 1 );
/* Allow reuse of local addresses. */
on = 1;
if ( setsockopt(
listen_fd, SOL_SOCKET, SO_REUSEADDR, (char*) &on,
sizeof(on) ) < 0 )
syslog( LOG_CRIT, "setsockopt SO_REUSEADDR - %m" );
/* Bind to it. */
if ( bind( listen_fd, &saP->sa, sockaddr_len( saP ) ) < 0 )
{
syslog(
LOG_CRIT, "bind %.80s - %m", httpd_ntoa( saP ) );
(void) close( listen_fd );
return -1;
}
/* Set the listen file descriptor to no-delay / non-blocking mode. */
flags = fcntl( listen_fd, F_GETFL, 0 );
if ( flags == -1 )
{
syslog( LOG_CRIT, "fcntl F_GETFL - %m" );
(void) close( listen_fd );
return -1;
}
if ( fcntl( listen_fd, F_SETFL, flags | O_NDELAY ) < 0 )
{
syslog( LOG_CRIT, "fcntl O_NDELAY - %m" );
(void) close( listen_fd );
return -1;
}
/* Start a listen going. */
if ( listen( listen_fd, LISTEN_BACKLOG ) < 0 )
{
syslog( LOG_CRIT, "listen - %m" );
(void) close( listen_fd );
return -1;
}
/* Use accept filtering, if available. */
#ifdef SO_ACCEPTFILTER
{
#if ( __FreeBSD_version >= 411000 )
#define ACCEPT_FILTER_NAME "httpready"
#else
#define ACCEPT_FILTER_NAME "dataready"
#endif
struct accept_filter_arg af;
(void) bzero( &af, sizeof(af) );
(void) strcpy( af.af_name, ACCEPT_FILTER_NAME );
(void) setsockopt(
listen_fd, SOL_SOCKET, SO_ACCEPTFILTER, (char*) &af, sizeof(af) );
}
#endif /* SO_ACCEPTFILTER */
return listen_fd;
}
void
httpd_set_logfp( httpd_server* hs, FILE* logfp )
{
if ( hs->logfp != (FILE*) 0 )
(void) fclose( hs->logfp );
hs->logfp = logfp;
}
void
httpd_terminate( httpd_server* hs )
{
httpd_unlisten( hs );
if ( hs->logfp != (FILE*) 0 )
(void) fclose( hs->logfp );
free_httpd_server( hs );
}
void
httpd_unlisten( httpd_server* hs )
{
if ( hs->listen4_fd != -1 )
{
(void) close( hs->listen4_fd );
hs->listen4_fd = -1;
}
if ( hs->listen6_fd != -1 )
{
(void) close( hs->listen6_fd );
hs->listen6_fd = -1;
}
}
/* Conditional macro to allow two alternate forms for use in the built-in
** error pages. If EXPLICIT_ERROR_PAGES is defined, the second and more
** explicit error form is used; otherwise, the first and more generic
** form is used.
*/
#ifdef EXPLICIT_ERROR_PAGES
#define ERROR_FORM(a,b) b
#else /* EXPLICIT_ERROR_PAGES */
#define ERROR_FORM(a,b) a
#endif /* EXPLICIT_ERROR_PAGES */
static char* ok200title = "OK";
static char* ok206title = "Partial Content";
static char* err302title = "Found";
static char* err302form = "The actual URL is '%.80s'.\n";
static char* err304title = "Not Modified";
char* httpd_err400title = "Bad Request";
char* httpd_err400form =
"Your request has bad syntax or is inherently impossible to satisfy.\n";
#ifdef AUTH_FILE
static char* err401title = "Unauthorized";
static char* err401form =
"Authorization required for the URL '%.80s'.\n";
#endif /* AUTH_FILE */
static char* err403title = "Forbidden";
#ifndef EXPLICIT_ERROR_PAGES
static char* err403form =
"You do not have permission to get URL '%.80s' from this server.\n";
#endif /* !EXPLICIT_ERROR_PAGES */
static char* err404title = "Not Found";
static char* err404form =
"The requested URL '%.80s' was not found on this server.\n";
char* httpd_err408title = "Request Timeout";
char* httpd_err408form =
"No request appeared within a reasonable time period.\n";
static char* err451title = "Unavailable For Legal Reasons";
static char* err451form =
"You do not have legal permission to get URL '%.80s' from this server.\n";
static char* err500title = "Internal Error";
static char* err500form =
"There was an unusual problem serving the requested URL '%.80s'.\n";
static char* err501title = "Not Implemented";
static char* err501form =
"The requested method '%.80s' is not implemented by this server.\n";
char* httpd_err503title = "Service Temporarily Overloaded";
char* httpd_err503form =
"The requested URL '%.80s' is temporarily overloaded. Please try again later.\n";
/* Append a string to the buffer waiting to be sent as response. */
static void
add_response( httpd_conn* hc, char* str )
{
size_t len;
len = strlen( str );
httpd_realloc_str( &hc->response, &hc->maxresponse, hc->responselen + len );
(void) memmove( &(hc->response[hc->responselen]), str, len );
hc->responselen += len;
}
/* Send the buffered response. */
void
httpd_write_response( httpd_conn* hc )
{
/* If we are in a sub-process, turn off no-delay mode. */
if ( sub_process )
httpd_clear_ndelay( hc->conn_fd );
/* Send the response, if necessary. */
if ( hc->responselen > 0 )
{
(void) httpd_write_fully( hc->conn_fd, hc->response, hc->responselen );
hc->responselen = 0;
}
}
/* Set no-delay / non-blocking mode on a socket. */
void
httpd_set_ndelay( int fd )
{
int flags, newflags;
flags = fcntl( fd, F_GETFL, 0 );
if ( flags != -1 )
{
newflags = flags | (int) O_NDELAY;
if ( newflags != flags )
(void) fcntl( fd, F_SETFL, newflags );
}
}
/* Clear no-delay / non-blocking mode on a socket. */
void
httpd_clear_ndelay( int fd )
{
int flags, newflags;
flags = fcntl( fd, F_GETFL, 0 );
if ( flags != -1 )
{
newflags = flags & ~ (int) O_NDELAY;
if ( newflags != flags )
(void) fcntl( fd, F_SETFL, newflags );
}
}
static void
send_mime( httpd_conn* hc, int status, char* title, char* encodings, char* extraheads, char* type, off_t length, time_t mod )
{
time_t now, expires;
const char* rfc1123fmt = "%a, %d %b %Y %H:%M:%S GMT";
char nowbuf[100];
char modbuf[100];
char expbuf[100];
char fixed_type[500];
char buf[1000];
int partial_content;
int s100;
hc->status = status;
hc->bytes_to_send = length;
if ( hc->mime_flag )
{
if ( status == 200 && hc->got_range &&
( hc->last_byte_index >= hc->first_byte_index ) &&
( ( hc->last_byte_index != length - 1 ) ||
( hc->first_byte_index != 0 ) ) &&
( hc->range_if == (time_t) -1 ||
hc->range_if == hc->sb.st_mtime ) )
{
partial_content = 1;
hc->status = status = 206;
title = ok206title;
}
else
{
partial_content = 0;
hc->got_range = 0;
}
now = time( (time_t*) 0 );
if ( mod == (time_t) 0 )
mod = now;
(void) strftime( nowbuf, sizeof(nowbuf), rfc1123fmt, gmtime( &now ) );
(void) strftime( modbuf, sizeof(modbuf), rfc1123fmt, gmtime( &mod ) );
(void) my_snprintf(
fixed_type, sizeof(fixed_type), type, hc->hs->charset );
(void) my_snprintf( buf, sizeof(buf),
"%.20s %d %s\015\012Server: %s\015\012Content-Type: %s\015\012Date: %s\015\012Last-Modified: %s\015\012Accept-Ranges: bytes\015\012Connection: close\015\012",
hc->protocol, status, title, EXPOSED_SERVER_SOFTWARE, fixed_type,
nowbuf, modbuf );
add_response( hc, buf );
s100 = status / 100;
if ( s100 != 2 && s100 != 3 )
{
(void) my_snprintf( buf, sizeof(buf),
"Cache-Control: no-cache,no-store\015\012" );
add_response( hc, buf );
}
if ( encodings[0] != '\0' )
{
(void) my_snprintf( buf, sizeof(buf),
"Content-Encoding: %s\015\012", encodings );
add_response( hc, buf );
}
if ( partial_content )
{
(void) my_snprintf( buf, sizeof(buf),
"Content-Range: bytes %lld-%lld/%lld\015\012Content-Length: %lld\015\012",
(long long) hc->first_byte_index,
(long long) hc->last_byte_index,
(long long) length,
(long long) ( hc->last_byte_index - hc->first_byte_index + 1 ) );
add_response( hc, buf );
}
else if ( length >= 0 )
{
(void) my_snprintf( buf, sizeof(buf),
"Content-Length: %lld\015\012", (long long) length );
add_response( hc, buf );
}
if ( hc->hs->p3p[0] != '\0' )
{
(void) my_snprintf( buf, sizeof(buf), "P3P: %s\015\012", hc->hs->p3p );
add_response( hc, buf );
}
if ( hc->hs->max_age >= 0 )
{
expires = now + hc->hs->max_age;
(void) strftime(
expbuf, sizeof(expbuf), rfc1123fmt, gmtime( &expires ) );
(void) my_snprintf( buf, sizeof(buf),
"Cache-Control: max-age=%d\015\012Expires: %s\015\012",
hc->hs->max_age, expbuf );
add_response( hc, buf );
}
if ( extraheads[0] != '\0' )
add_response( hc, extraheads );
add_response( hc, "\015\012" );
}
}
static int str_alloc_count = 0;
static size_t str_alloc_size = 0;
void
httpd_realloc_str( char** strP, size_t* maxsizeP, size_t size )
{
if ( *maxsizeP == 0 )
{
*maxsizeP = MAX( 200, size + 100 );
*strP = NEW( char, *maxsizeP + 1 );
++str_alloc_count;
str_alloc_size += *maxsizeP;
}
else if ( size > *maxsizeP )
{
str_alloc_size -= *maxsizeP;
*maxsizeP = MAX( *maxsizeP * 2, size * 5 / 4 );
*strP = RENEW( *strP, char, *maxsizeP + 1 );
str_alloc_size += *maxsizeP;
}
else
return;
if ( *strP == (char*) 0 )
{
syslog(
LOG_ERR, "out of memory reallocating a string to %ld bytes",
(long) *maxsizeP );
exit( 1 );
}
}
static void
send_response( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg )
{
char defanged_arg[1000], buf[2000];
send_mime(
hc, status, title, "", extraheads, "text/html; charset=%s", (off_t) -1,
(time_t) 0 );
(void) my_snprintf( buf, sizeof(buf), "\
<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n\
\n\
<html>\n\
\n\
<head>\n\
<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\">\n\
<title>%d %s</title>\n\
</head>\n\
\n\
<body bgcolor=\"#cc9999\" text=\"#000000\" link=\"#2020ff\" vlink=\"#4040cc\">\n\
\n\
<h2>%d %s</h2>\n",
status, title, status, title );
add_response( hc, buf );
defang( arg, defanged_arg, sizeof(defanged_arg) );
(void) my_snprintf( buf, sizeof(buf), form, defanged_arg );
add_response( hc, buf );
if ( match( "**MSIE**", hc->useragent ) )
{
int n;
add_response( hc, "<!--\n" );
for ( n = 0; n < 6; ++n )
add_response( hc, "Padding so that MSIE deigns to show this error instead of its own canned one.\n");
add_response( hc, "-->\n" );
}
send_response_tail( hc );
}
static void
send_response_tail( httpd_conn* hc )
{
char buf[1000];
(void) my_snprintf( buf, sizeof(buf), "\
<hr>\n\
\n\
<address><a href=\"%s\">%s</a></address>\n\
\n\
</body>\n\
\n\
</html>\n",
SERVER_ADDRESS, EXPOSED_SERVER_SOFTWARE );
add_response( hc, buf );
}
static void
defang( char* str, char* dfstr, int dfsize )
{
char* cp1;
char* cp2;
for ( cp1 = str, cp2 = dfstr;
*cp1 != '\0' && cp2 - dfstr < dfsize - 5;
++cp1, ++cp2 )
{
switch ( *cp1 )
{
case '<':
*cp2++ = '&';
*cp2++ = 'l';
*cp2++ = 't';
*cp2 = ';';
break;
case '>':
*cp2++ = '&';
*cp2++ = 'g';
*cp2++ = 't';
*cp2 = ';';
break;
default:
*cp2 = *cp1;
break;
}
}
*cp2 = '\0';
}
void
httpd_send_err( httpd_conn* hc, int status, char* title, char* extraheads, char* form, char* arg )
{
#ifdef ERR_DIR
char filename[1000];
/* Try virtual host error page. */
if ( hc->hs->vhost && hc->hostdir[0] != '\0' )
{
(void) my_snprintf( filename, sizeof(filename),
"%s/%s/err%d.html", hc->hostdir, ERR_DIR, status );
if ( send_err_file( hc, status, title, extraheads, filename ) )
return;
}
/* Try server-wide error page. */
(void) my_snprintf( filename, sizeof(filename),
"%s/err%d.html", ERR_DIR, status );
if ( send_err_file( hc, status, title, extraheads, filename ) )
return;
/* Fall back on built-in error page. */
send_response( hc, status, title, extraheads, form, arg );
#else /* ERR_DIR */
send_response( hc, status, title, extraheads, form, arg );
#endif /* ERR_DIR */
}
#ifdef ERR_DIR
static int
send_err_file( httpd_conn* hc, int status, char* title, char* extraheads, char* filename )
{
FILE* fp;
char buf[1000];
size_t r;
fp = fopen( filename, "r" );
if ( fp == (FILE*) 0 )
return 0;
send_mime(
hc, status, title, "", extraheads, "text/html; charset=%s", (off_t) -1,
(time_t) 0 );
for (;;)
{
r = fread( buf, 1, sizeof(buf) - 1, fp );
if ( r == 0 )
break;
buf[r] = '\0';
add_response( hc, buf );
}
(void) fclose( fp );
#ifdef ERR_APPEND_SERVER_INFO
send_response_tail( hc );
#endif /* ERR_APPEND_SERVER_INFO */
return 1;
}
#endif /* ERR_DIR */
#ifdef AUTH_FILE
static void
send_authenticate( httpd_conn* hc, char* realm )
{
static char* header;
static size_t maxheader = 0;
static char headstr[] = "WWW-Authenticate: Basic realm=\"";
httpd_realloc_str(
&header, &maxheader, sizeof(headstr) + strlen( realm ) + 3 );
(void) my_snprintf( header, maxheader, "%s%s\"\015\012", headstr, realm );
httpd_send_err( hc, 401, err401title, header, err401form, hc->encodedurl );
/* If the request was a POST then there might still be data to be read,
** so we need to do a lingering close.
*/
if ( hc->method == METHOD_POST )
hc->should_linger = 1;
}
/* Base-64 decoding. This represents binary data as printable ASCII
** characters. Three 8-bit binary bytes are turned into four 6-bit
** values, like so:
**
** [11111111] [22222222] [33333333]
**
** [111111] [112222] [222233] [333333]
**
** Then the 6-bit values are represented using the characters "A-Za-z0-9+/".
*/
static int b64_decode_table[256] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 00-0F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 10-1F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, /* 20-2F */
52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, /* 30-3F */
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, /* 40-4F */
15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, /* 50-5F */
-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, /* 60-6F */
41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1, /* 70-7F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 80-8F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* 90-9F */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* A0-AF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* B0-BF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* C0-CF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* D0-DF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, /* E0-EF */
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 /* F0-FF */
};
/* Do base-64 decoding on a string. Ignore any non-base64 bytes.
** Return the actual number of bytes generated. The decoded size will
** be at most 3/4 the size of the encoded, and may be smaller if there
** are padding characters (blanks, newlines).
*/
static int
b64_decode( const char* str, unsigned char* space, int size )
{
const char* cp;
int space_idx, phase;
int d, prev_d = 0;
unsigned char c;
space_idx = 0;
phase = 0;
for ( cp = str; *cp != '\0'; ++cp )
{
d = b64_decode_table[(int) ((unsigned char) *cp)];
if ( d != -1 )
{
switch ( phase )
{
case 0:
++phase;
break;
case 1:
c = ( ( prev_d << 2 ) | ( ( d & 0x30 ) >> 4 ) );
if ( space_idx < size )
space[space_idx++] = c;
++phase;
break;
case 2:
c = ( ( ( prev_d & 0xf ) << 4 ) | ( ( d & 0x3c ) >> 2 ) );
if ( space_idx < size )
space[space_idx++] = c;
++phase;
break;
case 3:
c = ( ( ( prev_d & 0x03 ) << 6 ) | d );
if ( space_idx < size )
space[space_idx++] = c;
phase = 0;
break;
}
prev_d = d;
}
}
return space_idx;
}
/* Returns -1 == unauthorized, 0 == no auth file, 1 = authorized. */
static int
auth_check( httpd_conn* hc, char* dirname )
{
if ( hc->hs->global_passwd )