1 package PVE
::APIServer
::AnyEvent
;
3 # Note 1: interactions with Crypt::OpenSSL::RSA
5 # Some handlers (auth_handler) use Crypt::OpenSSL::RSA, which seems to
6 # set the openssl error variable. We need to clear that here, else
7 # AnyEvent::TLS aborts the connection.
8 # Net::SSLeay::ERR_clear_error();
12 use Time
::HiRes
qw(usleep ualarm gettimeofday tv_interval);
13 use Socket
qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
14 use POSIX
qw(strftime EINTR EAGAIN);
22 # use AnyEvent::Strict; # only use this for debugging
23 use AnyEvent
::Util
qw(guard fh_nonblocking WSAEWOULDBLOCK WSAEINPROGRESS);
36 use PVE
::APIServer
::Formatter
;
37 use PVE
::APIServer
::Utils
;
42 use HTTP
::Status
qw(:constants);
50 my $limit_max_headers = 64;
51 my $limit_max_header_size = 8*1024;
52 my $limit_max_post = 64*1024;
61 my $split_abs_uri = sub {
62 my ($abs_uri, $base_uri) = @_;
64 my ($format, $rel_uri) = $abs_uri =~ m/^\Q$base_uri\E\/+([a-z
][a-z0-9
]+)(\
/.*)?$/;
65 $rel_uri = '/' if !$rel_uri;
67 return wantarray ?
($rel_uri, $format) : $rel_uri;
71 my ($self, $message) = @_;
73 return if !$self->{debug
};
75 my ($pkg, $pkgfile, $line, $sub) = caller(1);
76 $sub =~ s/^(?:.+::)+//;
77 print "worker[$$]: $pkg +$line: $sub: $message\n";
81 my ($self, $reqstate) = @_;
83 my $loginfo = $reqstate->{log};
85 # like apache2 common log format
86 # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
88 return if $loginfo->{written
}; # avoid duplicate logs
89 $loginfo->{written
} = 1;
91 my $peerip = $reqstate->{peer_host
} || '-';
92 my $userid = $loginfo->{userid
} || '-';
93 my $content_length = defined($loginfo->{content_length
}) ?
$loginfo->{content_length
} : '-';
94 my $code = $loginfo->{code
} || 500;
95 my $requestline = $loginfo->{requestline
} || '-';
96 my $timestr = strftime
("%d/%m/%Y:%H:%M:%S %z", localtime());
98 my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n";
100 $self->write_log($msg);
103 sub log_aborted_request {
104 my ($self, $reqstate, $error) = @_;
106 my $r = $reqstate->{request};
107 return if !$r; # no active request
110 syslog("err
", "problem with client
$reqstate->{peer_host
}; $error");
113 $self->log_request($reqstate);
116 sub cleanup_reqstate {
117 my ($reqstate, $deletetmpfile) = @_;
119 delete $reqstate->{log};
120 delete $reqstate->{request};
121 delete $reqstate->{proto};
122 delete $reqstate->{accept_gzip};
123 delete $reqstate->{starttime};
125 if ($reqstate->{tmpfilename}) {
126 unlink $reqstate->{tmpfilename} if $deletetmpfile;
127 delete $reqstate->{tmpfilename};
131 sub client_do_disconnect {
132 my ($self, $reqstate) = @_;
134 cleanup_reqstate($reqstate, 1);
136 my $shutdown_hdl = sub {
139 shutdown($hdl->{fh}, 1);
141 $hdl->on_drain(undef);
142 $hdl->on_read(undef);
146 if (my $proxyhdl = delete $reqstate->{proxyhdl}) {
147 &$shutdown_hdl($proxyhdl)
148 if !$proxyhdl->{block_disconnect};
151 my $hdl = delete $reqstate->{hdl};
154 syslog('err', "detected empty handle
");
158 $self->dprint("close connection
$hdl");
160 &$shutdown_hdl($hdl);
162 warn "connection count
<= 0!\n" if $self->{conn_count} <= 0;
164 $self->{conn_count}--;
166 $self->dprint("CLOSE FH
" . $hdl->{fh}->fileno() . " CONN
$self->{conn_count
}");
169 sub finish_response {
170 my ($self, $reqstate) = @_;
172 cleanup_reqstate($reqstate, 0);
174 my $hdl = $reqstate->{hdl};
175 return if !$hdl; # already disconnected
177 if (!$self->{end_loop} && $reqstate->{keep_alive} > 0) {
178 # print "KEEPALIVE
$reqstate->{keep_alive
}\n" if $self->{debug};
180 eval { $self->push_request_header($reqstate); };
184 $hdl->on_drain (sub {
186 $self->client_do_disconnect($reqstate);
193 sub response_stream {
194 my ($self, $reqstate, $stream_fh) = @_;
196 # disable timeout, we don't know how big the data is
197 $reqstate->{hdl}->timeout(0);
199 my $buf_size = 4*1024*1024;
204 my $reqhdl = $reqstate->{hdl};
207 my $wbuf_len = length($reqhdl->{wbuf});
208 my $rbuf_len = length($hdl->{rbuf});
209 # TODO: Take into account $reqhdl->{wbuf_max} ? Right now
210 # that's unbounded, so just assume $buf_size
211 my $to_read = $buf_size - $wbuf_len;
212 $to_read = $rbuf_len if $rbuf_len < $to_read;
214 my $data = substr($hdl->{rbuf}, 0, $to_read, '');
215 $reqhdl->push_write($data);
216 $rbuf_len -= $to_read;
217 } elsif ($hdl->{_eof}) {
218 # workaround: AnyEvent gives us a fake EPIPE if we don't consume
219 # any data when called at EOF, so unregister ourselves - data is
220 # flushed by on_eof anyway
221 # see: https://sources.debian.org/src/libanyevent-perl/7.170-2/lib/AnyEvent/Handle.pm/#L1329
226 # apply backpressure so we don't accept any more data into
227 # buffer if the client isn't downloading fast enough
228 # note: read_size can double upon read, and we also need to
229 # account for one more read after start_read, so *4
230 if ($rbuf_len + $hdl->{read_size}*4 > $buf_size) {
231 # stop reading until write buffer is empty
233 my $prev_on_drain = $reqhdl->{on_drain};
234 $reqhdl->on_drain(sub {
236 # on_drain called because write buffer is empty, continue reading
237 $hdl->on_read($on_read);
238 if ($prev_on_drain) {
239 $wrhdl->on_drain($prev_on_drain);
240 $prev_on_drain->($wrhdl);
246 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
248 rbuf_max => $buf_size,
254 if (my $reqhdl = $reqstate->{hdl}) {
255 $self->log_aborted_request($reqstate);
256 # write out any remaining data
257 $reqhdl->push_write($hdl->{rbuf}) if length($hdl->{rbuf}) > 0;
259 $reqhdl->push_shutdown();
260 $self->finish_response($reqstate);
263 if (my $err = $@) { syslog('err', "$err"); }
267 my ($hdl, $fatal, $message) = @_;
269 $self->log_aborted_request($reqstate, $message);
270 $self->client_do_disconnect($reqstate);
272 if (my $err = $@) { syslog('err', "$err"); }
279 my ($self, $reqstate, $resp, $mtime, $nocomp, $delay, $stream_fh) = @_;
281 #print "$$: send response
: " . Dumper($resp);
284 $reqstate->{hdl}->timeout_reset();
285 $reqstate->{hdl}->timeout($self->{timeout});
287 $nocomp = 1 if !$self->{compression};
288 $nocomp = 1 if !$reqstate->{accept_gzip};
290 my $code = $resp->code;
291 my $msg = $resp->message || HTTP::Status::status_message($code);
292 ($msg) = $msg =~m/^(.*)$/m;
293 my $content = $resp->content;
295 if ($code =~ /^(1\d\d|[23]04)$/) {
296 # make sure content we have no content
300 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
302 $reqstate->{log}->{code} = $code;
304 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
305 my $res = "$proto $code $msg\015\012";
308 my $date = HTTP::Date::time2str($ctime);
309 $resp->header('Date' => $date);
311 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
313 $resp->header('Expires' => $date);
314 $resp->header('Cache-Control' => "max-age
=0");
315 $resp->header("Pragma
", "no-cache
");
318 $resp->header('Server' => "pve-api-daemon
/3.0");
321 if ($content && !$stream_fh) {
323 $content_length = length($content);
325 if (!$nocomp && ($content_length > 1024)) {
326 my $comp = Compress::Zlib::memGzip($content);
327 $resp->header('Content-Encoding', 'gzip');
329 $content_length = length($content);
331 $resp->header("Content-Length
" => $content_length);
332 $reqstate->{log}->{content_length} = $content_length;
335 $resp->remove_header("Content-Length
");
338 if ($reqstate->{keep_alive} > 0) {
339 $resp->push_header('Connection' => 'Keep-Alive');
341 $resp->header('Connection' => 'close');
344 $res .= $resp->headers_as_string("\015\012");
345 #print "SEND
(without content
) $res\n" if $self->{debug};
348 $res .= $content if $content && !$stream_fh;
350 $self->log_request($reqstate, $reqstate->{request});
353 # write headers and preamble...
354 $reqstate->{hdl}->push_write($res);
355 # ...then stream data via an AnyEvent::Handle
356 $self->response_stream($reqstate, $stream_fh);
357 } elsif ($delay && $delay > 0) {
358 my $w; $w = AnyEvent->timer(after => $delay, cb => sub {
359 undef $w; # delete reference
360 $reqstate->{hdl}->push_write($res);
361 $self->finish_response($reqstate);
364 $reqstate->{hdl}->push_write($res);
365 $self->finish_response($reqstate);
370 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
373 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
374 $self->response($reqstate, $resp);
379 my $file_extension_info = {
380 css => { ct => 'text/css' },
381 html => { ct => 'text/html' },
382 js => { ct => 'application/javascript' },
383 json => { ct => 'application/json' },
384 map => { ct => 'application/json' },
385 png => { ct => 'image/png' , nocomp => 1 },
386 ico => { ct => 'image/x-icon', nocomp => 1},
387 gif => { ct => 'image/gif', nocomp => 1},
388 svg => { ct => 'image/svg+xml' },
389 jar => { ct => 'application/java-archive', nocomp => 1},
390 woff => { ct => 'application/font-woff', nocomp => 1},
391 woff2 => { ct => 'application/font-woff2', nocomp => 1},
392 ttf => { ct => 'application/font-snft', nocomp => 1},
393 pdf => { ct => 'application/pdf', nocomp => 1},
394 epub => { ct => 'application/epub+zip', nocomp => 1},
395 mp3 => { ct => 'audio/mpeg', nocomp => 1},
396 oga => { ct => 'audio/ogg', nocomp => 1},
397 tgz => { ct => 'application/x-compressed-tar', nocomp => 1},
400 sub send_file_start {
401 my ($self, $reqstate, $download) = @_;
404 # print "SEND FILE
$filename\n";
405 # Note: aio_load() this is not really async unless we use IO::AIO!
408 my $r = $reqstate->{request};
414 if (ref($download) eq 'HASH') {
415 $mime = $download->{'content-type'};
417 if ($download->{path} && $download->{stream} &&
418 $reqstate->{request}->header('PVEDisableProxy'))
420 # avoid double stream from a file, let the proxy handle it
421 die "internal error
: file proxy streaming only available
for pvedaemon
\n"
422 if !$self->{trusted_env};
423 my $header = HTTP::Headers->new(
424 pvestreamfile => $download->{path},
425 Content_Type => $mime,
427 # we need some data so Content-Length gets set correctly and
428 # the proxy doesn't wait for more data - place a canary
429 my $resp = HTTP::Response->new(200, "OK
", $header, "error canary
");
430 $self->response($reqstate, $resp);
434 if (!($fh = $download->{fh})) {
435 my $path = $download->{path};
436 die "internal error
: {download
} returned but neither fh
not path
given\n"
438 sysopen($fh, "$path", O_NONBLOCK | O_RDONLY)
439 or die "open stream path
'$path' for reading failed
: $!\n";
442 if ($download->{stream}) {
443 my $header = HTTP::Headers->new(Content_Type => $mime);
444 my $resp = HTTP::Response->new(200, "OK
", $header);
445 $self->response($reqstate, $resp, undef, 1, 0, $fh);
449 my $filename = $download;
450 $fh = IO::File->new($filename, '<') ||
451 die "unable to
open file
'$filename' - $!\n";
453 my ($ext) = $filename =~ m/\.([^.]*)$/;
454 my $ext_info = $file_extension_info->{$ext};
456 die "unable to detect content type
" if !$ext_info;
457 $mime = $ext_info->{ct};
458 $nocomp = $ext_info->{nocomp};
461 my $stat = File::stat::stat($fh) ||
464 my $mtime = $stat->mtime;
466 if (my $ifmod = $r->header('if-modified-since')) {
467 my $iftime = HTTP::Date::str2time($ifmod);
468 if ($mtime <= $iftime) {
469 my $resp = HTTP::Response->new(304, "NOT MODIFIED
");
470 $self->response($reqstate, $resp, $mtime);
476 my $len = sysread($fh, $data, $stat->size);
477 die "got short file
\n" if !defined($len) || $len != $stat->size;
479 my $header = HTTP::Headers->new(Content_Type => $mime);
480 my $resp = HTTP::Response->new(200, "OK
", $header, $data);
481 $self->response($reqstate, $resp, $mtime, $nocomp);
484 $self->error($reqstate, 501, $err);
491 sub websocket_proxy {
492 my ($self, $reqstate, $wsaccept, $wsproto, $param) = @_;
498 my $max_payload_size = 128*1024;
500 if ($param->{port}) {
501 $remhost = 'localhost';
502 $remport = $param->{port};
503 } elsif ($param->{socket}) {
505 $remport = $param->{socket};
507 die "websocket_proxy
: missing port
or socket\n";
511 my ($data, $opcode) = @_;
516 $string = $opcode ? $opcode : "\x82"; # binary frame
519 my $payload_len = length($payload);
520 if ($payload_len <= 125) {
521 $string .= pack 'C', $payload_len;
522 } elsif ($payload_len <= 0xffff) {
523 $string .= pack 'C', 126;
524 $string .= pack 'n', $payload_len;
526 $string .= pack 'C', 127;
527 $string .= pack 'Q>', $payload_len;
533 tcp_connect $remhost, $remport, sub {
535 or die "connect to
'$remhost:$remport' failed
: $!";
537 $self->dprint("CONNECTed to
'$remhost:$remport'");
539 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
541 rbuf_max => $max_payload_size,
542 wbuf_max => $max_payload_size*5,
547 $self->log_aborted_request($reqstate);
548 $self->client_do_disconnect($reqstate);
550 if (my $err = $@) { syslog('err', $err); }
553 my ($hdl, $fatal, $message) = @_;
555 $self->log_aborted_request($reqstate, $message);
556 $self->client_do_disconnect($reqstate);
558 if (my $err = $@) { syslog('err', "$err"); }
561 my $proxyhdlreader = sub {
564 my $len = length($hdl->{rbuf});
565 my $data = substr($hdl->{rbuf}, 0, $len > $max_payload_size ? $max_payload_size : $len, '');
567 my $string = $encode->(\$data);
569 $reqstate->{hdl}->push_write($string) if $reqstate->{hdl};
572 my $hdlreader = sub {
575 while (my $len = length($hdl->{rbuf})) {
578 my $hdr = unpack('C', substr($hdl->{rbuf}, 0, 1));
579 my $opcode = $hdr & 0b00001111;
580 my $fin = $hdr & 0b10000000;
582 die "received fragmented websocket frame
\n" if !$fin;
584 my $rsv = $hdr & 0b01110000;
585 die "received websocket frame with RSV flags
\n" if $rsv;
587 my $payload_len = unpack 'C', substr($hdl->{rbuf}, 1, 1);
589 my $masked = $payload_len & 0b10000000;
590 die "received unmasked websocket frame from client
\n" if !$masked;
593 $payload_len = $payload_len & 0b01111111;
594 if ($payload_len == 126) {
596 $payload_len = unpack('n', substr($hdl->{rbuf}, $offset, 2));
598 } elsif ($payload_len == 127) {
600 $payload_len = unpack('Q>', substr($hdl->{rbuf}, $offset, 8));
604 die "received too large websocket frame
(len
= $payload_len)\n"
605 if ($payload_len > $max_payload_size) || ($payload_len < 0);
607 return if $len < ($offset + 4 + $payload_len);
609 my $data = substr($hdl->{rbuf}, 0, $offset + 4 + $payload_len, ''); # now consume data
611 my $mask = substr($data, $offset, 4);
614 my $payload = substr($data, $offset, $payload_len);
616 # NULL-mask might be used over TLS, skip to increase performance
617 if ($mask ne pack('N', 0)) {
618 # repeat 4 byte mask to payload length + up to 4 byte
619 $mask = $mask x (int($payload_len / 4) + 1);
620 # truncate mask to payload length
621 substr($mask, $payload_len) = "";
626 if ($opcode == 1 || $opcode == 2) {
627 $reqstate->{proxyhdl}->push_write($payload) if $reqstate->{proxyhdl};
628 } elsif ($opcode == 8) {
629 my $statuscode = unpack ("n
", $payload);
630 $self->dprint("websocket received
close. status code
: '$statuscode'");
631 if (my $proxyhdl = $reqstate->{proxyhdl}) {
632 $proxyhdl->{block_disconnect} = 1 if length $proxyhdl->{wbuf} > 0;
633 $proxyhdl->push_shutdown();
635 $hdl->push_shutdown();
636 } elsif ($opcode == 9) {
637 # ping received, schedule pong
638 $reqstate->{hdl}->push_write($encode->(\$payload, "\x8A")) if $reqstate->{hdl};
639 } elsif ($opcode == 0xA) {
640 # pong received, continue
642 die "received unhandled websocket opcode
$opcode\n";
647 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.1';
649 $reqstate->{proxyhdl}->timeout(0);
650 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
651 $reqstate->{hdl}->on_read($hdlreader);
653 # todo: use stop_read/start_read if write buffer grows to much
655 # FIXME: remove protocol in PVE/PMG 8.x
657 # for backwards, compatibility, we have to reply with the websocket
658 # subprotocol from the request
659 my $res = "$proto 101 Switching Protocols
\015\012" .
660 "Upgrade
: websocket
\015\012" .
661 "Connection
: upgrade
\015\012" .
662 "Sec-WebSocket-Accept
: $wsaccept\015\012" .
663 ($wsproto ne "" ? "Sec-WebSocket-Protocol
: $wsproto\015\012" : "") .
668 $reqstate->{hdl}->push_write($res);
671 $reqstate->{log}->{code} = 101;
672 $self->log_request($reqstate);
678 $self->log_aborted_request($reqstate, $err);
679 $self->client_do_disconnect($reqstate);
684 my ($self, $reqstate, $clientip, $host, $node, $method, $uri, $auth, $params) = @_;
689 if ($host eq 'localhost') {
690 $target = "http
://$host:85$uri";
691 # keep alive for localhost is not worth (connection setup is about 0.2ms)
693 } elsif (Net::IP::ip_is_ipv6($host)) {
694 $target = "https
://[$host]:8006$uri";
696 $target = "https
://$host:8006$uri";
700 PVEDisableProxy => 'true',
701 PVEClientIP => $clientip,
704 $headers->{'cookie'} = PVE::APIServer::Formatter::create_auth_cookie($auth->{ticket}, $self->{cookie_name})
706 $headers->{'Authorization'} = PVE::APIServer::Formatter::create_auth_header($auth->{api_token}, $self->{apitoken_name})
707 if $auth->{api_token};
708 $headers->{'CSRFPreventionToken'} = $auth->{token}
710 $headers->{'Accept-Encoding'} = 'gzip' if ($reqstate->{accept_gzip} && $self->{compression});
712 if (defined(my $host = $reqstate->{request}->header('Host'))) {
713 $headers->{Host} = $host;
718 if ($method eq 'POST' || $method eq 'PUT') {
719 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
720 # use URI object to format application/x-www-form-urlencoded content.
721 my $url = URI->new('http:');
722 $url->query_form(%$params);
723 $content = $url->query;
724 if (defined($content)) {
725 $headers->{'Content-Length'} = length($content);
730 # TLS 1.x only, with certificate pinning
736 my (undef, undef, undef, $depth, undef, undef, $cert) = @_;
737 # we don't care about intermediate or root certificates
738 return 1 if $depth != 0;
739 # check server certificate against cache of pinned FPs
740 return $self->check_cert_fingerprint($cert);
744 # load and cache cert fingerprint if first time we proxy to this node
745 $self->initialize_cert_cache($node);
747 my $w; $w = http_request(
752 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
753 keepalive => $keep_alive,
755 tls_ctx => AnyEvent::TLS->new(%{$tls}),
757 my ($body, $hdr) = @_;
761 if (!$reqstate->{hdl}) {
762 warn "proxy detected vanished client connection
\n";
767 my $code = delete $hdr->{Status};
768 my $msg = delete $hdr->{Reason};
769 my $stream = delete $hdr->{pvestreamfile};
771 delete $hdr->{HTTPVersion};
772 my $header = HTTP::Headers->new(%$hdr);
773 if (my $location = $header->header('Location')) {
774 $location =~ s|^http://localhost:85||;
775 $header->header(Location => $location);
778 sysopen(my $fh, "$stream", O_NONBLOCK | O_RDONLY)
779 or die "open stream path
'$stream' for forwarding failed
: $!\n";
780 my $resp = HTTP::Response->new($code, $msg, $header, undef);
781 $self->response($reqstate, $resp, undef, 1, 0, $fh);
783 my $resp = HTTP::Response->new($code, $msg, $header, $body);
784 # Note: disable compression, because body is already compressed
785 $self->response($reqstate, $resp, undef, 1);
794 # return arrays as \0 separated strings (like CGI.pm)
795 # assume data is UTF8 encoded
796 sub decode_urlencoded {
801 return $res if !$data;
803 foreach my $kv (split(/[\&\;]/, $data)) {
804 my ($k, $v) = split(/=/, $kv);
806 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
810 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
812 $v = Encode::decode('utf8', $v);
814 if (defined(my $old = $res->{$k})) {
825 my ($r, $method) = @_;
829 if ($method eq 'PUT' || $method eq 'POST') {
831 if (my $ctype = $r->header('Content-Type')) {
832 $ct = parse_content_type($ctype);
834 if (defined($ct) && $ct eq 'application/json') {
835 $params = decode_json($r->content);
837 $params = decode_urlencoded($r->content);
841 my $query_params = decode_urlencoded($r->url->query());
843 foreach my $k (keys %{$query_params}) {
844 $params->{$k} = $query_params->{$k};
850 sub handle_api2_request {
851 my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
854 my $r = $reqstate->{request};
856 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
858 my $formatter = PVE::APIServer::Formatter::get_formatter($format, $method, $rel_uri);
860 if (!defined($formatter)) {
861 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no formatter
for uri
$rel_uri, $format");
865 #print Dumper($upload_state) if $upload_state;
870 $params = $upload_state->{params};
872 $params = extract_params($r, $method);
875 delete $params->{_dc}; # remove disable cache parameter
877 my $clientip = $reqstate->{peer_host};
879 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
882 Net::SSLeay::ERR_clear_error();
884 AnyEvent->now_update(); # in case somebody called sleep()
886 my $upgrade = $r->header('upgrade');
887 $upgrade = lc($upgrade) if $upgrade;
889 if (my $host = $res->{proxy}) {
891 if ($self->{trusted_env}) {
892 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
896 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
897 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
901 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
903 $self->proxy_request($reqstate, $clientip, $host, $res->{proxynode}, $method,
904 $r->uri, $auth, $res->{proxy_params});
907 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
908 die "unable to upgrade to protocol
'$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
909 my $wsver = $r->header('sec-websocket-version');
910 die "unsupported websocket-version
'$wsver'\n" if !$wsver || ($wsver ne '13');
911 my $wsproto = $r->header('sec-websocket-protocol') // "";
912 my $wskey = $r->header('sec-websocket-key');
913 die "missing websocket-key
\n" if !$wskey;
914 # Note: Digest::SHA::sha1_base64 has wrong padding
915 my $wsaccept = Digest::SHA::sha1_base64("${wskey
}258EAFA5-E914-47DA-95CA-C5AB0DC85B11
") . "=";
916 if ($res->{status} == HTTP_OK) {
917 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
923 if ($res->{status} == HTTP_UNAUTHORIZED) {
924 # always delay unauthorized calls by 3 seconds
925 $delay = 3 - tv_interval($reqstate->{starttime});
926 $delay = 0 if $delay < 0;
929 my $download = $res->{download};
930 $download //= $res->{data}->{download}
931 if defined($res->{data}) && ref($res->{data}) eq 'HASH';
932 if (defined($download)) {
933 send_file_start($self, $reqstate, $download);
937 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
938 $auth, $self->{formatter_config});
941 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
944 $resp = HTTP::Response->new($res->{status}, $res->{message});
945 $resp->header("Content-Type
" => $ct);
946 $resp->content($raw);
948 $self->response($reqstate, $resp, undef, $nocomp, $delay);
951 $self->error($reqstate, 501, $err);
955 sub handle_spice_proxy_request {
956 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
960 my ($minport, $maxport) = PVE::Tools::spice_port_range();
961 if ($spiceport < $minport || $spiceport > $maxport) {
962 die "SPICE Port
$spiceport is not in allowed range
($minport, $maxport)\n";
965 my $clientip = $reqstate->{peer_host};
966 my $r = $reqstate->{request};
970 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
971 $remip = $self->remote_node_ip($node);
972 $self->dprint("REMOTE CONNECT
$vmid, $remip, $connect_str");
974 $self->dprint("CONNECT
$vmid, $node, $spiceport");
977 if ($remip && $r->header('PVEDisableProxy')) {
978 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
982 $reqstate->{hdl}->timeout(0);
983 $reqstate->{hdl}->wbuf_max(64*10*1024);
985 my $remhost = $remip ? $remip : "localhost
";
986 my $remport = $remip ? 3128 : $spiceport;
988 tcp_connect $remhost, $remport, sub {
990 or die "connect to
'$remhost:$remport' failed
: $!";
992 $self->dprint("CONNECTed to
'$remhost:$remport'");
993 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
996 wbuf_max => 64*10*1024,
1001 $self->log_aborted_request($reqstate);
1002 $self->client_do_disconnect($reqstate);
1004 if (my $err = $@) { syslog('err', $err); }
1007 my ($hdl, $fatal, $message) = @_;
1009 $self->log_aborted_request($reqstate, $message);
1010 $self->client_do_disconnect($reqstate);
1012 if (my $err = $@) { syslog('err', "$err"); }
1016 my $proxyhdlreader = sub {
1019 my $len = length($hdl->{rbuf});
1020 my $data = substr($hdl->{rbuf}, 0, $len, '');
1022 #print "READ1
$len\n";
1023 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
1026 my $hdlreader = sub {
1029 my $len = length($hdl->{rbuf});
1030 my $data = substr($hdl->{rbuf}, 0, $len, '');
1032 #print "READ0
$len\n";
1033 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
1036 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
1038 my $startproxy = sub {
1039 $reqstate->{proxyhdl}->timeout(0);
1040 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
1041 $reqstate->{hdl}->on_read($hdlreader);
1043 # todo: use stop_read/start_read if write buffer grows to much
1045 # a response must be followed by an empty line
1046 my $res = "$proto 200 OK
\015\012\015\012";
1047 $reqstate->{hdl}->push_write($res);
1050 $reqstate->{log}->{code} = 200;
1051 $self->log_request($reqstate);
1055 my $header = "CONNECT
${connect_str
} $proto\015\012" .
1056 "Host
: ${connect_str
}\015\012" .
1057 "Proxy-Connection
: keep-alive
\015\012" .
1058 "User-Agent
: spiceproxy
\015\012" .
1059 "PVEDisableProxy
: true
\015\012" .
1060 "PVEClientIP
: $clientip\015\012" .
1063 $reqstate->{proxyhdl}->push_write($header);
1064 $reqstate->{proxyhdl}->push_read(line => sub {
1065 my ($hdl, $line) = @_;
1067 if ($line =~ m!^$proto 200 OK$!) {
1068 # read the empty line after the 200 OK
1069 $reqstate->{proxyhdl}->unshift_read(line => sub{
1073 $reqstate->{hdl}->push_write($line);
1074 $self->client_do_disconnect($reqstate);
1085 $self->log_aborted_request($reqstate, $err);
1086 $self->client_do_disconnect($reqstate);
1090 sub handle_request {
1091 my ($self, $reqstate, $auth, $method, $path) = @_;
1093 my $base_uri = $self->{base_uri};
1096 my $r = $reqstate->{request};
1098 # disable timeout on handle (we already have all data we need)
1099 # we re-enable timeout in response()
1100 $reqstate->{hdl}->timeout(0);
1102 if ($path =~ m/^\Q$base_uri\E/) {
1103 $self->handle_api2_request($reqstate, $auth, $method, $path);
1107 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
1108 if (ref($handler) eq 'CODE') {
1109 my $params = decode_urlencoded($r->url->query());
1110 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
1112 Net::SSLeay::ERR_clear_error();
1113 $self->response($reqstate, $resp);
1114 } elsif (ref($handler) eq 'HASH') {
1115 if (my $filename = $handler->{file}) {
1116 my $fh = IO::File->new($filename) ||
1117 die "unable to
open file
'$filename' - $!\n";
1118 send_file_start($self, $reqstate, $filename);
1120 die "internal error
- no handler
";
1123 die "internal error
- no handler
";
1128 if ($self->{dirs} && ($method eq 'GET')) {
1129 # we only allow simple names
1130 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
1131 my ($subdir, $file) = ($1, $2);
1132 if (my $dir = $self->{dirs}->{$subdir}) {
1133 my $filename = "$dir$file";
1134 my $fh = IO::File->new($filename) ||
1135 die "unable to
open file
'$filename' - $!\n";
1136 send_file_start($self, $reqstate, $filename);
1142 die "no such file
'$path'\n";
1145 $self->error($reqstate, 501, $err);
1149 sub file_upload_multipart {
1150 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
1153 my $boundary = $rstate->{boundary};
1154 my $hdl = $reqstate->{hdl};
1156 my $startlen = length($hdl->{rbuf});
1158 if ($rstate->{phase} == 0) { # skip everything until start
1159 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
1160 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
1162 my ($ct, $disp, $name, $filename);
1163 foreach my $line (split(/\015?\012/, $header)) {
1164 # assume we have single line headers
1165 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
1166 $ct = parse_content_type($1);
1167 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
1168 ($disp, $name, $filename) = parse_content_disposition($1);
1172 if (!($disp && $disp eq 'form-data' && $name)) {
1173 syslog('err', "wrong content disposition
in multipart
- abort upload
");
1174 $rstate->{phase} = -1;
1177 $rstate->{fieldname} = $name;
1180 if ($name eq 'filename') {
1181 # found file upload data
1182 $rstate->{phase} = 1;
1183 $rstate->{filename} = $filename;
1185 syslog('err', "wrong field name
for file upload
- abort upload
");
1186 $rstate->{phase} = -1;
1189 # found form data for field $name
1190 $rstate->{phase} = 2;
1194 my $len = length($hdl->{rbuf});
1195 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
1196 if $len > $rstate->{maxheader}; # skip garbage
1198 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
1199 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1200 my ($rest, $eof) = ($1, $3);
1201 my $len = length($rest);
1202 die "write to temporary file failed
- $!"
1203 if syswrite($rstate->{outfh}, $rest) != $len;
1204 $rstate->{ctx}->add($rest);
1205 $rstate->{params}->{filename} = $rstate->{filename};
1206 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
1207 $rstate->{bytes} += $len;
1208 $rstate->{phase} = $eof ? 100 : 0;
1210 my $len = length($hdl->{rbuf});
1211 my $wlen = $len - $rstate->{boundlen};
1213 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
1214 die "write to temporary file failed
- $!"
1215 if syswrite($rstate->{outfh}, $data) != $wlen;
1216 $rstate->{bytes} += $wlen;
1217 $rstate->{ctx}->add($data);
1220 } elsif ($rstate->{phase} == 2) { # inside normal field
1222 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1223 my ($rest, $eof) = ($1, $3);
1224 my $len = length($rest);
1225 $rstate->{post_size} += $len;
1226 if ($rstate->{post_size} < $limit_max_post) {
1227 $rstate->{params}->{$rstate->{fieldname}} = $rest;
1228 $rstate->{phase} = $eof ? 100 : 0;
1230 syslog('err', "form data to large
- abort upload
");
1231 $rstate->{phase} = -1; # skip
1235 my $len = length($hdl->{rbuf});
1236 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
1239 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
1241 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
1242 $rstate->{done} = 1; # make sure we dont get called twice
1243 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
1244 die "upload failed
\n";
1246 my $elapsed = tv_interval($rstate->{starttime});
1248 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
1249 syslog('info', "multipart upload complete
" .
1250 "(size
: %d time: %ds rate
: %.2fMiB
/s md5sum
: $rstate->{md5sum
})",
1251 $rstate->{bytes}, $elapsed, $rate);
1252 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1257 syslog('err', $err);
1258 $self->error($reqstate, 501, $err);
1262 sub parse_content_type {
1265 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
1267 foreach my $v (@params) {
1268 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1269 return wantarray ? ($ct, $1) : $ct;
1273 return wantarray ? ($ct) : $ct;
1276 sub parse_content_disposition {
1279 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
1283 foreach my $v (@params) {
1284 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
1286 $name =~ s/^"(.*)"$/$1/;
1287 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
1289 $filename =~ s/^"(.*)"$/$1/;
1293 return wantarray ? ($disp, $name, $filename) : $disp;
1296 my $tmpfile_seq_no = 0;
1298 sub get_upload_filename {
1299 # choose unpredictable tmpfile name
1302 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1305 sub unshift_read_header {
1306 my ($self, $reqstate, $state) = @_;
1308 $state = { size => 0, count => 0 } if !$state;
1310 $reqstate->{hdl}->unshift_read(line => sub {
1311 my ($hdl, $line) = @_;
1314 # print "$$: got header
: $line\n" if $self->{debug};
1316 die "too many http header lines
(> $limit_max_headers)\n" if ++$state->{count} >= $limit_max_headers;
1317 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1319 my $r = $reqstate->{request};
1322 my $path = uri_unescape($r->uri->path());
1323 my $method = $r->method();
1325 $r->push_header($state->{key}, $state->{val})
1328 if (!$known_methods->{$method}) {
1329 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
1330 $self->response($reqstate, $resp);
1334 my $conn = $r->header('Connection');
1335 my $accept_enc = $r->header('Accept-Encoding');
1336 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1339 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1341 if ($reqstate->{proto}->{ver} < 1001) {
1342 $reqstate->{keep_alive} = 0;
1346 my $te = $r->header('Transfer-Encoding');
1347 if ($te && lc($te) eq 'chunked') {
1348 # Handle chunked transfer encoding
1349 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
1352 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
1356 my $pveclientip = $r->header('PVEClientIP');
1357 my $base_uri = $self->{base_uri};
1359 # fixme: how can we make PVEClientIP header trusted?
1360 if ($self->{trusted_env} && $pveclientip) {
1361 $reqstate->{peer_host} = $pveclientip;
1363 $r->header('PVEClientIP', $reqstate->{peer_host});
1366 my $len = $r->header('Content-Length');
1368 my $host_header = $r->header('Host');
1369 if (my $rpcenv = $self->{rpcenv}) {
1370 $rpcenv->set_request_host($host_header);
1373 # header processing complete - authenticate now
1376 if ($self->{spiceproxy}) {
1377 my $connect_str = $host_header;
1378 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
1379 if (!(defined($vmid) && $node && $port)) {
1380 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket
");
1383 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1385 } elsif ($path =~ m/^\Q$base_uri\E/) {
1386 my $token = $r->header('CSRFPreventionToken');
1387 my $cookie = $r->header('Cookie');
1388 my $auth_header = $r->header('Authorization');
1390 # prefer actual cookie
1391 my $ticket = PVE::APIServer::Formatter::extract_auth_value($cookie, $self->{cookie_name});
1393 # fallback to cookie in 'Authorization' header
1394 $ticket = PVE::APIServer::Formatter::extract_auth_value($auth_header, $self->{cookie_name})
1397 # finally, fallback to API token if no ticket has been provided so far
1399 $api_token = PVE::APIServer::Formatter::extract_auth_value($auth_header, $self->{apitoken_name})
1402 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1404 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
1409 $auth = $self->auth_handler($method, $rel_uri, $ticket, $token, $api_token,
1410 $reqstate->{peer_host});
1414 Net::SSLeay::ERR_clear_error();
1415 # always delay unauthorized calls by 3 seconds
1418 if (ref($err) eq "PVE
::Exception
") {
1420 $err->{code} ||= HTTP_INTERNAL_SERVER_ERROR,
1421 my $resp = HTTP::Response->new($err->{code}, $err->{msg});
1422 $self->response($reqstate, $resp, undef, 0, $delay);
1424 } elsif (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
1425 my ($raw, $ct, $nocomp) =
1426 $formatter->($path, $auth, $self->{formatter_config});
1428 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1431 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required
");
1432 $resp->header("Content-Type
" => $ct);
1433 $resp->content($raw);
1435 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1437 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1438 $self->response($reqstate, $resp, undef, 0, $delay);
1444 $reqstate->{log}->{userid} = $auth->{userid};
1448 if (!($method eq 'PUT' || $method eq 'POST')) {
1449 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
1453 my $ctype = $r->header('Content-Type');
1454 my ($ct, $boundary);
1455 ($ct, $boundary)= parse_content_type($ctype) if $ctype;
1457 if ($auth->{isUpload} && !$self->{trusted_env}) {
1458 die "upload
'Content-Type '$ctype' not implemented\n"
1459 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
1461 die "upload without content length header not supported" if !$len;
1463 die "upload without content length header not supported" if !$len;
1465 $self->dprint("start upload $path $ct $boundary");
1467 my $tmpfilename = get_upload_filename();
1468 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1469 die "unable to create temporary upload file '$tmpfilename'";
1471 $reqstate->{keep_alive} = 0;
1473 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1477 boundary => $boundary,
1478 ctx => Digest::MD5->new,
1479 boundlen => $boundlen,
1480 maxheader => 2048 + $boundlen, # should be large enough
1481 params => decode_urlencoded($r->url->query()),
1485 starttime => [gettimeofday],
1488 $reqstate->{tmpfilename} = $tmpfilename;
1489 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $method, $path, $state); });
1493 if ($len > $limit_max_post) {
1494 $self->error($reqstate, 501, "for data too large");
1498 if (!$ct || $ct eq 'application
/x-www-form-urlencoded' || $ct eq 'application/json
') {
1499 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1500 my ($hdl, $data) = @_;
1502 $self->handle_request($reqstate, $auth, $method, $path);
1505 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
1508 $self->handle_request($reqstate, $auth, $method, $path);
1510 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1511 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1512 ($state->{key}, $state->{val}) = ($1, $2);
1513 $self->unshift_read_header($reqstate, $state);
1514 } elsif ($line =~ /^\s+(.*)/) {
1515 $state->{val} .= " $1";
1516 $self->unshift_read_header($reqstate, $state);
1518 $self->error($reqstate, 506, "unable to parse request header
");
1525 sub push_request_header {
1526 my ($self, $reqstate) = @_;
1529 $reqstate->{hdl}->push_read(line => sub {
1530 my ($hdl, $line) = @_;
1533 # print "got request header
: $line\n" if $self->{debug};
1535 $reqstate->{keep_alive}--;
1537 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1538 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1541 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
1545 $self->{request_count}++; # only count valid request headers
1546 if ($self->{request_count} >= $self->{max_requests}) {
1547 $self->{end_loop} = 1;
1549 $reqstate->{log} = { requestline => $line };
1550 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
1551 $reqstate->{proto}->{maj} = $maj;
1552 $reqstate->{proto}->{min} = $min;
1553 $reqstate->{proto}->{ver} = $maj*1000+$min;
1554 $reqstate->{request} = HTTP::Request->new($method, $url);
1555 $reqstate->{starttime} = [gettimeofday],
1557 $self->unshift_read_header($reqstate);
1558 } elsif ($line eq '') {
1559 # ignore empty lines before requests (browser bugs?)
1560 $self->push_request_header($reqstate);
1562 $self->error($reqstate, 400, 'bad request');
1576 return if $self->{end_loop};
1578 # we need to m make sure that only one process calls accept
1579 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1580 next if $! == EINTR;
1581 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
1587 while (!$self->{end_loop} &&
1588 !defined($clientfh = $self->{socket}->accept()) &&
1591 if ($self->{end_loop}) {
1594 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1595 if (!defined($clientfh)) {
1596 $errmsg = "failed to
accept connection
: $!\n";
1602 flock($self->{lockfh}, Fcntl::LOCK_UN());
1604 if (!defined($clientfh)) {
1606 die $errmsg if $errmsg;
1609 fh_nonblocking $clientfh, 1;
1617 $self->{end_loop} = 1;
1619 undef $self->{socket_watch};
1621 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1623 if ($self->{conn_count} <= 0) {
1624 $self->{end_cond}->send(1);
1628 # fork and exit, so that parent starts a new worker
1633 # else we need to wait until all open connections gets closed
1634 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1636 # todo: test for active connections instead (we can abort idle connections)
1637 if ($self->{conn_count} <= 0) {
1639 $self->{end_cond}->send(1);
1647 sub check_host_access {
1648 my ($self, $clientip) = @_;
1650 $clientip = PVE::APIServer::Utils::normalize_v4_in_v6($clientip);
1651 my $cip = Net::IP->new($clientip);
1654 $self->dprint("client IP
not parsable
: $@");
1658 my $match_allow = 0;
1661 if ($self->{allow_from}) {
1662 foreach my $t (@{$self->{allow_from}}) {
1663 if ($t->overlaps($cip)) {
1665 $self->dprint("client IP allowed
: ". $t->prefix());
1671 if ($self->{deny_from}) {
1672 foreach my $t (@{$self->{deny_from}}) {
1673 if ($t->overlaps($cip)) {
1674 $self->dprint("client IP denied
: ". $t->prefix());
1681 if ($match_allow == $match_deny) {
1682 # match both allow and deny, or no match
1683 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1686 return $match_allow;
1689 sub accept_connections {
1692 my ($clientfh, $handle_creation);
1695 while ($clientfh = $self->accept()) {
1697 my $reqstate = { keep_alive => $self->{keep_alive} };
1699 # stop keep-alive when there are many open connections
1700 if ($self->{conn_count} + 1 >= $self->{max_conn_soft_limit}) {
1701 $reqstate->{keep_alive} = 0;
1704 if (my $sin = getpeername($clientfh)) {
1705 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1706 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1708 $self->dprint("getpeername failed
: $!");
1713 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1714 $self->dprint("ABORT request from
$reqstate->{peer_host
} - access denied
");
1715 $reqstate->{log}->{code} = 403;
1716 $self->log_request($reqstate);
1721 # Increment conn_count before creating new handle, since creation
1722 # triggers callbacks, which can potentialy decrement (e.g.
1723 # on_error) conn_count before AnyEvent::Handle->new() returns.
1724 $handle_creation = 1;
1725 $self->{conn_count}++;
1726 $reqstate->{hdl} = AnyEvent::Handle->new(
1728 rbuf_max => 64*1024,
1729 timeout => $self->{timeout},
1730 linger => 0, # avoid problems with ssh - really needed ?
1734 $self->log_aborted_request($reqstate);
1735 $self->client_do_disconnect($reqstate);
1737 if (my $err = $@) { syslog('err', $err); }
1740 my ($hdl, $fatal, $message) = @_;
1742 $self->log_aborted_request($reqstate, $message);
1743 $self->client_do_disconnect($reqstate);
1745 if (my $err = $@) { syslog('err', "$err"); }
1747 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1748 $handle_creation = 0;
1750 $self->dprint("ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}");
1752 $self->push_request_header($reqstate);
1757 syslog('err', $err);
1758 $self->dprint("connection
accept error
: $err");
1760 if ($handle_creation) {
1761 if ($self->{conn_count} <= 0) {
1762 warn "connection count
<= 0 not decrementing
!\n";
1764 $self->{conn_count}--;
1767 $self->{end_loop} = 1;
1770 $self->wait_end_loop() if $self->{end_loop};
1773 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1774 # because we write from multiple processes, and that would arbitrarily mix output
1776 sub open_access_log {
1777 my ($self, $filename) = @_;
1779 my $old_mask = umask(0137);;
1780 my $logfh = IO::File->new($filename, ">>") ||
1781 die "unable to
open log file
'$filename' - $!\n";
1784 $logfh->autoflush(1);
1786 $self->{logfh} = $logfh;
1790 my ($self, $data) = @_;
1792 return if !defined($self->{logfh}) || !$data;
1794 my $res = $self->{logfh}->print($data);
1797 delete $self->{logfh};
1798 syslog('err', "error writing access
log");
1799 $self->{end_loop} = 1; # terminate asap
1803 sub atfork_handler {
1807 # something else do to ?
1808 close($self->{socket});
1816 $self->{end_cond}->recv;
1820 my ($this, %args) = @_;
1822 my $class = ref($this) || $this;
1824 foreach my $req (qw(socket lockfh lockfile)) {
1825 die "misssing required argument '$req'" if !defined($args{$req});
1828 my $self = bless { %args }, $class;
1830 $self->{cookie_name
} //= 'PVEAuthCookie';
1831 $self->{apitoken_name
} //= 'PVEAPIToken';
1832 $self->{base_uri
} //= "/api2";
1833 $self->{dirs
} //= {};
1834 $self->{title
} //= 'API Inspector';
1835 $self->{compression
} //= 1;
1837 # formatter_config: we pass some configuration values to the Formatter
1838 $self->{formatter_config
} = {};
1839 foreach my $p (qw(apitoken_name cookie_name base_uri title)) {
1840 $self->{formatter_config
}->{$p} = $self->{$p};
1842 $self->{formatter_config
}->{csrfgen_func
} =
1843 $self->can('generate_csrf_prevention_token');
1845 # add default dirs which includes jquery and bootstrap
1846 my $jsbase = '/usr/share/javascript';
1847 add_dirs
($self->{dirs
}, '/js/' => "$jsbase/");
1848 # libjs-bootstrap uses symlinks for this, which we do not want to allow..
1849 my $glyphicons = '/usr/share/fonts/truetype/glyphicons/';
1850 add_dirs
($self->{dirs
}, '/js/bootstrap/fonts/' => "$glyphicons");
1853 PVE
::INotify
::inotify_init
();
1855 fh_nonblocking
($self->{socket}, 1);
1857 $self->{end_loop
} = 0;
1858 $self->{conn_count
} = 0;
1859 $self->{request_count
} = 0;
1860 $self->{timeout
} = 5 if !$self->{timeout
};
1861 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1862 $self->{max_conn
} = 800 if !$self->{max_conn
};
1863 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1865 $self->{policy
} = 'allow' if !$self->{policy
};
1867 $self->{end_cond
} = AnyEvent-
>condvar;
1870 my $ssl_defaults = {
1871 # Note: older versions are considered insecure, for example
1872 # search for "Poodle"-Attack
1876 cipher_list
=> 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256',
1877 honor_cipher_order
=> 1,
1880 foreach my $k (keys %$ssl_defaults) {
1881 $self->{ssl
}->{$k} //= $ssl_defaults->{$k};
1884 if (!defined($self->{ssl
}->{dh_file
})) {
1885 $self->{ssl
}->{dh
} = 'skip2048';
1888 my $tls_ctx_flags = &Net
::SSLeay
::OP_NO_COMPRESSION
| &Net
::SSLeay
::OP_SINGLE_ECDH_USE
|
1889 &Net
::SSLeay
::OP_SINGLE_DH_USE
| &Net
::SSLeay
::OP_NO_RENEGOTIATION
;
1890 if ( delete $self->{ssl
}->{honor_cipher_order
} ) {
1891 $tls_ctx_flags |= &Net
::SSLeay
::OP_CIPHER_SERVER_PREFERENCE
;
1894 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
1895 Net
::SSLeay
::CTX_set_options
($self->{tls_ctx
}->{ctx
}, $tls_ctx_flags);
1898 if ($self->{spiceproxy
}) {
1899 $known_methods = { CONNECT
=> 1 };
1902 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
1904 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
1906 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
1908 if ($self->{conn_count
} >= $self->{max_conn
}) {
1909 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
1910 if ($self->{conn_count
} < $self->{max_conn
}) {
1912 $self->accept_connections();
1916 $self->accept_connections();
1922 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
1923 undef $self->{term_watch
};
1924 $self->wait_end_loop();
1927 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
1928 undef $self->{quit_watch
};
1929 $self->wait_end_loop();
1932 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
1933 PVE
::INotify
::poll
(); # read inotify events
1939 # static helper to add directory including all subdirs
1940 # This can be used to setup $self->{dirs}
1942 my ($result_hash, $alias, $subdir) = @_;
1944 $result_hash->{$alias} = $subdir;
1947 my $dir = $File::Find
::dir
;
1948 if ($dir =~m!^$subdir(.*)$!) {
1949 my $name = "$alias$1/";
1950 $result_hash->{$name} = "$dir/";
1954 find
({wanted
=> $wanted, follow
=> 0, no_chdir
=> 1}, $subdir);
1957 # abstract functions - subclass should overwrite/implement them
1959 sub verify_spice_connect_url
{
1960 my ($self, $connect_str) = @_;
1964 #return ($vmid, $node, $port);
1967 # formatters can call this when the generate a new page
1968 sub generate_csrf_prevention_token
{
1969 my ($username) = @_;
1971 return undef; # do nothing by default
1975 my ($self, $method, $rel_uri, $ticket, $token, $api_token, $peer_host) = @_;
1980 # ticket => $ticket,
1982 # userid => $username,
1984 # isUpload => $isUpload,
1985 # api_token => $api_token,
1990 my ($self, $clientip, $method, $rel_uri, $auth, $params, $format) = @_;
1992 # please do not raise exceptions here (always return a result).
1995 status
=> HTTP_NOT_IMPLEMENTED
,
1996 message
=> "Method '$method $rel_uri' not implemented",
1999 # this should return the following properties, which
2000 # are then passed to the Formatter
2002 # status: HTTP status code
2003 # message: Error message
2004 # errors: more detailed error hash (per parameter)
2005 # info: reference to JSON schema definition - useful to format output
2008 # total: additional info passed to output
2009 # changes: additional info passed to output
2011 # if you want to proxy the request to another node return this
2012 # { proxy => $remip, proxynode => $node, proxy_params => $params };
2014 # to pass the request to the local priviledged daemon use:
2015 # { proxy => 'localhost' , proxy_params => $params };
2017 # to download aspecific file use:
2018 # { download => "/path/to/file" };
2021 sub check_cert_fingerprint
{
2022 my ($self, $cert) = @_;
2027 sub initialize_cert_cache
{
2028 my ($self, $node) = @_;
2033 sub remote_node_ip
{
2034 my ($self, $node) = @_;