1 package PVE
::HTTPServer
;
5 use Time
::HiRes
qw(usleep ualarm gettimeofday tv_interval);
6 use Socket
qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
7 use POSIX
qw(strftime EINTR EAGAIN);
12 # use AnyEvent::Strict; # only use this for debugging
13 use AnyEvent
::Util
qw(guard fh_nonblocking WSAEWOULDBLOCK WSAEINPROGRESS);
22 use PVE
::RPCEnvironment
;
27 use HTTP
::Status
qw(:constants);
32 my $limit_max_headers = 30;
33 my $limit_max_header_size = 8*1024;
34 my $limit_max_post = 16*1024;
44 my $baseuri = "/api2";
49 my ($format, $rel_uri) = $abs_uri =~ m/^\Q$baseuri\E\/+(html
|text
|json
|extjs
|png
|htmljs
)(\
/.*)?$/;
50 $rel_uri = '/' if !$rel_uri;
52 return wantarray ?
($rel_uri, $format) : $rel_uri;
56 my ($self, $reqstate) = @_;
58 my $loginfo = $reqstate->{log};
60 # like apache2 common log format
61 # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
63 my $peerip = $reqstate->{peer_host
} || '-';
64 my $userid = $loginfo->{userid
} || '-';
65 my $content_length = defined($loginfo->{content_length
}) ?
$loginfo->{content_length
} : '-';
66 my $code = $loginfo->{code
} || 500;
67 my $requestline = $loginfo->{requestline
} || '-';
68 my $timestr = strftime
("%d/%b/%Y:%H:%M:%S %z", localtime());
70 my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n";
72 $self->write_log($msg);
75 sub log_aborted_request {
76 my ($self, $reqstate, $error) = @_;
78 my $r = $reqstate->{request};
79 return if !$r; # no active request
82 syslog("err
", "problem with client
$reqstate->{peer_host
}; $error");
85 $self->log_request($reqstate);
88 sub client_do_disconnect {
89 my ($self, $reqstate) = @_;
91 if ($reqstate->{tmpfilename}) {
92 unlink $reqstate->{tmpfilename};
93 delete $reqstate->{tmpfilename};
96 my $hdl = delete $reqstate->{hdl};
99 syslog('err', "detected empty handle
");
103 #print "close connection
$hdl\n";
105 shutdown($hdl->{fh}, 1);
107 $hdl->on_drain(undef);
108 $hdl->on_read(undef);
110 $self->{conn_count}--;
112 print "$$: CLOSE FH
" . $hdl->{fh}->fileno() . " CONN
$self->{conn_count
}\n" if $self->{debug};
115 sub finish_response {
116 my ($self, $reqstate) = @_;
118 my $hdl = $reqstate->{hdl};
120 delete $reqstate->{log};
121 delete $reqstate->{request};
122 delete $reqstate->{proto};
123 delete $reqstate->{accept_gzip};
125 if ($reqstate->{tmpfilename}) {
126 unlink $reqstate->{tmpfilename};
127 delete $reqstate->{tmpfilename};
130 if (!$self->{end_loop} && $reqstate->{keep_alive} > 0) {
131 # print "KEEPALIVE
$reqstate->{keep_alive
}\n" if $self->{debug};
133 eval { $self->push_request_header($reqstate); };
137 $hdl->on_drain (sub {
139 $self->client_do_disconnect($reqstate);
147 my ($self, $reqstate, $resp, $mtime, $nocomp) = @_;
149 #print "$$: send response
: " . Dumper($resp);
151 $nocomp = 1 if !$reqstate->{accept_gzip};
153 my $code = $resp->code;
154 my $msg = $resp->message || HTTP::Status::status_message($code);
155 ($msg) = $msg =~m/^(.*)$/m;
156 my $content = $resp->content;
158 if ($code =~ /^(1\d\d|[23]04)$/) {
159 # make sure content we have no content
163 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
165 $reqstate->{log}->{code} = $code;
167 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
168 my $res = "$proto $code $msg\015\012";
171 my $date = HTTP::Date::time2str($ctime);
172 $resp->header('Date' => $date);
174 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
176 $resp->header('Expires' => $date);
177 $resp->header('Cache-Control' => "max-age
=0");
178 $resp->header("Pragma
", "no-cache
");
181 $resp->header('Server' => "pve-api-daemon
/3.0");
186 $content_length = length($content);
188 if (!$nocomp && ($content_length > 1024)) {
189 my $comp = Compress::Zlib::memGzip($content);
190 $resp->header('Content-Encoding', 'gzip');
192 $content_length = length($content);
194 $resp->header("Content-Length
" => $content_length);
195 $reqstate->{log}->{content_length} = $content_length;
198 $resp->remove_header("Content-Length
");
201 if ($reqstate->{keep_alive} > 0) {
202 $resp->push_header('Connection' => 'Keep-Alive');
204 $resp->header('Connection' => 'close');
207 $res .= $resp->headers_as_string("\015\012");
208 #print "SEND
(without content
) $res\n" if $self->{debug};
213 $self->log_request($reqstate, $reqstate->{request});
215 $reqstate->{hdl}->push_write($res);
216 $self->finish_response($reqstate);
220 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
223 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
224 $self->response($reqstate, $resp);
229 sub send_file_start {
230 my ($self, $reqstate, $filename) = @_;
233 # print "SEND FILE
$filename\n";
234 # Note: aio_load() this is not really async unless we use IO::AIO!
237 my $r = $reqstate->{request};
239 my $fh = IO::File->new($filename, '<') ||
241 my $stat = File::stat::stat($fh) ||
244 my $mtime = $stat->mtime;
246 if (my $ifmod = $r->header('if-modified-since')) {
247 my $iftime = HTTP::Date::str2time($ifmod);
248 if ($mtime <= $iftime) {
249 my $resp = HTTP::Response->new(304, "NOT MODIFIED
");
250 $self->response($reqstate, $resp, $mtime);
256 my $len = sysread($fh, $data, $stat->size);
257 die "got short file
\n" if !defined($len) || $len != $stat->size;
260 if ($filename =~ m/\.css$/) {
262 } elsif ($filename =~ m/\.js$/) {
263 $ct = 'application/javascript';
264 } elsif ($filename =~ m/\.png$/) {
266 } elsif ($filename =~ m/\.gif$/) {
268 } elsif ($filename =~ m/\.jar$/) {
269 $ct = 'application/java-archive';
271 die "unable to detect content type
";
274 my $header = HTTP::Headers->new(Content_Type => $ct);
275 my $resp = HTTP::Response->new(200, "OK
", $header, $data);
276 $self->response($reqstate, $resp, $mtime);
279 $self->error($reqstate, 501, $err);
287 my ($self, $reqstate, $clientip, $host, $method, $uri, $ticket, $token, $params) = @_;
292 if ($host eq 'localhost') {
293 $target = "http
://$host:85$uri";
294 # keep alive for localhost is not worth (connection setup is about 0.2ms)
297 $target = "https
://$host:8006$uri";
301 PVEDisableProxy => 'true',
302 PVEClientIP => $clientip,
305 my $cookie_name = 'PVEAuthCookie';
307 $headers->{'cookie'} = PVE::REST::create_auth_cookie($ticket) if $ticket;
308 $headers->{'CSRFPreventionToken'} = $token if $token;
309 $headers->{'Accept-Encoding'} = 'gzip' if $reqstate->{accept_gzip};
313 if ($method eq 'POST' || $method eq 'PUT') {
314 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
315 # use URI object to format application/x-www-form-urlencoded content.
316 my $url = URI->new('http:');
317 $url->query_form(%$params);
318 $content = $url->query;
319 if (defined($content)) {
320 $headers->{'Content-Length'} = length($content);
324 my $w; $w = http_request(
329 keepalive => $keep_alive,
331 tls_ctx => $self->{tls_ctx},
333 my ($body, $hdr) = @_;
337 if (!$reqstate->{hdl}) {
338 warn "proxy detected vanished client connection
\n";
343 my $code = delete $hdr->{Status};
344 my $msg = delete $hdr->{Reason};
346 delete $hdr->{HTTPVersion};
347 my $header = HTTP::Headers->new(%$hdr);
348 my $resp = HTTP::Response->new($code, $msg, $header, $body);
349 # Note: disable compression, because body is already compressed
350 $self->response($reqstate, $resp, undef, 1);
358 # return arrays as \0 separated strings (like CGI.pm)
359 sub decode_urlencoded {
364 return $res if !$data;
366 foreach my $kv (split(/[\&\;]/, $data)) {
367 my ($k, $v) = split(/=/, $kv);
369 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
371 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
373 if (defined(my $old = $res->{$k})) {
374 $res->{$k} = "$old\0$v";
383 my ($r, $method) = @_;
387 if ($method eq 'PUT' || $method eq 'POST') {
388 $params = decode_urlencoded($r->content);
391 my $query_params = decode_urlencoded($r->url->query());
393 foreach my $k (keys %{$query_params}) {
394 $params->{$k} = $query_params->{$k};
397 return PVE::Tools::decode_utf8_parameters($params);
400 sub handle_api2_request {
401 my ($self, $reqstate, $auth, $upload_state) = @_;
404 my $r = $reqstate->{request};
405 my $method = $r->method();
406 my $path = $r->uri->path();
408 my ($rel_uri, $format) = split_abs_uri($path);
410 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
414 #print Dumper($upload_state) if $upload_state;
416 my $rpcenv = $self->{rpcenv};
421 $params = $upload_state->{params};
423 $params = extract_params($r, $method);
426 delete $params->{_dc}; # remove disable cache parameter
428 my $clientip = $reqstate->{peer_host};
430 $rpcenv->init_request();
432 my $res = PVE::REST::rest_handler($rpcenv, $clientip, $method, $rel_uri, $auth, $params);
434 $rpcenv->set_user(undef); # clear after request
438 if ($self->{trusted_env}) {
439 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
443 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
445 $self->proxy_request($reqstate, $clientip, $res->{proxy}, $method,
446 $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params});
451 PVE::REST::prepare_response_data($format, $res);
452 my ($raw, $ct) = PVE::REST::format_response_data($format, $res, $path);
454 my $resp = HTTP::Response->new($res->{status}, $res->{message});
455 $resp->header("Content-Type
" => $ct);
456 $resp->content($raw);
457 $self->response($reqstate, $resp);
460 $self->error($reqstate, 501, $err);
465 my ($self, $reqstate, $auth) = @_;
468 my $r = $reqstate->{request};
469 my $method = $r->method();
470 my $path = $r->uri->path();
472 if ($path =~ m!$baseuri!) {
473 $self->handle_api2_request($reqstate, $auth);
477 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
478 if (ref($handler) eq 'CODE') {
479 my $params = decode_urlencoded($r->url->query());
480 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
481 $self->response($reqstate, $resp);
482 } elsif (ref($handler) eq 'HASH') {
483 if (my $filename = $handler->{file}) {
484 my $fh = IO::File->new($filename) ||
485 die "unable to
open file
'$filename' - $!\n";
486 send_file_start($self, $reqstate, $filename);
488 die "internal error
- no handler
";
491 die "internal error
- no handler
";
496 if ($self->{dirs} && ($method eq 'GET')) {
497 # we only allow simple names
498 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
499 my ($subdir, $file) = ($1, $2);
500 if (my $dir = $self->{dirs}->{$subdir}) {
501 my $filename = "$dir$file";
502 my $fh = IO::File->new($filename) ||
503 die "unable to
open file
'$filename' - $!\n";
504 send_file_start($self, $reqstate, $filename);
510 die "no such file
'$path'";
513 $self->error($reqstate, 501, $err);
517 sub file_upload_multipart {
518 my ($self, $reqstate, $auth, $rstate) = @_;
521 my $boundary = $rstate->{boundary};
522 my $hdl = $reqstate->{hdl};
524 my $startlen = length($hdl->{rbuf});
526 if ($rstate->{phase} == 0) { # skip everything until start
527 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
528 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
530 my ($ct, $disp, $name, $filename);
531 foreach my $line (split(/\015?\012/, $header)) {
532 # assume we have single line headers
533 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
534 $ct = parse_content_type($1);
535 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
536 ($disp, $name, $filename) = parse_content_disposition($1);
540 if (!($disp && $disp eq 'form-data' && $name)) {
541 syslog('err', "wrong content disposition
in multipart
- abort upload
");
542 $rstate->{phase} = -1;
545 $rstate->{fieldname} = $name;
548 if ($name eq 'filename') {
549 # found file upload data
550 $rstate->{phase} = 1;
551 $rstate->{filename} = $filename;
553 syslog('err', "wrong field name
for file upload
- abort upload
");
554 $rstate->{phase} = -1;
557 # found form data for field $name
558 $rstate->{phase} = 2;
562 my $len = length($hdl->{rbuf});
563 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
564 if $len > $rstate->{maxheader}; # skip garbage
566 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
567 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
568 my ($rest, $eof) = ($1, $3);
569 my $len = length($rest);
570 die "write to temporary file failed
- $!"
571 if syswrite($rstate->{outfh}, $rest) != $len;
572 $rstate->{ctx}->add($rest);
573 $rstate->{params}->{filename} = $rstate->{filename};
574 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
575 $rstate->{bytes} += $len;
576 $rstate->{phase} = $eof ? 100 : 0;
578 my $len = length($hdl->{rbuf});
579 my $wlen = $len - $rstate->{boundlen};
581 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
582 die "write to temporary file failed
- $!"
583 if syswrite($rstate->{outfh}, $data) != $wlen;
584 $rstate->{bytes} += $wlen;
585 $rstate->{ctx}->add($data);
588 } elsif ($rstate->{phase} == 2) { # inside normal field
590 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
591 my ($rest, $eof) = ($1, $3);
592 my $len = length($rest);
593 $rstate->{post_size} += $len;
594 if ($rstate->{post_size} < $limit_max_post) {
595 $rstate->{params}->{$rstate->{fieldname}} = $rest;
596 $rstate->{phase} = $eof ? 100 : 0;
598 syslog('err', "form data to large
- abort upload
");
599 $rstate->{phase} = -1; # skip
603 my $len = length($hdl->{rbuf});
604 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
607 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
609 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
610 $rstate->{done} = 1; # make sure we dont get called twice
611 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
612 die "upload failed
\n";
614 my $elapsed = tv_interval($rstate->{starttime});
616 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
617 syslog('info', "multipart upload complete
" .
618 "(size
: %d time: %ds rate
: %.2fMiB
/s md5sum
: $rstate->{md5sum
})",
619 $rstate->{bytes}, $elapsed, $rate);
620 $self->handle_api2_request($reqstate, $auth, $rstate);
626 $self->error($reqstate, 501, $err);
630 sub parse_content_type {
633 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
635 foreach my $v (@params) {
636 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
637 return wantarray ? ($ct, $1) : $ct;
641 return wantarray ? ($ct) : $ct;
644 sub parse_content_disposition {
647 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
651 foreach my $v (@params) {
652 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
654 $name =~ s/^"(.*)"$/$1/;
655 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
657 $filename =~ s/^"(.*)"$/$1/;
661 return wantarray ? ($disp, $name, $filename) : $disp;
664 my $tmpfile_seq_no = 0;
666 sub get_upload_filename {
667 # choose unpredictable tmpfile name
670 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
673 sub unshift_read_header {
674 my ($self, $reqstate, $state) = @_;
676 $state = { size => 0, count => 0 } if !$state;
678 $reqstate->{hdl}->unshift_read(line => sub {
679 my ($hdl, $line) = @_;
682 # print "$$: got header
: $line\n" if $self->{debug};
684 die "to many http header lines
\n" if ++$state->{count} >= $limit_max_headers;
685 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
687 my $r = $reqstate->{request};
690 my $path = $r->uri->path();
691 my $method = $r->method();
693 $r->push_header($state->{key}, $state->{val})
696 if (!$known_methods->{$method}) {
697 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
698 $self->response($reqstate, $resp);
702 my $conn = $r->header('Connection');
703 my $accept_enc = $r->header('Accept-Encoding');
704 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
707 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
709 if ($reqstate->{proto}->{ver} < 1001) {
710 $reqstate->{keep_alive} = 0;
714 my $te = $r->header('Transfer-Encoding');
715 if ($te && lc($te) eq 'chunked') {
716 # Handle chunked transfer encoding
717 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
720 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
724 my $pveclientip = $r->header('PVEClientIP');
726 # fixme: how can we make PVEClientIP header trusted?
727 if ($self->{trusted_env} && $pveclientip) {
728 $reqstate->{peer_host} = $pveclientip;
730 $r->header('PVEClientIP', $reqstate->{peer_host});
733 my $len = $r->header('Content-Length');
735 # header processing complete - authenticate now
738 if ($path =~ m!$baseuri!) {
739 my $token = $r->header('CSRFPreventionToken');
740 my $cookie = $r->header('Cookie');
741 my $ticket = PVE::REST::extract_auth_cookie($cookie);
743 my ($rel_uri, $format) = split_abs_uri($path);
745 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
750 $auth = PVE::REST::auth_handler($self->{rpcenv}, $reqstate->{peer_host}, $method,
751 $rel_uri, $ticket, $token);
754 $self->error($reqstate, HTTP_UNAUTHORIZED, $err);
759 $reqstate->{log}->{userid} = $auth->{userid};
763 if (!($method eq 'PUT' || $method eq 'POST')) {
764 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
768 my $ctype = $r->header('Content-Type');
769 my ($ct, $boundary) = parse_content_type($ctype) if $ctype;
771 if ($auth->{isUpload} && !$self->{trusted_env}) {
772 die "upload
'Content-Type '$ctype' not implemented\n"
773 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
775 die "upload without content length header not supported" if !$len;
777 die "upload without content length header not supported" if !$len;
779 print "start upload $path $ct $boundary\n" if $self->{debug};
781 my $tmpfilename = get_upload_filename();
782 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
783 die "unable to create temporary upload file '$tmpfilename'";
785 $reqstate->{keep_alive} = 0;
787 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
791 boundary => $boundary,
792 ctx => Digest::MD5->new,
793 boundlen => $boundlen,
794 maxheader => 2048 + $boundlen, # should be large enough
795 params => decode_urlencoded($r->url->query()),
799 starttime => [gettimeofday],
802 $reqstate->{tmpfilename} = $tmpfilename;
803 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $state); });
807 if ($len > $limit_max_post) {
808 $self->error($reqstate, 501, "for data too large");
812 if (!$ct || $ct eq 'application
/x-www-form-urlencoded
') {
813 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
814 my ($hdl, $data) = @_;
816 $self->handle_request($reqstate, $auth);
819 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
822 $self->handle_request($reqstate, $auth);
824 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
825 $r->push_header($state->{key}, $state->{val}) if $state->{key};
826 ($state->{key}, $state->{val}) = ($1, $2);
827 $self->unshift_read_header($reqstate, $state);
828 } elsif ($line =~ /^\s+(.*)/) {
829 $state->{val} .= " $1";
830 $self->unshift_read_header($reqstate, $state);
832 $self->error($reqstate, 506, "unable to parse request header
");
839 sub push_request_header {
840 my ($self, $reqstate) = @_;
843 $reqstate->{hdl}->push_read(line => sub {
844 my ($hdl, $line) = @_;
847 # print "got request header
: $line\n" if $self->{debug};
849 $reqstate->{keep_alive}--;
851 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
852 my ($method, $uri, $maj, $min) = ($1, $2, $3, $4);
855 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
859 $self->{request_count}++; # only count valid request headers
860 if ($self->{request_count} >= $self->{max_requests}) {
861 $self->{end_loop} = 1;
863 $reqstate->{log} = { requestline => $line };
864 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
865 $reqstate->{proto}->{maj} = $maj;
866 $reqstate->{proto}->{min} = $min;
867 $reqstate->{proto}->{ver} = $maj*1000+$min;
868 $reqstate->{request} = HTTP::Request->new($method, $uri);
870 $self->unshift_read_header($reqstate);
871 } elsif ($line eq '') {
872 # ignore empty lines before requests (browser bugs?)
873 $self->push_request_header($reqstate);
875 $self->error($reqstate, 400, 'bad request');
889 return if $self->{end_loop};
891 # we need to m make sure that only one process calls accept
892 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
894 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
900 while (!$self->{end_loop} &&
901 !defined($clientfh = $self->{socket}->accept()) &&
904 if ($self->{end_loop}) {
907 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
908 if (!defined($clientfh)) {
909 $errmsg = "failed to
accept connection
: $!\n";
915 flock($self->{lockfh}, Fcntl::LOCK_UN());
917 if (!defined($clientfh)) {
919 die $errmsg if $errmsg;
922 fh_nonblocking $clientfh, 1;
924 $self->{conn_count}++;
932 $self->{end_loop} = 1;
934 undef $self->{socket_watch};
936 if ($self->{conn_count} <= 0) {
937 $self->{end_cond}->send(1);
941 # else we need to wait until all open connections gets closed
942 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
944 # todo: test for active connections instead (we can abort idle connections)
945 if ($self->{conn_count} <= 0) {
947 $self->{end_cond}->send(1);
955 sub check_host_access {
956 my ($self, $clientip) = @_;
958 my $cip = Net::IP->new($clientip);
963 if ($self->{allow_from}) {
964 foreach my $t (@{$self->{allow_from}}) {
965 if ($t->overlaps($cip)) {
972 if ($self->{deny_from}) {
973 foreach my $t (@{$self->{deny_from}}) {
974 if ($t->overlaps($cip)) {
981 if ($match_allow == $match_deny) {
982 # match both allow and deny, or no match
983 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
989 sub accept_connections {
994 while (my $clientfh = $self->accept()) {
996 my $reqstate = { keep_alive => $self->{keep_alive} };
998 # stop keep-alive when there are many open connections
999 if ($self->{conn_count} >= $self->{max_conn_soft_limit}) {
1000 $reqstate->{keep_alive} = 0;
1003 if (my $sin = getpeername($clientfh)) {
1004 my ($pport, $phost) = Socket::unpack_sockaddr_in($sin);
1005 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntoa($phost));
1008 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1009 print "$$: ABORT request from
$reqstate->{peer_host
} - access denied
\n" if $self->{debug};
1010 $reqstate->{log}->{code} = 403;
1011 $self->log_request($reqstate);
1015 $reqstate->{hdl} = AnyEvent::Handle->new(
1017 rbuf_max => 64*1024,
1018 timeout => $self->{timeout},
1019 linger => 0, # avoid problems with ssh - really needed ?
1023 $self->log_aborted_request($reqstate);
1024 $self->client_do_disconnect($reqstate);
1026 if (my $err = $@) { syslog('err', $err); }
1029 my ($hdl, $fatal, $message) = @_;
1031 $self->log_aborted_request($reqstate, $message);
1032 $self->client_do_disconnect($reqstate);
1034 if (my $err = $@) { syslog('err', "$err"); }
1036 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1038 print "$$: ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}\n" if $self->{debug};
1040 $self->push_request_header($reqstate);
1045 syslog('err', $err);
1046 $self->{end_loop} = 1;
1049 $self->wait_end_loop() if $self->{end_loop};
1052 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1053 # because we write from multiple processes, and that would arbitrarily mix output
1055 sub open_access_log {
1056 my ($self, $filename) = @_;
1058 my $old_mask = umask(0137);;
1059 my $logfh = IO::File->new($filename, ">>") ||
1060 die "unable to
open log file
'$filename' - $!\n";
1063 $logfh->autoflush(1);
1065 $self->{logfh} = $logfh;
1069 my ($self, $data) = @_;
1071 return if !defined($self->{logfh}) || !$data;
1073 my $res = $self->{logfh}->print($data);
1076 delete $self->{logfh};
1077 syslog('err', "error writing access
log");
1078 $self->{end_loop} = 1; # terminate asap
1082 sub atfork_handler {
1086 # something else do to ?
1087 close($self->{socket});
1093 my ($this, %args) = @_;
1095 my $class = ref($this) || $this;
1097 foreach my $req (qw(socket lockfh lockfile)) {
1098 die "misssing required argument '$req'" if !defined($args{$req});
1101 my $self = bless { %args }, $class;
1104 PVE
::INotify
::inotify_init
();
1106 $self->{rpcenv
} = PVE
::RPCEnvironment-
>init(
1107 $self->{trusted_env
} ?
'priv' : 'pub', atfork
=> sub { $self-> atfork_handler
() });
1109 fh_nonblocking
($self->{socket}, 1);
1111 $self->{end_loop
} = 0;
1112 $self->{conn_count
} = 0;
1113 $self->{request_count
} = 0;
1114 $self->{timeout
} = 5 if !$self->{timeout
};
1115 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1116 $self->{max_conn
} = 800 if !$self->{max_conn
};
1117 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1119 $self->{policy
} = 'allow' if !$self->{policy
};
1121 $self->{end_cond
} = AnyEvent-
>condvar;
1124 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
1127 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
1129 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
1131 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
1133 if ($self->{conn_count
} >= $self->{max_conn
}) {
1134 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
1135 if ($self->{conn_count
} < $self->{max_conn
}) {
1137 $self->accept_connections();
1141 $self->accept_connections();
1147 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
1148 undef $self->{term_watch
};
1149 $self->wait_end_loop();
1152 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
1153 undef $self->{quit_watch
};
1154 $self->wait_end_loop();
1157 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
1158 PVE
::INotify
::poll
(); # read inotify events
1167 $self->{end_cond
}->recv;