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