-
Notifications
You must be signed in to change notification settings - Fork 2
/
thttpd.c
966 lines (858 loc) · 24.5 KB
/
thttpd.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
// This software has been changed to serve as a simple httpd
// for use with pprof and google-perftools. It is not the original thttpd.c.
// See README for details.
/* thttpd.c - tiny/turbo/throttling HTTP server
**
** Copyright � 1995,1998,1999,2000,2001 by Jef Poskanzer <[email protected]>.
** 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"
#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/uio.h>
#include <pthread.h>
#include <errno.h>
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <pwd.h>
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef TIME_WITH_SYS_TIME
#include <time.h>
#endif
#include <unistd.h>
#include "fdwatch.h"
#include "libhttpd.h"
#include "timers.h"
#ifndef SHUT_WR
#define SHUT_WR 1
#endif
#ifndef HAVE_INT64T
typedef long long int64_t;
#endif
static char* argv0;
static int debug;
static unsigned short port;
static char* dir;
static char* data_dir;
static int do_chroot, no_log, no_symlink_check, do_vhost, do_global_passwd;
static char* cgi_pattern;
static int cgi_limit;
static char* url_pattern;
static int no_empty_referers;
static char* local_pattern;
static char* logfile;
static char* throttlefile;
static char* hostname;
static char* pidfile;
static char* user;
static char* charset = "utf-8";
static char* p3p = "";
static int max_age;
typedef struct {
int conn_state;
int next_free_connect;
httpd_conn* hc;
long max_limit, min_limit;
time_t started_at, active_at;
Timer* wakeup_timer;
Timer* linger_timer;
long wouldblock_delay;
off_t bytes;
off_t end_byte_index;
off_t next_byte_index;
} connecttab;
static connecttab* connects;
static int num_connects, max_connects, first_free_connect;
static int httpd_conn_count;
/* The connection states. */
#define CNST_FREE 0
#define CNST_READING 1
#define CNST_SENDING 2
#define CNST_PAUSING 3
#define CNST_LINGERING 4
#define CNST_SLEEPING 5
static httpd_server* hs = (httpd_server*) 0;
int terminate = 0;
time_t start_time, stats_time;
long stats_connections;
off_t stats_bytes;
int stats_simultaneous;
/* Forwards. */
static void lookup_hostname( httpd_sockaddr* sa4P, size_t sa4_len, int* gotv4P, httpd_sockaddr* sa6P, size_t sa6_len, int* gotv6P );
static void shut_down( void );
static int handle_newconnect( struct timeval* tvP, int listen_fd );
static void handle_read( connecttab* c, struct timeval* tvP );
static void handle_send( connecttab* c, struct timeval* tvP );
static void handle_linger( connecttab* c, struct timeval* tvP );
static void finish_connection( connecttab* c, struct timeval* tvP );
static void clear_connection( connecttab* c, struct timeval* tvP );
static void really_clear_connection( connecttab* c, struct timeval* tvP );
static void idle( ClientData client_data, struct timeval* nowP );
static void wakeup_connection( ClientData client_data, struct timeval* nowP );
static void linger_clear_connection( ClientData client_data, struct timeval* nowP );
static void occasional( ClientData client_data, struct timeval* nowP );
int
thttpd_run(void)
{
char* cp;
struct passwd* pwd;
uid_t uid = 32767;
gid_t gid = 32767;
int num_ready;
int cnum;
connecttab* c;
httpd_conn* hc;
httpd_sockaddr sa4;
httpd_sockaddr sa6;
int gotv4, gotv6;
struct timeval tv;
cp = getenv( "GHTTPPORT" );
if ( cp )
port = atoi( cp );
if( port == 0 )
port = 9999;
/* Read zone info now, in case we chroot(). */
tzset();
/* Look up hostname now, in case we chroot(). */
lookup_hostname( &sa4, sizeof(sa4), &gotv4, &sa6, sizeof(sa6), &gotv6 );
if ( ! ( gotv4 || gotv6 ) )
{
memset(&sa4, 0, sizeof sa4);
gotv4 = 1;
}
/* Initialize the fdwatch package. Have to do this before chroot,
** if /dev/poll is used.
*/
max_connects = fdwatch_get_nfiles();
if ( max_connects < 0 )
{
return;
}
max_connects -= SPARE_FDS;
/* Set up to catch signals. */
#ifdef HAVE_SIGSET
(void) sigset( SIGPIPE, SIG_IGN ); /* get EPIPE instead */
#else /* HAVE_SIGSET */
(void) signal( SIGPIPE, SIG_IGN ); /* get EPIPE instead */
#endif /* HAVE_SIGSET */
/* Initialize the timer package. */
tmr_init();
/* Initialize the HTTP layer. Got to do this before giving up root,
** so that we can bind to a privileged port.
*/
hs = httpd_initialize(
hostname,
gotv4 ? &sa4 : (httpd_sockaddr*) 0, gotv6 ? &sa6 : (httpd_sockaddr*) 0,
port, cgi_pattern, cgi_limit, charset, p3p, max_age, "/", no_log,
no_symlink_check, do_vhost, do_global_passwd, url_pattern,
local_pattern, no_empty_referers );
if ( hs == (httpd_server*) 0 )
{
return;
}
/* Set up the occasional timer. */
if ( tmr_create( (struct timeval*) 0, occasional, JunkClientData, OCCASIONAL_TIME * 1000L, 1 ) == (Timer*) 0 )
{
return;
}
/* Set up the idle timer. */
if ( tmr_create( (struct timeval*) 0, idle, JunkClientData, 5 * 1000L, 1 ) == (Timer*) 0 )
{
return;
}
start_time = stats_time = time( (time_t*) 0 );
stats_connections = 0;
stats_bytes = 0;
stats_simultaneous = 0;
/* Initialize our connections table. */
connects = NEW( connecttab, max_connects );
if ( connects == (connecttab*) 0 )
{
return;
}
for ( cnum = 0; cnum < max_connects; ++cnum )
{
connects[cnum].conn_state = CNST_FREE;
connects[cnum].next_free_connect = cnum + 1;
connects[cnum].hc = (httpd_conn*) 0;
}
connects[max_connects - 1].next_free_connect = -1; /* end of link list */
first_free_connect = 0;
num_connects = 0;
httpd_conn_count = 0;
if ( hs != (httpd_server*) 0 )
{
if ( hs->listen4_fd != -1 )
fdwatch_add_fd( hs->listen4_fd, (void*) 0, FDW_READ );
if ( hs->listen6_fd != -1 )
fdwatch_add_fd( hs->listen6_fd, (void*) 0, FDW_READ );
}
/* Main loop. */
(void) gettimeofday( &tv, (struct timezone*) 0 );
while ( ( ! terminate ) || num_connects > 0 )
{
/* Do the fd watch. */
num_ready = fdwatch( tmr_mstimeout( &tv ) );
if ( num_ready < 0 )
{
if ( errno == EINTR || errno == EAGAIN )
continue; /* try again */
return;
}
(void) gettimeofday( &tv, (struct timezone*) 0 );
if ( num_ready == 0 )
{
/* No fd's are ready - run the timers. */
tmr_run( &tv );
continue;
}
/* Is it a new connection? */
if ( hs != (httpd_server*) 0 && hs->listen6_fd != -1 &&
fdwatch_check_fd( hs->listen6_fd ) )
{
if ( handle_newconnect( &tv, hs->listen6_fd ) )
/* Go around the loop and do another fdwatch, rather than
** dropping through and processing existing connections.
** New connections always get priority.
*/
continue;
}
if ( hs != (httpd_server*) 0 && hs->listen4_fd != -1 &&
fdwatch_check_fd( hs->listen4_fd ) )
{
if ( handle_newconnect( &tv, hs->listen4_fd ) )
/* Go around the loop and do another fdwatch, rather than
** dropping through and processing existing connections.
** New connections always get priority.
*/
continue;
}
/* Find the connections that need servicing. */
while ( ( c = (connecttab*) fdwatch_get_next_client_data() ) != (connecttab*) -1 )
{
if ( c == (connecttab*) 0 )
continue;
hc = c->hc;
if ( ! fdwatch_check_fd( hc->conn_fd ) )
/* Something went wrong. */
clear_connection( c, &tv );
else
switch ( c->conn_state )
{
case CNST_READING: handle_read( c, &tv ); break;
case CNST_SENDING: handle_send( c, &tv ); break;
case CNST_LINGERING: handle_linger( c, &tv ); break;
}
}
tmr_run( &tv );
}
/* The main loop terminated. */
shut_down();
return 0;
}
void
ghttpd( void )
{
pthread_t id;
pthread_create(&id, 0, (void*(*)(void*))thttpd_run, 0);
}
static void
lookup_hostname( httpd_sockaddr* sa4P, size_t sa4_len, int* gotv4P, httpd_sockaddr* sa6P, size_t sa6_len, int* gotv6P )
{
#ifdef USE_IPV6
struct addrinfo hints;
char portstr[10];
int gaierr;
struct addrinfo* ai;
struct addrinfo* ai2;
struct addrinfo* aiv6;
struct addrinfo* aiv4;
*gotv4P = 0;
*gotv6P = 0;
(void) memset( &hints, 0, sizeof(hints) );
hints.ai_family = PF_UNSPEC;
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = SOCK_STREAM;
(void) snprintf( portstr, sizeof(portstr), "%d", (int) port );
if ( (gaierr = getaddrinfo( hostname, portstr, &hints, &ai )) != 0 )
{
return;
}
/* Find the first IPv6 and IPv4 entries. */
aiv6 = (struct addrinfo*) 0;
aiv4 = (struct addrinfo*) 0;
for ( ai2 = ai; ai2 != (struct addrinfo*) 0; ai2 = ai2->ai_next )
{
switch ( ai2->ai_family )
{
case AF_INET6:
if ( aiv6 == (struct addrinfo*) 0 )
aiv6 = ai2;
break;
case AF_INET:
if ( aiv4 == (struct addrinfo*) 0 )
aiv4 = ai2;
break;
}
}
if ( aiv6 == (struct addrinfo*) 0 )
*gotv6P = 0;
else
{
if ( sa6_len < aiv6->ai_addrlen )
{
return;
}
(void) memset( sa6P, 0, sa6_len );
(void) memmove( sa6P, aiv6->ai_addr, aiv6->ai_addrlen );
*gotv6P = 1;
}
if ( aiv4 == (struct addrinfo*) 0 )
*gotv4P = 0;
else
{
if ( sa4_len < aiv4->ai_addrlen )
{
return;
}
(void) memset( sa4P, 0, sa4_len );
(void) memmove( sa4P, aiv4->ai_addr, aiv4->ai_addrlen );
*gotv4P = 1;
}
freeaddrinfo( ai );
#else /* USE_IPV6 */
struct hostent* he;
*gotv6P = 0;
(void) memset( sa4P, 0, sa4_len );
sa4P->sa.sa_family = AF_INET;
if ( hostname == (char*) 0 )
sa4P->sa_in.sin_addr.s_addr = htonl( INADDR_ANY );
else
{
sa4P->sa_in.sin_addr.s_addr = inet_addr( hostname );
if ( (int) sa4P->sa_in.sin_addr.s_addr == -1 )
{
he = gethostbyname( hostname );
if ( he == (struct hostent*) 0 )
{
return;
}
if ( he->h_addrtype != AF_INET )
{
return;
}
(void) memmove(
&sa4P->sa_in.sin_addr.s_addr, he->h_addr, he->h_length );
}
}
sa4P->sa_in.sin_port = htons( port );
*gotv4P = 1;
#endif /* USE_IPV6 */
}
static void
shut_down( void )
{
int cnum;
struct timeval tv;
(void) gettimeofday( &tv, (struct timezone*) 0 );
for ( cnum = 0; cnum < max_connects; ++cnum )
{
if ( connects[cnum].conn_state != CNST_FREE )
httpd_close_conn( connects[cnum].hc, &tv );
if ( connects[cnum].hc != (httpd_conn*) 0 )
{
httpd_destroy_conn( connects[cnum].hc );
free( (void*) connects[cnum].hc );
--httpd_conn_count;
connects[cnum].hc = (httpd_conn*) 0;
}
}
if ( hs != (httpd_server*) 0 )
{
httpd_server* ths = hs;
hs = (httpd_server*) 0;
if ( ths->listen4_fd != -1 )
fdwatch_del_fd( ths->listen4_fd );
if ( ths->listen6_fd != -1 )
fdwatch_del_fd( ths->listen6_fd );
httpd_terminate( ths );
}
tmr_destroy();
free( (void*) connects );
}
static int
handle_newconnect( struct timeval* tvP, int listen_fd )
{
connecttab* c;
ClientData client_data;
/* This loops until the accept() fails, trying to start new
** connections as fast as possible so we don't overrun the
** listen queue.
*/
for (;;)
{
/* Is there room in the connection table? */
if ( num_connects >= max_connects )
{
/* Out of connection slots. Run the timers, then the
** existing connections, and maybe we'll free up a slot
** by the time we get back here.
*/
tmr_run( tvP );
return 0;
}
/* Get the first free connection entry off the free list. */
if ( first_free_connect == -1 || connects[first_free_connect].conn_state != CNST_FREE )
{
return;
}
c = &connects[first_free_connect];
/* Make the httpd_conn if necessary. */
if ( c->hc == (httpd_conn*) 0 )
{
c->hc = NEW( httpd_conn, 1 );
if ( c->hc == (httpd_conn*) 0 )
{
return;
}
c->hc->initialized = 0;
c->hc->conn = c;
++httpd_conn_count;
}
/* Get the connection. */
switch ( httpd_get_conn( hs, listen_fd, c->hc ) )
{
/* Some error happened. Run the timers, then the
** existing connections. Maybe the error will clear.
*/
case GC_FAIL:
tmr_run( tvP );
return 0;
/* No more connections to accept for now. */
case GC_NO_MORE:
return 1;
}
c->conn_state = CNST_READING;
/* Pop it off the free list. */
first_free_connect = c->next_free_connect;
c->next_free_connect = -1;
++num_connects;
client_data.p = c;
c->active_at = tvP->tv_sec;
c->wakeup_timer = (Timer*) 0;
c->linger_timer = (Timer*) 0;
c->next_byte_index = 0;
/* Set the connection file descriptor to no-delay mode. */
httpd_set_ndelay( c->hc->conn_fd );
fdwatch_add_fd( c->hc->conn_fd, c, FDW_READ );
++stats_connections;
if ( num_connects > stats_simultaneous )
stats_simultaneous = num_connects;
}
}
static void handle_read_2( connecttab*, struct timeval* );
static void
handle_read( connecttab* c, struct timeval* tvP )
{
int sz;
httpd_conn* hc = c->hc;
/* Is there room in our buffer to read more bytes? */
if ( hc->read_idx >= hc->read_size )
{
if ( hc->read_size > 5000 )
{
httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
finish_connection( c, tvP );
return;
}
httpd_realloc_str(
&hc->read_buf, &hc->read_size, hc->read_size + 1000 );
}
/* Read some more bytes. */
sz = read(
hc->conn_fd, &(hc->read_buf[hc->read_idx]),
hc->read_size - hc->read_idx );
if ( sz == 0 )
{
httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
finish_connection( c, tvP );
return;
}
if ( sz < 0 )
{
/* Ignore EINTR and EAGAIN. Also ignore EWOULDBLOCK. At first glance
** you would think that connections returned by fdwatch as readable
** should never give an EWOULDBLOCK; however, this apparently can
** happen if a packet gets garbled.
*/
if ( errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK )
return;
httpd_send_err(
hc, 400, httpd_err400title, "", httpd_err400form, "" );
finish_connection( c, tvP );
return;
}
hc->read_idx += sz;
c->active_at = tvP->tv_sec;
/* Do we have a complete request yet? */
switch ( httpd_got_request( hc ) )
{
case GR_NO_REQUEST:
return;
case GR_BAD_REQUEST:
httpd_send_err( hc, 400, httpd_err400title, "", httpd_err400form, "" );
finish_connection( c, tvP );
return;
}
/* Yes. Try parsing and resolving it. */
if ( httpd_parse_request( hc ) < 0 )
{
finish_connection( c, tvP );
return;
}
/* Start the connection going. */
if ( httpd_start_request( hc, tvP ) < 0 )
{
/* Something went wrong. Close down the connection. */
finish_connection( c, tvP );
return;
}
if ( c->conn_state == CNST_SLEEPING )
{
return;
}
handle_read_2( c, tvP );
}
static void
handle_read_2( connecttab *c, struct timeval *tvP )
{
httpd_conn* hc = c->hc;
ClientData client_data;
/* Fill in end_byte_index. */
if ( hc->got_range )
{
c->next_byte_index = hc->first_byte_index;
c->end_byte_index = hc->last_byte_index + 1;
}
else if ( hc->bytes_to_send < 0 )
c->end_byte_index = 0;
else
c->end_byte_index = hc->bytes_to_send;
/* Check if it's already handled. */
if ( hc->body_data == (char*) 0 )
{
/* No body data means someone else is handling it. */
c->next_byte_index = hc->bytes_sent;
finish_connection( c, tvP );
return;
}
if ( c->next_byte_index >= c->end_byte_index )
{
/* There's nothing to send. */
finish_connection( c, tvP );
return;
}
/* Cool, we have a valid connection and a file to send to it. */
c->conn_state = CNST_SENDING;
c->started_at = tvP->tv_sec;
c->wouldblock_delay = 0;
client_data.p = c;
fdwatch_del_fd( hc->conn_fd );
fdwatch_add_fd( hc->conn_fd, c, FDW_WRITE );
}
static void
handle_send( connecttab* c, struct timeval* tvP )
{
size_t max_bytes;
int sz, coast;
ClientData client_data;
time_t elapsed;
httpd_conn* hc = c->hc;
int tind;
max_bytes = 1000000000L;
/* Do we need to write the headers first? */
if ( hc->responselen == 0 )
{
/* No, just write the file. */
sz = write(
hc->conn_fd, &(hc->body_data[c->next_byte_index]),
MIN( c->end_byte_index - c->next_byte_index, max_bytes ) );
}
else
{
/* Yes. We'll combine headers and file into a single writev(),
** hoping that this generates a single packet.
*/
struct iovec iv[2];
iv[0].iov_base = hc->response;
iv[0].iov_len = hc->responselen;
iv[1].iov_base = &(hc->body_data[c->next_byte_index]);
iv[1].iov_len = MIN( c->end_byte_index - c->next_byte_index, max_bytes );
sz = writev( hc->conn_fd, iv, 2 );
}
if ( sz < 0 && errno == EINTR )
return;
if ( sz == 0 ||
( sz < 0 && ( errno == EWOULDBLOCK || errno == EAGAIN ) ) )
{
/* This shouldn't happen, but some kernels, e.g.
** SunOS 4.1.x, are broken and select() says that
** O_NDELAY sockets are always writable even when
** they're actually not.
**
** Current workaround is to block sending on this
** socket for a brief adaptively-tuned period.
** Fortunately we already have all the necessary
** blocking code, for use with throttling.
*/
c->wouldblock_delay += MIN_WOULDBLOCK_DELAY;
c->conn_state = CNST_PAUSING;
fdwatch_del_fd( hc->conn_fd );
client_data.p = c;
c->wakeup_timer = tmr_create(
tvP, wakeup_connection, client_data, c->wouldblock_delay, 0 );
if ( c->wakeup_timer == (Timer*) 0 )
{
return;
}
return;
}
if ( sz < 0 )
{
/* Something went wrong, close this connection.
*/
clear_connection( c, tvP );
return;
}
/* Ok, we wrote something. */
c->active_at = tvP->tv_sec;
/* Was this a headers + file writev()? */
if ( hc->responselen > 0 )
{
/* Yes; did we write only part of the headers? */
if ( sz < hc->responselen )
{
/* Yes; move the unwritten part to the front of the buffer. */
int newlen = hc->responselen - sz;
(void) memmove( hc->response, &(hc->response[sz]), newlen );
hc->responselen = newlen;
sz = 0;
}
else
{
/* Nope, we wrote the full headers, so adjust accordingly. */
sz -= hc->responselen;
hc->responselen = 0;
}
}
/* And update how much of the file we wrote. */
c->next_byte_index += sz;
c->hc->bytes_sent += sz;
/* Are we done? */
if ( c->next_byte_index >= c->end_byte_index )
{
/* This connection is finished! */
finish_connection( c, tvP );
return;
}
/* Tune the (blockheaded) wouldblock delay. */
if ( c->wouldblock_delay > MIN_WOULDBLOCK_DELAY )
c->wouldblock_delay -= MIN_WOULDBLOCK_DELAY;
/* (No check on min_limit here, that only controls connection startups.) */
}
static void
handle_linger( connecttab* c, struct timeval* tvP )
{
char buf[4096];
int r;
/* In lingering-close mode we just read and ignore bytes. An error
** or EOF ends things, otherwise we go until a timeout.
*/
r = read( c->hc->conn_fd, buf, sizeof(buf) );
if ( r < 0 && ( errno == EINTR || errno == EAGAIN ) )
return;
if ( r <= 0 )
really_clear_connection( c, tvP );
}
static void
finish_connection( connecttab* c, struct timeval* tvP )
{
/* If we haven't actually sent the buffered response yet, do so now. */
httpd_write_response( c->hc );
/* And clear. */
clear_connection( c, tvP );
}
static void
clear_connection( connecttab* c, struct timeval* tvP )
{
ClientData client_data;
if ( c->wakeup_timer != (Timer*) 0 )
{
tmr_cancel( c->wakeup_timer );
c->wakeup_timer = 0;
}
/* This is our version of Apache's lingering_close() routine, which is
** their version of the often-broken SO_LINGER socket option. For why
** this is necessary, see http://www.apache.org/docs/misc/fin_wait_2.html
** What we do is delay the actual closing for a few seconds, while reading
** any bytes that come over the connection. However, we don't want to do
** this unless it's necessary, because it ties up a connection slot and
** file descriptor which means our maximum connection-handling rate
** is lower. So, elsewhere we set a flag when we detect the few
** circumstances that make a lingering close necessary. If the flag
** isn't set we do the real close now.
*/
if ( c->conn_state == CNST_LINGERING )
{
/* If we were already lingering, shut down for real. */
tmr_cancel( c->linger_timer );
c->linger_timer = (Timer*) 0;
c->hc->should_linger = 0;
}
if ( c->hc->should_linger )
{
if ( c->conn_state != CNST_PAUSING && c->conn_state != CNST_SLEEPING )
fdwatch_del_fd( c->hc->conn_fd );
c->conn_state = CNST_LINGERING;
shutdown( c->hc->conn_fd, SHUT_WR );
fdwatch_add_fd( c->hc->conn_fd, c, FDW_READ );
client_data.p = c;
c->linger_timer = tmr_create(
tvP, linger_clear_connection, client_data, LINGER_TIME, 0 );
}
else
really_clear_connection( c, tvP );
}
static void
really_clear_connection( connecttab* c, struct timeval* tvP )
{
stats_bytes += c->hc->bytes_sent;
if ( c->conn_state != CNST_PAUSING && c->conn_state != CNST_SLEEPING )
fdwatch_del_fd( c->hc->conn_fd );
httpd_close_conn( c->hc, tvP );
if ( c->linger_timer != (Timer*) 0 )
{
tmr_cancel( c->linger_timer );
c->linger_timer = 0;
}
c->conn_state = CNST_FREE;
c->next_free_connect = first_free_connect;
first_free_connect = c - connects; /* division by sizeof is implied */
--num_connects;
}
static void
idle( ClientData client_data, struct timeval* nowP )
{
int cnum;
connecttab* c;
for ( cnum = 0; cnum < max_connects; ++cnum )
{
c = &connects[cnum];
switch ( c->conn_state )
{
case CNST_READING:
if ( nowP->tv_sec - c->active_at >= IDLE_READ_TIMELIMIT )
{
httpd_send_err(
c->hc, 408, httpd_err408title, "", httpd_err408form, "" );
finish_connection( c, nowP );
}
break;
case CNST_SENDING:
case CNST_PAUSING:
if ( nowP->tv_sec - c->active_at >= IDLE_SEND_TIMELIMIT )
{
clear_connection( c, nowP );
}
break;
case CNST_SLEEPING:;
}
}
}
static void
wakeup_connection( ClientData client_data, struct timeval* nowP )
{
connecttab* c;
c = (connecttab*) client_data.p;
c->wakeup_timer = (Timer*) 0;
if ( c->conn_state == CNST_PAUSING || c->conn_state == CNST_SLEEPING )
{
c->conn_state = CNST_SENDING;
fdwatch_add_fd( c->hc->conn_fd, c, FDW_WRITE );
}
}
static void
linger_clear_connection( ClientData client_data, struct timeval* nowP )
{
connecttab* c;
c = (connecttab*) client_data.p;
c->linger_timer = (Timer*) 0;
really_clear_connection( c, nowP );
}
static void
occasional( ClientData client_data, struct timeval* nowP )
{
tmr_cleanup();
}
static void
httpd_conn_wakeup( ClientData client_data, struct timeval* nowP )
{
connecttab* c = client_data.p;
c->conn_state = CNST_READING;
c->wakeup_timer = (Timer*) 0;
if( httpd_continue_request( c->hc, nowP ) < 0 )
{
finish_connection( c, nowP );
return;
}
if( c->conn_state == CNST_READING )
handle_read_2( c, nowP );
}
void
httpd_conn_sleep( httpd_conn *hc, int seconds )
{
connecttab* c = hc->conn;
ClientData client_data;
if ( c->wakeup_timer != (Timer*) 0 )
{
tmr_cancel( c->wakeup_timer );
c->wakeup_timer = 0;
}
fdwatch_del_fd( hc->conn_fd );
c->conn_state = CNST_SLEEPING;
client_data.p = c;
c->wakeup_timer = tmr_create(
0, httpd_conn_wakeup, client_data, seconds * 1000, 0 );
}