|
|
1 | use AnyEvent (); |
|
|
2 | |
1 | use Coro; |
3 | use Coro; |
2 | use Coro::Semaphore; |
4 | use Coro::Semaphore; |
|
|
5 | use Coro::SemaphoreSet; |
3 | use Coro::Event; |
6 | use Coro::EV; |
4 | use Coro::Socket; |
7 | use Coro::Socket; |
|
|
8 | use Coro::Signal; |
|
|
9 | use Coro::AIO (); |
5 | |
10 | |
|
|
11 | use Fcntl; |
6 | use HTTP::Date; |
12 | use HTTP::Date; |
|
|
13 | use POSIX (); |
7 | |
14 | |
8 | no utf8; |
15 | use Compress::Zlib (); |
9 | use bytes; |
16 | |
|
|
17 | use common::sense; |
10 | |
18 | |
11 | # at least on my machine, this thingy serves files |
19 | # at least on my machine, this thingy serves files |
12 | # quite a bit faster than apache, ;) |
20 | # quite a bit faster than apache, ;) |
13 | # and quite a bit slower than thttpd :( |
21 | # and quite a bit slower than thttpd :( |
14 | |
22 | |
15 | $SIG{PIPE} = 'IGNORE'; |
23 | $SIG{PIPE} = 'IGNORE'; |
16 | |
24 | |
17 | our $accesslog; |
25 | our $accesslog; |
|
|
26 | our $errorlog; |
|
|
27 | our @listen_sockets; |
|
|
28 | |
|
|
29 | our $NOW; |
|
|
30 | our $HTTP_NOW; |
|
|
31 | |
|
|
32 | our $ERROR_LOG; |
|
|
33 | our $ACCESS_LOG; |
|
|
34 | our $TRANSFER_LOCK = new Coro::SemaphoreSet; # lock to be acquired per ip |
|
|
35 | |
|
|
36 | our $update_time = EV::periodic 0, 1, undef, sub { |
|
|
37 | $NOW = time; |
|
|
38 | $HTTP_NOW = time2str $NOW; |
|
|
39 | }; |
|
|
40 | $update_time->invoke; |
|
|
41 | |
|
|
42 | if ($ERROR_LOG) { |
|
|
43 | use IO::Handle; |
|
|
44 | open $errorlog, ">>$ERROR_LOG" |
|
|
45 | or die "$ERROR_LOG: $!"; |
|
|
46 | $errorlog->autoflush(1); |
|
|
47 | } |
18 | |
48 | |
19 | if ($ACCESS_LOG) { |
49 | if ($ACCESS_LOG) { |
20 | use IO::Handle; |
50 | use IO::Handle; |
21 | open $accesslog, ">>$ACCESS_LOG" |
51 | open $accesslog, ">>$ACCESS_LOG" |
22 | or die "$ACCESS_LOG: $!"; |
52 | or die "$ACCESS_LOG: $!"; |
… | |
… | |
24 | } |
54 | } |
25 | |
55 | |
26 | sub slog { |
56 | sub slog { |
27 | my $level = shift; |
57 | my $level = shift; |
28 | my $format = shift; |
58 | my $format = shift; |
|
|
59 | |
|
|
60 | $format = sprintf $format, @_ if @_; |
|
|
61 | |
|
|
62 | my $NOW = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW); |
29 | printf "---: $format\n", @_; |
63 | print "$NOW: $format\n"; |
|
|
64 | print $errorlog "$NOW: $format\n", @_ if $errorlog; |
30 | } |
65 | } |
31 | |
66 | |
32 | our $connections = new Coro::Semaphore $MAX_CONNECTS || 250; |
67 | our $connections = new Coro::Semaphore $::MAX_CONNECTS || 250; |
|
|
68 | our $httpevent = new Coro::Signal; |
33 | |
69 | |
34 | our $wait_factor = 0.95; |
70 | our $queue_file = new transferqueue $::MAX_TRANSFERS; |
|
|
71 | our $queue_index = new transferqueue 10; |
35 | |
72 | |
36 | our @transfers = ( |
73 | our $tbf_top = new tbf rate => $::TBF_RATE || 100000; |
37 | [(new Coro::Semaphore $MAX_TRANSFERS_SMALL || 50), 1], |
|
|
38 | [(new Coro::Semaphore $MAX_TRANSFERS_LARGE || 50), 1], |
|
|
39 | ); |
|
|
40 | |
74 | |
41 | my @newcons; |
75 | my $unused_bytes = 0; |
42 | my @pool; |
76 | my $unused_last = time; |
43 | |
77 | |
44 | # one "execution thread" |
78 | sub unused_bandwidth { |
45 | sub handler { |
79 | $unused_bytes += $_[0]; |
|
|
80 | if ($unused_last < $NOW - 30 && $unused_bytes / ($NOW - $unused_last) > 50000) { |
|
|
81 | $unused_last = $NOW; |
|
|
82 | $unused_bytes = 0; |
|
|
83 | $queue_file->force_wake_next |
|
|
84 | and slog 1, "forced filetransfer due to unused bandwidth"; |
|
|
85 | } |
|
|
86 | } |
|
|
87 | |
|
|
88 | sub listen_on { |
|
|
89 | my $listen = $_[0]; |
|
|
90 | |
|
|
91 | push @listen_sockets, $listen; |
|
|
92 | |
|
|
93 | # the "main thread" |
|
|
94 | async { |
|
|
95 | slog 1, "accepting connections"; |
46 | while () { |
96 | while () { |
47 | my $new = pop @newcons; |
97 | $connections->down; |
48 | if ($new) { |
98 | my @conn = $listen->accept; |
|
|
99 | #slog 3, "accepted @$connections ".scalar(@pool); |
|
|
100 | |
|
|
101 | async_pool { |
49 | eval { |
102 | eval { |
50 | conn->new(@$new)->handle; |
103 | conn->new (@conn)->handle; |
51 | }; |
104 | }; |
52 | slog 1, "$@" if $@ && !ref $@; |
105 | slog 1, "$@" if $@ && !ref $@; |
|
|
106 | |
|
|
107 | $httpevent->broadcast; # only for testing, but doesn't matter much |
|
|
108 | |
53 | $connections->up; |
109 | $connections->up; |
54 | } else { |
|
|
55 | last if @pool >= $MAX_POOL; |
|
|
56 | push @pool, $Coro::current; |
|
|
57 | schedule; |
|
|
58 | } |
110 | } |
|
|
111 | } |
59 | } |
112 | }; |
60 | } |
113 | } |
61 | |
114 | |
62 | my $http_port = new Coro::Socket |
115 | my $http_port = new Coro::Socket |
63 | LocalAddr => $SERVER_HOST, |
116 | LocalAddr => $::SERVER_HOST, |
64 | LocalPort => $SERVER_PORT, |
117 | LocalPort => $::SERVER_PORT, |
65 | ReuseAddr => 1, |
118 | ReuseAddr => 1, |
66 | Listen => 50, |
119 | Listen => 50, |
67 | or die "unable to start server"; |
120 | or die "unable to start server"; |
68 | |
121 | |
69 | push @listen_sockets, $http_port; |
122 | listen_on $http_port; |
70 | |
123 | |
71 | our $NOW; |
124 | if ($::SERVER_PORT2) { |
72 | our $HTTP_NOW; |
125 | my $http_port = new Coro::Socket |
|
|
126 | LocalAddr => $::SERVER_HOST, |
|
|
127 | LocalPort => $::SERVER_PORT2, |
|
|
128 | ReuseAddr => 1, |
|
|
129 | Listen => 50, |
|
|
130 | or die "unable to start server"; |
73 | |
131 | |
74 | Event->timer(interval => 1, hard => 1, cb => sub { |
132 | listen_on $http_port; |
75 | $NOW = time; |
133 | } |
76 | $HTTP_NOW = time2str $NOW; |
|
|
77 | })->now; |
|
|
78 | |
|
|
79 | # the "main thread" |
|
|
80 | async { |
|
|
81 | slog 1, "accepting connections"; |
|
|
82 | while () { |
|
|
83 | $connections->down; |
|
|
84 | push @newcons, [$http_port->accept]; |
|
|
85 | #slog 3, "accepted @$connections ".scalar(@pool); |
|
|
86 | if (@pool) { |
|
|
87 | (pop @pool)->ready; |
|
|
88 | } else { |
|
|
89 | async \&handler; |
|
|
90 | } |
|
|
91 | |
|
|
92 | } |
|
|
93 | }; |
|
|
94 | |
134 | |
95 | package conn; |
135 | package conn; |
|
|
136 | |
|
|
137 | use common::sense; |
96 | |
138 | |
97 | use Socket; |
139 | use Socket; |
98 | use HTTP::Date; |
140 | use HTTP::Date; |
99 | use Convert::Scalar 'weaken'; |
141 | use Convert::Scalar 'weaken'; |
100 | use Linux::AIO; |
142 | use IO::AIO; |
|
|
143 | use AnyEvent::AIO; |
101 | |
144 | |
102 | Linux::AIO::min_parallel $::AIO_PARALLEL; |
145 | IO::AIO::min_parallel $::AIO_PARALLEL; |
103 | |
|
|
104 | my $aio_requests = new Coro::Semaphore $::AIO_PARALLEL * 4; |
|
|
105 | |
|
|
106 | Event->io(fd => Linux::AIO::poll_fileno, |
|
|
107 | poll => 'r', async => 1, |
|
|
108 | cb => \&Linux::AIO::poll_cb); |
|
|
109 | |
146 | |
110 | our %conn; # $conn{ip}{self} => connobj |
147 | our %conn; # $conn{ip}{self} => connobj |
111 | our %uri; # $uri{ip}{uri}{self} |
148 | our %uri; # $uri{ip}{uri}{self} |
112 | our %blocked; |
149 | our %blocked; |
113 | our %mimetype; |
150 | our %mimetype; |
114 | |
151 | |
115 | sub read_mimetypes { |
152 | sub read_mimetypes { |
116 | local *M; |
|
|
117 | if (open M, "<mime_types") { |
153 | if (open my $fh, "<mime_types") { |
118 | while (<M>) { |
154 | while (<$fh>) { |
119 | if (/^([^#]\S+)\t+(\S+)$/) { |
155 | if (/^([^#]\S+)\t+(\S+)$/) { |
120 | $mimetype{lc $1} = $2; |
156 | $mimetype{lc $1} = $2; |
121 | } |
157 | } |
122 | } |
158 | } |
123 | } else { |
159 | } else { |
… | |
… | |
127 | |
163 | |
128 | read_mimetypes; |
164 | read_mimetypes; |
129 | |
165 | |
130 | sub new { |
166 | sub new { |
131 | my $class = shift; |
167 | my $class = shift; |
|
|
168 | my $fh = shift; |
132 | my $peername = shift; |
169 | my $peername = shift; |
133 | my $fh = shift; |
|
|
134 | my $self = bless { fh => $fh }, $class; |
170 | my $self = bless { fh => $fh }, $class; |
135 | my (undef, $iaddr) = unpack_sockaddr_in $peername |
171 | my (undef, $iaddr) = unpack_sockaddr_in $peername |
136 | or $self->err(500, "unable to decode peername"); |
172 | or $self->err (500, "unable to decode peername"); |
137 | |
173 | |
|
|
174 | $self->{remote_addr} = |
138 | $self->{remote_addr} = inet_ntoa $iaddr; |
175 | $self->{remote_id} = inet_ntoa $iaddr; |
|
|
176 | |
139 | $self->{time} = $::NOW; |
177 | $self->{time} = $::NOW; |
140 | |
178 | |
141 | # enter ourselves into various lists |
179 | weaken ($Coro::current->{conn} = $self); |
142 | weaken ($conn{$self->{remote_addr}}{$self*1} = $self); |
|
|
143 | |
180 | |
144 | $::conns++; |
181 | ++$::conns; |
|
|
182 | $::maxconns = $::conns if $::conns > $::maxconns; |
145 | |
183 | |
146 | $self; |
184 | $self |
147 | } |
185 | } |
148 | |
186 | |
149 | sub DESTROY { |
187 | sub DESTROY { |
150 | my $self = shift; |
188 | my $self = shift; |
151 | |
189 | |
152 | $::conns--; |
190 | --$::conns; |
153 | |
|
|
154 | $self->eoconn; |
|
|
155 | delete $conn{$self->{remote_addr}}{$self*1}; |
|
|
156 | } |
191 | } |
157 | |
192 | |
158 | # end of connection |
193 | sub prune_cache { |
159 | sub eoconn { |
194 | my $hash = $_[0]; |
160 | my $self = shift; |
195 | |
161 | delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1}; |
196 | for (keys %$hash) { |
|
|
197 | if (ref $hash->{$_} eq HASH::) { |
|
|
198 | prune_cache($hash->{$_}); |
|
|
199 | unless (scalar keys %{$hash->{$_}}) { |
|
|
200 | delete $hash->{$_}; |
|
|
201 | } |
|
|
202 | } |
|
|
203 | } |
162 | } |
204 | } |
|
|
205 | |
|
|
206 | sub prune_caches { |
|
|
207 | prune_cache \%conn; |
|
|
208 | prune_cache \%uri; |
|
|
209 | |
|
|
210 | for (keys %blocked) { |
|
|
211 | delete $blocked{$_} unless $blocked{$_}[0] > $::NOW; |
|
|
212 | } |
|
|
213 | } |
|
|
214 | |
|
|
215 | our $PRUNE_WATCHER = AE::timer 60, 60, \&prune_caches; |
163 | |
216 | |
164 | sub slog { |
217 | sub slog { |
165 | my $self = shift; |
218 | my $self = shift; |
166 | main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]"); |
219 | main::slog($_[0], "$self->{remote_id}> $_[1]"); |
167 | } |
220 | } |
168 | |
221 | |
169 | sub response { |
222 | sub response { |
170 | my ($self, $code, $msg, $hdr, $content) = @_; |
223 | my ($self, $code, $msg, $hdr, $content) = @_; |
171 | my $res = "HTTP/1.1 $code $msg\015\012"; |
224 | my $res = "HTTP/1.1 $code $msg\015\012"; |
|
|
225 | my $GZ = ""; |
172 | |
226 | |
173 | $self->{h}{connection} ||= $hdr->{Connection}; |
227 | if (exists $hdr->{Connection}) { |
|
|
228 | if ($hdr->{Connection} =~ /close/) { |
|
|
229 | $self->{h}{connection} = "close" |
|
|
230 | } |
|
|
231 | } else { |
|
|
232 | if ($self->{version} < 1.1) { |
|
|
233 | if ($self->{h}{connection} =~ /keep-alive/i) { |
|
|
234 | $hdr->{Connection} = "Keep-Alive"; |
|
|
235 | } else { |
|
|
236 | $self->{h}{connection} = "close" |
|
|
237 | } |
|
|
238 | } |
|
|
239 | } |
|
|
240 | |
|
|
241 | if ($self->{method} ne "HEAD" |
|
|
242 | && $self->{h}{"accept-encoding"} =~ /\bgzip\b/ |
|
|
243 | && 400 < length $content |
|
|
244 | && $hdr->{"Content-Length"} == length $content |
|
|
245 | && !exists $hdr->{"Content-Encoding"} |
|
|
246 | ) { |
|
|
247 | my $orig = length $content; |
|
|
248 | $hdr->{"Content-Encoding"} = "gzip"; |
|
|
249 | $content = Compress::Zlib::memGzip(\$content); |
|
|
250 | $hdr->{"Content-Length"} = length $content; |
|
|
251 | $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig); |
|
|
252 | } |
174 | |
253 | |
175 | $res .= "Date: $HTTP_NOW\015\012"; |
254 | $res .= "Date: $HTTP_NOW\015\012"; |
|
|
255 | $res .= "Server: $::NAME\015\012"; |
176 | |
256 | |
177 | while (my ($h, $v) = each %$hdr) { |
257 | while (my ($h, $v) = each %$hdr) { |
178 | $res .= "$h: $v\015\012" |
258 | $res .= "$h: $v\015\012" |
179 | } |
259 | } |
180 | $res .= "\015\012"; |
260 | $res .= "\015\012"; |
181 | |
261 | |
182 | $res .= $content if defined $content and $self->{method} ne "HEAD"; |
262 | $res .= $content if defined $content and $self->{method} ne "HEAD"; |
183 | |
263 | |
184 | my $log = "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n"; |
264 | my $log = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW). |
|
|
265 | " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}.$GZ. |
|
|
266 | " \"$self->{h}{referer}\"\n"; |
185 | |
267 | |
186 | print $accesslog $log if $accesslog; |
268 | print $::accesslog $log if $::accesslog; |
187 | print STDERR $log; |
269 | print STDERR $log; |
188 | |
270 | |
189 | $self->{written} += |
271 | $tbf_top->request(length $res, 1e6); |
190 | print {$self->{fh}} $res; |
272 | $self->{written} += print {$self->{fh}} $res; |
191 | } |
273 | } |
192 | |
274 | |
193 | sub err { |
275 | sub err { |
194 | my $self = shift; |
276 | my $self = shift; |
195 | my ($code, $msg, $hdr, $content) = @_; |
277 | my ($code, $msg, $hdr, $content) = @_; |
… | |
… | |
199 | $hdr->{"Content-Type"} = "text/plain"; |
281 | $hdr->{"Content-Type"} = "text/plain"; |
200 | $hdr->{"Content-Length"} = length $content; |
282 | $hdr->{"Content-Length"} = length $content; |
201 | } |
283 | } |
202 | $hdr->{"Connection"} = "close"; |
284 | $hdr->{"Connection"} = "close"; |
203 | |
285 | |
204 | $self->response($code, $msg, $hdr, $content); |
286 | $self->response ($code, $msg, $hdr, $content); |
205 | |
287 | |
206 | die bless {}, err::; |
288 | die bless {}, err:: |
207 | } |
289 | } |
208 | |
290 | |
209 | sub handle { |
291 | sub handle { |
210 | my $self = shift; |
292 | my $self = shift; |
211 | my $fh = $self->{fh}; |
293 | my $fh = $self->{fh}; |
212 | |
294 | |
213 | my $host; |
295 | my $host; |
214 | |
296 | |
215 | $fh->timeout($::REQ_TIMEOUT); |
297 | $fh->timeout($::REQ_TIMEOUT); |
216 | while() { |
298 | while () { |
217 | $self->{reqs}++; |
299 | $self->{reqs}++; |
218 | |
300 | |
219 | # read request and parse first line |
301 | # read request and parse first line |
220 | my $req = $fh->readline("\015\012\015\012"); |
302 | my $req = $fh->readline("\015\012\015\012"); |
221 | |
303 | |
… | |
… | |
228 | } |
310 | } |
229 | |
311 | |
230 | $self->{h} = {}; |
312 | $self->{h} = {}; |
231 | |
313 | |
232 | $fh->timeout($::RES_TIMEOUT); |
314 | $fh->timeout($::RES_TIMEOUT); |
233 | my $ip = $self->{remote_addr}; |
|
|
234 | |
|
|
235 | if ($blocked{$ip}) { |
|
|
236 | $self->err_blocked($blocked{$ip}) |
|
|
237 | if $blocked{$ip} > $::NOW; |
|
|
238 | |
|
|
239 | delete $blocked{$ip}; |
|
|
240 | } |
|
|
241 | |
|
|
242 | if (%{$conn{$ip}} > $::MAX_CONN_IP) { |
|
|
243 | my $delay = 120; |
|
|
244 | while (%{$conn{$ip}} > $::MAX_CONN_IP) { |
|
|
245 | if ($delay <= 0) { |
|
|
246 | $self->slog(2, "blocked ip $ip"); |
|
|
247 | $self->err_blocked; |
|
|
248 | } else { |
|
|
249 | Coro::Event::do_timer(after => 3); |
|
|
250 | $delay -= 3; |
|
|
251 | } |
|
|
252 | } |
|
|
253 | } |
|
|
254 | |
315 | |
255 | $req =~ /^(?:\015\012)? |
316 | $req =~ /^(?:\015\012)? |
256 | (GET|HEAD) \040+ |
317 | (GET|HEAD) \040+ |
257 | ([^\040]+) \040+ |
318 | ([^\040]+) \040+ |
258 | HTTP\/([0-9]+\.[0-9]+) |
319 | HTTP\/([0-9]+\.[0-9]+) |
… | |
… | |
271 | my (%hdr, $h, $v); |
332 | my (%hdr, $h, $v); |
272 | |
333 | |
273 | $hdr{lc $1} .= ",$2" |
334 | $hdr{lc $1} .= ",$2" |
274 | while $req =~ /\G |
335 | while $req =~ /\G |
275 | ([^:\000-\040]+): |
336 | ([^:\000-\040]+): |
276 | [\008\040]* |
337 | [\011\040]* |
277 | ((?: [^\015\012]+ | \015\012[\008\040] )*) |
338 | ((?: [^\015\012]+ | \015\012[\011\040] )*) |
278 | \015\012 |
339 | \015\012 |
279 | /gxc; |
340 | /gxc; |
280 | |
341 | |
281 | $req =~ /\G\015\012$/ |
342 | $req =~ /\G\015\012$/ |
282 | or $self->err(400, "bad request"); |
343 | or $self->err(400, "bad request"); |
283 | |
344 | |
284 | $self->{h}{$h} = substr $v, 1 |
345 | $self->{h}{$h} = substr $v, 1 |
285 | while ($h, $v) = each %hdr; |
346 | while ($h, $v) = each %hdr; |
|
|
347 | } |
|
|
348 | |
|
|
349 | # remote id should be unique per user |
|
|
350 | my $id = $self->{remote_addr}; |
|
|
351 | |
|
|
352 | if (exists $self->{h}{"client-ip"}) { |
|
|
353 | $id .= "[".$self->{h}{"client-ip"}."]"; |
|
|
354 | } elsif (exists $self->{h}{"x-forwarded-for"}) { |
|
|
355 | $id .= "[".$self->{h}{"x-forwarded-for"}."]"; |
|
|
356 | } |
|
|
357 | |
|
|
358 | $self->{remote_id} = $id; |
|
|
359 | |
|
|
360 | weaken (local $conn{$id}{$self*1} = $self); |
|
|
361 | |
|
|
362 | if ($blocked{$id}) { |
|
|
363 | $self->err_blocked |
|
|
364 | if $blocked{$id}[0] > $::NOW; |
|
|
365 | |
|
|
366 | delete $blocked{$id}; |
286 | } |
367 | } |
287 | |
368 | |
288 | # find out server name and port |
369 | # find out server name and port |
289 | if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) { |
370 | if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) { |
290 | $host = $1; |
371 | $host = $1; |
… | |
… | |
294 | |
375 | |
295 | if (defined $host) { |
376 | if (defined $host) { |
296 | $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80; |
377 | $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80; |
297 | } else { |
378 | } else { |
298 | ($self->{server_port}, $host) |
379 | ($self->{server_port}, $host) |
299 | = unpack_sockaddr_in $self->{fh}->getsockname |
380 | = unpack_sockaddr_in $self->{fh}->sockname |
300 | or $self->err(500, "unable to get socket name"); |
381 | or $self->err(500, "unable to get socket name"); |
301 | $host = inet_ntoa $host; |
382 | $host = inet_ntoa $host; |
302 | } |
383 | } |
303 | |
384 | |
304 | $self->{server_name} = $host; |
385 | $self->{server_name} = $host; |
305 | |
386 | |
306 | # remote id should be unique per user |
|
|
307 | $self->{remote_id} = $self->{remote_addr}; |
|
|
308 | |
|
|
309 | if (exists $self->{h}{"client-ip"}) { |
|
|
310 | $self->{remote_id} .= "[".$self->{h}{"client-ip"}."]"; |
|
|
311 | } elsif (exists $self->{h}{"x-forwarded-for"}) { |
|
|
312 | $self->{remote_id} .= "[".$self->{h}{"x-forwarded-for"}."]"; |
|
|
313 | } |
|
|
314 | |
|
|
315 | weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self); |
387 | weaken (local $uri{$id}{$self->{uri}}{$self*1} = $self); |
316 | |
388 | |
317 | eval { |
389 | eval { |
318 | $self->map_uri; |
390 | $self->map_uri; |
319 | $self->respond; |
391 | $self->respond; |
320 | }; |
392 | }; |
321 | |
393 | |
322 | $self->eoconn; |
|
|
323 | |
|
|
324 | die if $@ && !ref $@; |
394 | die if $@ && !ref $@; |
325 | |
395 | |
326 | last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1; |
396 | last if $self->{h}{connection} =~ /close/i; |
|
|
397 | |
|
|
398 | $httpevent->broadcast; |
327 | |
399 | |
328 | $fh->timeout($::PER_TIMEOUT); |
400 | $fh->timeout($::PER_TIMEOUT); |
329 | } |
401 | } |
|
|
402 | } |
|
|
403 | |
|
|
404 | sub block { |
|
|
405 | my $self = shift; |
|
|
406 | |
|
|
407 | $blocked{$self->{remote_id}} = [$::NOW + $_[0], $_[1]]; |
|
|
408 | $self->slog(2, "blocked ip $self->{remote_id}"); |
|
|
409 | $self->err_blocked; |
330 | } |
410 | } |
331 | |
411 | |
332 | # uri => path mapping |
412 | # uri => path mapping |
333 | sub map_uri { |
413 | sub map_uri { |
334 | my $self = shift; |
414 | my $self = shift; |
335 | my $host = $self->{server_name}; |
415 | my $host = $self->{server_name}; |
336 | my $uri = $self->{uri}; |
416 | my $uri = $self->{uri}; |
|
|
417 | |
|
|
418 | $host =~ /[\/\\]/ |
|
|
419 | and $self->err(400, "bad request"); |
337 | |
420 | |
338 | # some massaging, also makes it more secure |
421 | # some massaging, also makes it more secure |
339 | $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; |
422 | $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; |
340 | $uri =~ s%//+%/%g; |
423 | $uri =~ s%//+%/%g; |
341 | $uri =~ s%/\.(?=/|$)%%g; |
424 | $uri =~ s%/\.(?=/|$)%%g; |
… | |
… | |
381 | |
464 | |
382 | sub respond { |
465 | sub respond { |
383 | my $self = shift; |
466 | my $self = shift; |
384 | my $path = $self->{path}; |
467 | my $path = $self->{path}; |
385 | |
468 | |
386 | stat $path |
469 | if ($self->{name} =~ s%^/internal/([^/]+)%%) { |
387 | or $self->err(404, "not found"); |
470 | if ($::internal{$1}) { |
388 | |
471 | $::internal{$1}->($self); |
389 | $self->{stat} = [stat _]; |
|
|
390 | |
|
|
391 | # idiotic netscape sends idiotic headers AGAIN |
|
|
392 | my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ |
|
|
393 | ? str2time $1 : 0; |
|
|
394 | |
|
|
395 | if (-d _ && -r _) { |
|
|
396 | # directory |
|
|
397 | if ($path !~ /\/$/) { |
|
|
398 | # create a redirect to get the trailing "/" |
|
|
399 | # we don't try to avoid the :80 |
|
|
400 | $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" }); |
|
|
401 | } else { |
472 | } else { |
402 | $ims < $self->{stat}[9] |
|
|
403 | or $self->err(304, "not modified"); |
473 | $self->err (404, "not found"); |
|
|
474 | } |
|
|
475 | } else { |
404 | |
476 | |
405 | if (-r "$path/index.html") { |
477 | Coro::AIO::aio_stat $path |
406 | $self->{path} .= "/index.html"; |
478 | and $self->err (404, "not found"); |
407 | $self->handle_file; |
479 | |
|
|
480 | $self->{stat} = [stat _]; |
|
|
481 | |
|
|
482 | # idiotic netscape sends idiotic headers AGAIN |
|
|
483 | my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ |
|
|
484 | ? str2time $1 : 0; |
|
|
485 | |
|
|
486 | if (-d _ && -r _) { |
|
|
487 | # directory |
|
|
488 | if ($path !~ /\/$/) { |
|
|
489 | # create a redirect to get the trailing "/" |
|
|
490 | # we don't try to avoid the :80 |
|
|
491 | $self->err (301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" }); |
408 | } else { |
492 | } else { |
|
|
493 | $ims < $self->{stat}[9] |
|
|
494 | or $self->err (304, "not modified"); |
|
|
495 | |
|
|
496 | if (-r "$path/index.html") { |
|
|
497 | # replace directory "size" by index.html filesize |
|
|
498 | $self->{stat} = [stat ($self->{path} .= "/index.html")]; |
|
|
499 | $self->handle_file ($queue_index, $tbf_top); |
|
|
500 | } else { |
409 | $self->handle_dir; |
501 | $self->handle_dir; |
410 | } |
502 | } |
411 | } |
503 | } |
412 | } elsif (-f _ && -r _) { |
504 | } elsif (-f _ && -r _) { |
413 | -x _ and $self->err(403, "forbidden"); |
505 | -x _ and $self->err (403, "forbidden"); |
414 | $self->handle_file; |
506 | |
|
|
507 | if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { |
|
|
508 | my $timeout = $::NOW + 10; |
|
|
509 | while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { |
|
|
510 | if ($timeout < $::NOW) { |
|
|
511 | $self->block($::BLOCKTIME, "too many connections"); |
|
|
512 | } else { |
|
|
513 | $httpevent->wait; |
|
|
514 | } |
|
|
515 | } |
|
|
516 | } |
|
|
517 | |
|
|
518 | $self->handle_file ($queue_file, $tbf_top); |
415 | } else { |
519 | } else { |
416 | $self->err(404, "not found"); |
520 | $self->err (404, "not found"); |
|
|
521 | } |
417 | } |
522 | } |
418 | } |
523 | } |
419 | |
524 | |
420 | sub handle_dir { |
525 | sub handle_dir { |
421 | my $self = shift; |
526 | my $self = shift; |
422 | my $idx = $self->diridx; |
527 | my $idx = $self->diridx; |
423 | |
528 | |
424 | $self->response(200, "ok", |
529 | $self->response (200, "ok", |
425 | { |
530 | { |
426 | "Content-Type" => "text/html", |
531 | "Content-Type" => "text/html; charset=utf-8", |
427 | "Content-Length" => length $idx, |
532 | "Content-Length" => length $idx, |
|
|
533 | "Last-Modified" => time2str ($self->{stat}[9]), |
428 | }, |
534 | }, |
429 | $idx); |
535 | $idx); |
430 | } |
536 | } |
431 | |
537 | |
432 | sub handle_file { |
538 | sub handle_file { |
433 | my $self = shift; |
539 | my ($self, $queue, $tbf) = @_; |
434 | my $length = $self->{stat}[7]; |
540 | my $length = $self->{stat}[7]; |
435 | my $queue = $::transfers[$length >= $::TRANSFER_SMALL]; |
|
|
436 | my $hdr = { |
541 | my $hdr = { |
437 | "Last-Modified" => time2str ((stat _)[9]), |
542 | "Last-Modified" => time2str ((stat _)[9]), |
|
|
543 | "Accept-Ranges" => "bytes", |
438 | }; |
544 | }; |
439 | |
545 | |
440 | my @code = (200, "ok"); |
546 | my @code = (200, "ok"); |
441 | my ($l, $h); |
547 | my ($l, $h); |
442 | |
548 | |
443 | if ($self->{h}{range} =~ /^bytes=(.*)$/) { |
549 | if ($self->{h}{range} =~ /^bytes=(.*)$/i) { |
444 | for (split /,/, $1) { |
550 | for (split /,/, $1) { |
445 | if (/^-(\d+)$/) { |
551 | if (/^-(\d+)$/) { |
446 | ($l, $h) = ($length - $1, $length - 1); |
552 | ($l, $h) = ($length - $1, $length - 1); |
447 | } elsif (/^(\d+)-(\d*)$/) { |
553 | } elsif (/^(\d+)-(\d*)$/) { |
448 | ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); |
554 | ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); |
… | |
… | |
452 | } |
558 | } |
453 | goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; |
559 | goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; |
454 | } |
560 | } |
455 | $hdr->{"Content-Range"} = "bytes */$length"; |
561 | $hdr->{"Content-Range"} = "bytes */$length"; |
456 | $hdr->{"Content-Length"} = $length; |
562 | $hdr->{"Content-Length"} = $length; |
457 | $self->err(416, "not satisfiable", $hdr, ""); |
563 | $self->err (416, "not satisfiable", $hdr, ""); |
458 | |
564 | |
459 | satisfiable: |
565 | satisfiable: |
460 | # check for segmented downloads |
566 | # check for segmented downloads |
461 | if ($l && $::NO_SEGMENTED) { |
567 | if ($l && $::NO_SEGMENTED) { |
462 | my $delay = 180; |
568 | my $timeout = $::NOW + 15; |
463 | while (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) { |
569 | while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { |
464 | if ($delay <= 0) { |
570 | if ($timeout <= $::NOW) { |
|
|
571 | $self->block ($::BLOCKTIME, "segmented downloads are forbidden"); |
465 | $self->err_segmented_download; |
572 | #$self->err_segmented_download; |
466 | } else { |
573 | } else { |
467 | Coro::Event::do_timer(after => 3); $delay -= 3; |
574 | $httpevent->wait; |
468 | } |
575 | } |
469 | } |
576 | } |
470 | } |
577 | } |
471 | |
578 | |
472 | $hdr->{"Content-Range"} = "bytes $l-$h/$length"; |
579 | $hdr->{"Content-Range"} = "bytes $l-$h/$length"; |
… | |
… | |
480 | |
587 | |
481 | $self->{path} =~ /\.([^.]+)$/; |
588 | $self->{path} =~ /\.([^.]+)$/; |
482 | $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; |
589 | $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; |
483 | $hdr->{"Content-Length"} = $length; |
590 | $hdr->{"Content-Length"} = $length; |
484 | |
591 | |
485 | $self->response(@code, $hdr, ""); |
592 | $self->response (@code, $hdr, ""); |
486 | |
593 | |
487 | if ($self->{method} eq "GET") { |
594 | if ($self->{method} eq "GET") { |
488 | $self->{time} = $::NOW; |
595 | $self->{time} = $::NOW; |
489 | |
|
|
490 | my $fudge = $queue->[0]->waiters; |
|
|
491 | $fudge = $fudge ? ($fudge+1)/$fudge : 1; |
|
|
492 | |
|
|
493 | $queue->[1] *= $fudge; |
|
|
494 | my $transfer = $queue->[0]->guard; |
|
|
495 | |
|
|
496 | if ($fudge != 1) { |
|
|
497 | $queue->[1] /= $fudge; |
|
|
498 | $queue->[1] = $queue->[1] * $::wait_factor |
|
|
499 | + ($::NOW - $self->{time}) * (1 - $::wait_factor); |
|
|
500 | } |
|
|
501 | $self->{time} = $::NOW; |
596 | $self->{written} = 0; |
502 | |
597 | |
503 | $self->{fh}->writable or return; |
598 | my $fh = Coro::AIO::aio_open $self->{path}, Fcntl::O_RDONLY, 0 |
504 | |
|
|
505 | my ($fh, $buf, $r); |
|
|
506 | my $current = $Coro::current; |
|
|
507 | open $fh, "<", $self->{path} |
|
|
508 | or die "$self->{path}: late open failure ($!)"; |
599 | or die "$self->{path}: late open failure ($!)"; |
509 | |
600 | |
510 | $h -= $l - 1; |
601 | $h -= $l - 1; |
511 | |
602 | |
512 | if (0) { |
603 | my $transfer = $queue->start_transfer ($h); |
513 | if ($l) { |
604 | my $locked; |
514 | sysseek $fh, $l, 0; |
605 | my $bufsize = $::WAIT_BUFSIZE; # initial buffer size |
515 | } |
|
|
516 | } |
|
|
517 | |
606 | |
518 | while ($h > 0) { |
607 | while ($h > 0) { |
519 | if (0) { |
608 | Coro::cede; |
520 | sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h |
609 | my $transfer_lock = $TRANSFER_LOCK->guard ($self->{remote_id}); |
|
|
610 | |
|
|
611 | unless ($locked) { |
|
|
612 | if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) { |
|
|
613 | $bufsize = $::BUFSIZE; |
|
|
614 | $self->{time} = $::NOW; |
|
|
615 | $self->{written} = 0; |
|
|
616 | } |
|
|
617 | } |
|
|
618 | |
|
|
619 | if ($blocked{$self->{remote_id}}) { |
|
|
620 | $self->{h}{connection} = "close"; |
|
|
621 | die bless {}, err::; |
|
|
622 | } |
|
|
623 | |
|
|
624 | Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0 |
521 | or last; |
625 | or last; |
522 | } else { |
626 | |
523 | undef $buf; |
627 | $tbf->request (length $buf); |
524 | $aio_requests->down; |
|
|
525 | aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h), |
|
|
526 | $buf, 0, sub { |
|
|
527 | $r = $_[0]; |
|
|
528 | $current->ready; |
|
|
529 | }); |
|
|
530 | &Coro::schedule; |
|
|
531 | $aio_requests->up; |
|
|
532 | last unless $r; |
|
|
533 | } |
|
|
534 | my $w = $self->{fh}->syswrite($buf) |
628 | my $w = $self->{fh}->syswrite ($buf) |
535 | or last; |
629 | or last; |
536 | $::written += $w; |
630 | $::written += $w; |
537 | $self->{written} += $w; |
631 | $self->{written} += $w; |
538 | $l += $r; |
632 | $l += $w; |
539 | } |
633 | } |
540 | |
634 | |
541 | close $fh; |
635 | close $fh; |
542 | } |
636 | } |
543 | } |
637 | } |
544 | |
638 | |
545 | 1; |
639 | 1 |
|
|
640 | |