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
;
41 use HTTP
::Status
qw(:constants);
49 my $limit_max_headers = 64;
50 my $limit_max_header_size = 8*1024;
51 my $limit_max_post = 64*1024;
60 my $split_abs_uri = sub {
61 my ($abs_uri, $base_uri) = @_;
63 my ($format, $rel_uri) = $abs_uri =~ m/^\Q$base_uri\E\/+([a-z
][a-z0-9
]+)(\
/.*)?$/;
64 $rel_uri = '/' if !$rel_uri;
66 return wantarray ?
($rel_uri, $format) : $rel_uri;
70 my ($self, $message) = @_;
72 return if !$self->{debug
};
74 my ($pkg, $pkgfile, $line, $sub) = caller(1);
75 $sub =~ s/^(?:.+::)+//;
76 print "worker[$$]: $pkg +$line: $sub: $message\n";
80 my ($self, $reqstate) = @_;
82 my $loginfo = $reqstate->{log};
84 # like apache2 common log format
85 # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
87 return if $loginfo->{written
}; # avoid duplicate logs
88 $loginfo->{written
} = 1;
90 my $peerip = $reqstate->{peer_host
} || '-';
91 my $userid = $loginfo->{userid
} || '-';
92 my $content_length = defined($loginfo->{content_length
}) ?
$loginfo->{content_length
} : '-';
93 my $code = $loginfo->{code
} || 500;
94 my $requestline = $loginfo->{requestline
} || '-';
95 my $timestr = strftime
("%d/%m/%Y:%H:%M:%S %z", localtime());
97 my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n";
99 $self->write_log($msg);
102 sub log_aborted_request {
103 my ($self, $reqstate, $error) = @_;
105 my $r = $reqstate->{request};
106 return if !$r; # no active request
109 syslog("err
", "problem with client
$reqstate->{peer_host
}; $error");
112 $self->log_request($reqstate);
115 sub cleanup_reqstate {
118 delete $reqstate->{log};
119 delete $reqstate->{request};
120 delete $reqstate->{proto};
121 delete $reqstate->{accept_gzip};
122 delete $reqstate->{starttime};
124 if ($reqstate->{tmpfilename}) {
125 unlink $reqstate->{tmpfilename};
126 delete $reqstate->{tmpfilename};
130 sub client_do_disconnect {
131 my ($self, $reqstate) = @_;
133 cleanup_reqstate($reqstate);
135 my $shutdown_hdl = sub {
138 shutdown($hdl->{fh}, 1);
140 $hdl->on_drain(undef);
141 $hdl->on_read(undef);
145 if (my $proxyhdl = delete $reqstate->{proxyhdl}) {
146 &$shutdown_hdl($proxyhdl);
149 my $hdl = delete $reqstate->{hdl};
152 syslog('err', "detected empty handle
");
156 $self->dprint("close connection
$hdl");
158 &$shutdown_hdl($hdl);
160 warn "connection count
<= 0!\n" if $self->{conn_count} <= 0;
162 $self->{conn_count}--;
164 $self->dprint("CLOSE FH
" . $hdl->{fh}->fileno() . " CONN
$self->{conn_count
}");
167 sub finish_response {
168 my ($self, $reqstate) = @_;
170 cleanup_reqstate($reqstate);
172 my $hdl = $reqstate->{hdl};
173 return if !$hdl; # already disconnected
175 if (!$self->{end_loop} && $reqstate->{keep_alive} > 0) {
176 # print "KEEPALIVE
$reqstate->{keep_alive
}\n" if $self->{debug};
178 eval { $self->push_request_header($reqstate); };
182 $hdl->on_drain (sub {
184 $self->client_do_disconnect($reqstate);
192 my ($self, $reqstate, $resp, $mtime, $nocomp, $delay) = @_;
194 #print "$$: send response
: " . Dumper($resp);
197 $reqstate->{hdl}->timeout_reset();
198 $reqstate->{hdl}->timeout($self->{timeout});
200 $nocomp = 1 if !$self->{compression};
201 $nocomp = 1 if !$reqstate->{accept_gzip};
203 my $code = $resp->code;
204 my $msg = $resp->message || HTTP::Status::status_message($code);
205 ($msg) = $msg =~m/^(.*)$/m;
206 my $content = $resp->content;
208 if ($code =~ /^(1\d\d|[23]04)$/) {
209 # make sure content we have no content
213 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
215 $reqstate->{log}->{code} = $code;
217 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
218 my $res = "$proto $code $msg\015\012";
221 my $date = HTTP::Date::time2str($ctime);
222 $resp->header('Date' => $date);
224 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
226 $resp->header('Expires' => $date);
227 $resp->header('Cache-Control' => "max-age
=0");
228 $resp->header("Pragma
", "no-cache
");
231 $resp->header('Server' => "pve-api-daemon
/3.0");
236 $content_length = length($content);
238 if (!$nocomp && ($content_length > 1024)) {
239 my $comp = Compress::Zlib::memGzip($content);
240 $resp->header('Content-Encoding', 'gzip');
242 $content_length = length($content);
244 $resp->header("Content-Length
" => $content_length);
245 $reqstate->{log}->{content_length} = $content_length;
248 $resp->remove_header("Content-Length
");
251 if ($reqstate->{keep_alive} > 0) {
252 $resp->push_header('Connection' => 'Keep-Alive');
254 $resp->header('Connection' => 'close');
257 $res .= $resp->headers_as_string("\015\012");
258 #print "SEND
(without content
) $res\n" if $self->{debug};
261 $res .= $content if $content;
263 $self->log_request($reqstate, $reqstate->{request});
265 if ($delay && $delay > 0) {
266 my $w; $w = AnyEvent->timer(after => $delay, cb => sub {
267 undef $w; # delete reference
268 $reqstate->{hdl}->push_write($res);
269 $self->finish_response($reqstate);
272 $reqstate->{hdl}->push_write($res);
273 $self->finish_response($reqstate);
278 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
281 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
282 $self->response($reqstate, $resp);
287 my $file_extension_info = {
288 css => { ct => 'text/css' },
289 html => { ct => 'text/html' },
290 js => { ct => 'application/javascript' },
291 json => { ct => 'application/json' },
292 map => { ct => 'application/json' },
293 png => { ct => 'image/png' , nocomp => 1 },
294 ico => { ct => 'image/x-icon', nocomp => 1},
295 gif => { ct => 'image/gif', nocomp => 1},
296 svg => { ct => 'image/svg+xml' },
297 jar => { ct => 'application/java-archive', nocomp => 1},
298 woff => { ct => 'application/font-woff', nocomp => 1},
299 woff2 => { ct => 'application/font-woff2', nocomp => 1},
300 ttf => { ct => 'application/font-snft', nocomp => 1},
301 pdf => { ct => 'application/pdf', nocomp => 1},
302 epub => { ct => 'application/epub+zip', nocomp => 1},
303 mp3 => { ct => 'audio/mpeg', nocomp => 1},
304 oga => { ct => 'audio/ogg', nocomp => 1},
305 tgz => { ct => 'application/x-compressed-tar', nocomp => 1},
308 sub send_file_start {
309 my ($self, $reqstate, $download) = @_;
312 # print "SEND FILE
$filename\n";
313 # Note: aio_load() this is not really async unless we use IO::AIO!
316 my $r = $reqstate->{request};
322 if (ref($download) eq 'HASH') {
323 $fh = $download->{fh};
324 $mime = $download->{'content-type'};
326 my $filename = $download;
327 $fh = IO::File->new($filename, '<') ||
328 die "unable to
open file
'$filename' - $!\n";
330 my ($ext) = $filename =~ m/\.([^.]*)$/;
331 my $ext_info = $file_extension_info->{$ext};
333 die "unable to detect content type
" if !$ext_info;
334 $mime = $ext_info->{ct};
335 $nocomp = $ext_info->{nocomp};
338 my $stat = File::stat::stat($fh) ||
341 my $mtime = $stat->mtime;
343 if (my $ifmod = $r->header('if-modified-since')) {
344 my $iftime = HTTP::Date::str2time($ifmod);
345 if ($mtime <= $iftime) {
346 my $resp = HTTP::Response->new(304, "NOT MODIFIED
");
347 $self->response($reqstate, $resp, $mtime);
353 my $len = sysread($fh, $data, $stat->size);
354 die "got short file
\n" if !defined($len) || $len != $stat->size;
356 my $header = HTTP::Headers->new(Content_Type => $mime);
357 my $resp = HTTP::Response->new(200, "OK
", $header, $data);
358 $self->response($reqstate, $resp, $mtime, $nocomp);
361 $self->error($reqstate, 501, $err);
368 sub websocket_proxy {
369 my ($self, $reqstate, $wsaccept, $wsproto, $param) = @_;
375 my $max_payload_size = 128*1024;
378 if ($wsproto eq 'binary') {
380 } elsif ($wsproto eq 'base64') {
383 die "websocket_proxy
: unsupported protocol
'$wsproto'\n";
386 if ($param->{port}) {
387 $remhost = 'localhost';
388 $remport = $param->{port};
389 } elsif ($param->{socket}) {
391 $remport = $param->{socket};
393 die "websocket_proxy
: missing port
or socket\n";
397 my ($data, $opcode) = @_;
402 $string = $opcode ? $opcode : "\x82"; # binary frame
405 $string = $opcode ? $opcode : "\x81"; # text frame
406 $payload = encode_base64($$data, '');
409 my $payload_len = length($payload);
410 if ($payload_len <= 125) {
411 $string .= pack 'C', $payload_len;
412 } elsif ($payload_len <= 0xffff) {
413 $string .= pack 'C', 126;
414 $string .= pack 'n', $payload_len;
416 $string .= pack 'C', 127;
417 $string .= pack 'Q>', $payload_len;
423 tcp_connect $remhost, $remport, sub {
425 or die "connect to
'$remhost:$remport' failed
: $!";
427 $self->dprint("CONNECTed to
'$remhost:$remport'");
429 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
431 rbuf_max => $max_payload_size,
432 wbuf_max => $max_payload_size*5,
437 $self->log_aborted_request($reqstate);
438 $self->client_do_disconnect($reqstate);
440 if (my $err = $@) { syslog('err', $err); }
443 my ($hdl, $fatal, $message) = @_;
445 $self->log_aborted_request($reqstate, $message);
446 $self->client_do_disconnect($reqstate);
448 if (my $err = $@) { syslog('err', "$err"); }
451 my $proxyhdlreader = sub {
454 my $len = length($hdl->{rbuf});
455 my $data = substr($hdl->{rbuf}, 0, $len > $max_payload_size ? $max_payload_size : $len, '');
457 my $string = $encode->(\$data);
459 $reqstate->{hdl}->push_write($string) if $reqstate->{hdl};
462 my $hdlreader = sub {
465 while (my $len = length($hdl->{rbuf})) {
468 my $hdr = unpack('C', substr($hdl->{rbuf}, 0, 1));
469 my $opcode = $hdr & 0b00001111;
470 my $fin = $hdr & 0b10000000;
472 die "received fragmented websocket frame
\n" if !$fin;
474 my $rsv = $hdr & 0b01110000;
475 die "received websocket frame with RSV flags
\n" if $rsv;
477 my $payload_len = unpack 'C', substr($hdl->{rbuf}, 1, 1);
479 my $masked = $payload_len & 0b10000000;
480 die "received unmasked websocket frame from client
\n" if !$masked;
483 $payload_len = $payload_len & 0b01111111;
484 if ($payload_len == 126) {
486 $payload_len = unpack('n', substr($hdl->{rbuf}, $offset, 2));
488 } elsif ($payload_len == 127) {
490 $payload_len = unpack('Q>', substr($hdl->{rbuf}, $offset, 8));
494 die "received too large websocket frame
(len
= $payload_len)\n"
495 if ($payload_len > $max_payload_size) || ($payload_len < 0);
497 return if $len < ($offset + 4 + $payload_len);
499 my $data = substr($hdl->{rbuf}, 0, $offset + 4 + $payload_len, ''); # now consume data
501 my $mask = substr($data, $offset, 4);
504 my $payload = substr($data, $offset, $payload_len);
506 # NULL-mask might be used over TLS, skip to increase performance
507 if ($mask ne pack('N', 0)) {
508 # repeat 4 byte mask to payload length + up to 4 byte
509 $mask = $mask x (int($payload_len / 4) + 1);
510 # truncate mask to payload length
511 substr($mask, $payload_len) = "";
516 $payload = decode_base64($payload) if !$binary;
518 if ($opcode == 1 || $opcode == 2) {
519 $reqstate->{proxyhdl}->push_write($payload) if $reqstate->{proxyhdl};
520 } elsif ($opcode == 8) {
521 my $statuscode = unpack ("n
", $payload);
522 $self->dprint("websocket received
close. status code
: '$statuscode'");
523 if ($reqstate->{proxyhdl}) {
524 $reqstate->{proxyhdl}->push_shutdown();
526 $hdl->push_shutdown();
527 } elsif ($opcode == 9) {
528 # ping received, schedule pong
529 $reqstate->{hdl}->push_write($encode->(\$payload, "\x8A")) if $reqstate->{hdl};
530 } elsif ($opcode == 0xA) {
531 # pong received, continue
533 die "received unhandled websocket opcode
$opcode\n";
538 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.1';
540 $reqstate->{proxyhdl}->timeout(0);
541 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
542 $reqstate->{hdl}->on_read($hdlreader);
544 # todo: use stop_read/start_read if write buffer grows to much
546 my $res = "$proto 101 Switching Protocols
\015\012" .
547 "Upgrade
: websocket
\015\012" .
548 "Connection
: upgrade
\015\012" .
549 "Sec-WebSocket-Accept
: $wsaccept\015\012" .
550 "Sec-WebSocket-Protocol
: $wsproto\015\012" .
555 $reqstate->{hdl}->push_write($res);
558 $reqstate->{log}->{code} = 101;
559 $self->log_request($reqstate);
565 $self->log_aborted_request($reqstate, $err);
566 $self->client_do_disconnect($reqstate);
571 my ($self, $reqstate, $clientip, $host, $node, $method, $uri, $auth, $params) = @_;
576 if ($host eq 'localhost') {
577 $target = "http
://$host:85$uri";
578 # keep alive for localhost is not worth (connection setup is about 0.2ms)
580 } elsif (Net::IP::ip_is_ipv6($host)) {
581 $target = "https
://[$host]:8006$uri";
583 $target = "https
://$host:8006$uri";
587 PVEDisableProxy => 'true',
588 PVEClientIP => $clientip,
591 $headers->{'cookie'} = PVE::APIServer::Formatter::create_auth_cookie($auth->{ticket}, $self->{cookie_name})
593 $headers->{'Authorization'} = PVE::APIServer::Formatter::create_auth_header($auth->{api_token}, $self->{apitoken_name})
594 if $auth->{api_token};
595 $headers->{'CSRFPreventionToken'} = $auth->{token}
597 $headers->{'Accept-Encoding'} = 'gzip' if ($reqstate->{accept_gzip} && $self->{compression});
599 if (defined(my $host = $reqstate->{request}->header('Host'))) {
600 $headers->{Host} = $host;
605 if ($method eq 'POST' || $method eq 'PUT') {
606 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
607 # use URI object to format application/x-www-form-urlencoded content.
608 my $url = URI->new('http:');
609 $url->query_form(%$params);
610 $content = $url->query;
611 if (defined($content)) {
612 $headers->{'Content-Length'} = length($content);
617 # TLS 1.x only, with certificate pinning
623 my (undef, undef, undef, $depth, undef, undef, $cert) = @_;
624 # we don't care about intermediate or root certificates
625 return 1 if $depth != 0;
626 # check server certificate against cache of pinned FPs
627 return $self->check_cert_fingerprint($cert);
631 # load and cache cert fingerprint if first time we proxy to this node
632 $self->initialize_cert_cache($node);
634 my $w; $w = http_request(
639 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
640 keepalive => $keep_alive,
642 tls_ctx => AnyEvent::TLS->new(%{$tls}),
644 my ($body, $hdr) = @_;
648 if (!$reqstate->{hdl}) {
649 warn "proxy detected vanished client connection
\n";
654 my $code = delete $hdr->{Status};
655 my $msg = delete $hdr->{Reason};
657 delete $hdr->{HTTPVersion};
658 my $header = HTTP::Headers->new(%$hdr);
659 if (my $location = $header->header('Location')) {
660 $location =~ s|^http://localhost:85||;
661 $header->header(Location => $location);
663 my $resp = HTTP::Response->new($code, $msg, $header, $body);
664 # Note: disable compression, because body is already compressed
665 $self->response($reqstate, $resp, undef, 1);
673 # return arrays as \0 separated strings (like CGI.pm)
674 # assume data is UTF8 encoded
675 sub decode_urlencoded {
680 return $res if !$data;
682 foreach my $kv (split(/[\&\;]/, $data)) {
683 my ($k, $v) = split(/=/, $kv);
685 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
689 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
691 $v = Encode::decode('utf8', $v);
693 if (defined(my $old = $res->{$k})) {
704 my ($r, $method) = @_;
708 if ($method eq 'PUT' || $method eq 'POST') {
710 if (my $ctype = $r->header('Content-Type')) {
711 $ct = parse_content_type($ctype);
713 if (defined($ct) && $ct eq 'application/json') {
714 $params = decode_json($r->content);
716 $params = decode_urlencoded($r->content);
720 my $query_params = decode_urlencoded($r->url->query());
722 foreach my $k (keys %{$query_params}) {
723 $params->{$k} = $query_params->{$k};
729 sub handle_api2_request {
730 my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
733 my $r = $reqstate->{request};
735 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
737 my $formatter = PVE::APIServer::Formatter::get_formatter($format, $method, $rel_uri);
739 if (!defined($formatter)) {
740 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no formatter
for uri
$rel_uri, $format");
744 #print Dumper($upload_state) if $upload_state;
749 $params = $upload_state->{params};
751 $params = extract_params($r, $method);
754 delete $params->{_dc}; # remove disable cache parameter
756 my $clientip = $reqstate->{peer_host};
758 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
761 Net::SSLeay::ERR_clear_error();
763 AnyEvent->now_update(); # in case somebody called sleep()
765 my $upgrade = $r->header('upgrade');
766 $upgrade = lc($upgrade) if $upgrade;
768 if (my $host = $res->{proxy}) {
770 if ($self->{trusted_env}) {
771 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
775 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
776 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
780 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
782 $self->proxy_request($reqstate, $clientip, $host, $res->{proxynode}, $method,
783 $r->uri, $auth, $res->{proxy_params});
786 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
787 die "unable to upgrade to protocol
'$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
788 my $wsver = $r->header('sec-websocket-version');
789 die "unsupported websocket-version
'$wsver'\n" if !$wsver || ($wsver ne '13');
790 my $wsproto_str = $r->header('sec-websocket-protocol');
791 die "missing websocket-protocol header
" if !$wsproto_str;
793 foreach my $p (PVE::Tools::split_list($wsproto_str)) {
794 $wsproto = $p if !$wsproto && $p eq 'base64';
795 $wsproto = $p if $p eq 'binary';
797 die "unsupported websocket-protocol protocol
'$wsproto_str'\n" if !$wsproto;
798 my $wskey = $r->header('sec-websocket-key');
799 die "missing websocket-key
\n" if !$wskey;
800 # Note: Digest::SHA::sha1_base64 has wrong padding
801 my $wsaccept = Digest::SHA::sha1_base64("${wskey
}258EAFA5-E914-47DA-95CA-C5AB0DC85B11
") . "=";
802 if ($res->{status} == HTTP_OK) {
803 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
809 if ($res->{status} == HTTP_UNAUTHORIZED) {
810 # always delay unauthorized calls by 3 seconds
811 $delay = 3 - tv_interval($reqstate->{starttime});
812 $delay = 0 if $delay < 0;
815 if (defined(my $download = $res->{download})) {
816 send_file_start($self, $reqstate, $download);
820 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
821 $auth, $self->{formatter_config});
824 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
827 $resp = HTTP::Response->new($res->{status}, $res->{message});
828 $resp->header("Content-Type
" => $ct);
829 $resp->content($raw);
831 $self->response($reqstate, $resp, undef, $nocomp, $delay);
834 $self->error($reqstate, 501, $err);
838 sub handle_spice_proxy_request {
839 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
843 my ($minport, $maxport) = PVE::Tools::spice_port_range();
844 if ($spiceport < $minport || $spiceport > $maxport) {
845 die "SPICE Port
$spiceport is not in allowed range
($minport, $maxport)\n";
848 my $clientip = $reqstate->{peer_host};
849 my $r = $reqstate->{request};
853 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
854 $remip = $self->remote_node_ip($node);
855 $self->dprint("REMOTE CONNECT
$vmid, $remip, $connect_str");
857 $self->dprint("CONNECT
$vmid, $node, $spiceport");
860 if ($remip && $r->header('PVEDisableProxy')) {
861 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
865 $reqstate->{hdl}->timeout(0);
866 $reqstate->{hdl}->wbuf_max(64*10*1024);
868 my $remhost = $remip ? $remip : "localhost
";
869 my $remport = $remip ? 3128 : $spiceport;
871 tcp_connect $remhost, $remport, sub {
873 or die "connect to
'$remhost:$remport' failed
: $!";
875 $self->dprint("CONNECTed to
'$remhost:$remport'");
876 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
879 wbuf_max => 64*10*1024,
884 $self->log_aborted_request($reqstate);
885 $self->client_do_disconnect($reqstate);
887 if (my $err = $@) { syslog('err', $err); }
890 my ($hdl, $fatal, $message) = @_;
892 $self->log_aborted_request($reqstate, $message);
893 $self->client_do_disconnect($reqstate);
895 if (my $err = $@) { syslog('err', "$err"); }
899 my $proxyhdlreader = sub {
902 my $len = length($hdl->{rbuf});
903 my $data = substr($hdl->{rbuf}, 0, $len, '');
905 #print "READ1
$len\n";
906 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
909 my $hdlreader = sub {
912 my $len = length($hdl->{rbuf});
913 my $data = substr($hdl->{rbuf}, 0, $len, '');
915 #print "READ0
$len\n";
916 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
919 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
921 my $startproxy = sub {
922 $reqstate->{proxyhdl}->timeout(0);
923 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
924 $reqstate->{hdl}->on_read($hdlreader);
926 # todo: use stop_read/start_read if write buffer grows to much
928 # a response must be followed by an empty line
929 my $res = "$proto 200 OK
\015\012\015\012";
930 $reqstate->{hdl}->push_write($res);
933 $reqstate->{log}->{code} = 200;
934 $self->log_request($reqstate);
938 my $header = "CONNECT
${connect_str
} $proto\015\012" .
939 "Host
: ${connect_str
}\015\012" .
940 "Proxy-Connection
: keep-alive
\015\012" .
941 "User-Agent
: spiceproxy
\015\012" .
942 "PVEDisableProxy
: true
\015\012" .
943 "PVEClientIP
: $clientip\015\012" .
946 $reqstate->{proxyhdl}->push_write($header);
947 $reqstate->{proxyhdl}->push_read(line => sub {
948 my ($hdl, $line) = @_;
950 if ($line =~ m!^$proto 200 OK$!) {
951 # read the empty line after the 200 OK
952 $reqstate->{proxyhdl}->unshift_read(line => sub{
956 $reqstate->{hdl}->push_write($line);
957 $self->client_do_disconnect($reqstate);
968 $self->log_aborted_request($reqstate, $err);
969 $self->client_do_disconnect($reqstate);
974 my ($self, $reqstate, $auth, $method, $path) = @_;
976 my $base_uri = $self->{base_uri};
979 my $r = $reqstate->{request};
981 # disable timeout on handle (we already have all data we need)
982 # we re-enable timeout in response()
983 $reqstate->{hdl}->timeout(0);
985 if ($path =~ m/^\Q$base_uri\E/) {
986 $self->handle_api2_request($reqstate, $auth, $method, $path);
990 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
991 if (ref($handler) eq 'CODE') {
992 my $params = decode_urlencoded($r->url->query());
993 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
995 Net::SSLeay::ERR_clear_error();
996 $self->response($reqstate, $resp);
997 } elsif (ref($handler) eq 'HASH') {
998 if (my $filename = $handler->{file}) {
999 my $fh = IO::File->new($filename) ||
1000 die "unable to
open file
'$filename' - $!\n";
1001 send_file_start($self, $reqstate, $filename);
1003 die "internal error
- no handler
";
1006 die "internal error
- no handler
";
1011 if ($self->{dirs} && ($method eq 'GET')) {
1012 # we only allow simple names
1013 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
1014 my ($subdir, $file) = ($1, $2);
1015 if (my $dir = $self->{dirs}->{$subdir}) {
1016 my $filename = "$dir$file";
1017 my $fh = IO::File->new($filename) ||
1018 die "unable to
open file
'$filename' - $!\n";
1019 send_file_start($self, $reqstate, $filename);
1025 die "no such file
'$path'\n";
1028 $self->error($reqstate, 501, $err);
1032 sub file_upload_multipart {
1033 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
1036 my $boundary = $rstate->{boundary};
1037 my $hdl = $reqstate->{hdl};
1039 my $startlen = length($hdl->{rbuf});
1041 if ($rstate->{phase} == 0) { # skip everything until start
1042 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
1043 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
1045 my ($ct, $disp, $name, $filename);
1046 foreach my $line (split(/\015?\012/, $header)) {
1047 # assume we have single line headers
1048 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
1049 $ct = parse_content_type($1);
1050 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
1051 ($disp, $name, $filename) = parse_content_disposition($1);
1055 if (!($disp && $disp eq 'form-data' && $name)) {
1056 syslog('err', "wrong content disposition
in multipart
- abort upload
");
1057 $rstate->{phase} = -1;
1060 $rstate->{fieldname} = $name;
1063 if ($name eq 'filename') {
1064 # found file upload data
1065 $rstate->{phase} = 1;
1066 $rstate->{filename} = $filename;
1068 syslog('err', "wrong field name
for file upload
- abort upload
");
1069 $rstate->{phase} = -1;
1072 # found form data for field $name
1073 $rstate->{phase} = 2;
1077 my $len = length($hdl->{rbuf});
1078 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
1079 if $len > $rstate->{maxheader}; # skip garbage
1081 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
1082 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1083 my ($rest, $eof) = ($1, $3);
1084 my $len = length($rest);
1085 die "write to temporary file failed
- $!"
1086 if syswrite($rstate->{outfh}, $rest) != $len;
1087 $rstate->{ctx}->add($rest);
1088 $rstate->{params}->{filename} = $rstate->{filename};
1089 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
1090 $rstate->{bytes} += $len;
1091 $rstate->{phase} = $eof ? 100 : 0;
1093 my $len = length($hdl->{rbuf});
1094 my $wlen = $len - $rstate->{boundlen};
1096 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
1097 die "write to temporary file failed
- $!"
1098 if syswrite($rstate->{outfh}, $data) != $wlen;
1099 $rstate->{bytes} += $wlen;
1100 $rstate->{ctx}->add($data);
1103 } elsif ($rstate->{phase} == 2) { # inside normal field
1105 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1106 my ($rest, $eof) = ($1, $3);
1107 my $len = length($rest);
1108 $rstate->{post_size} += $len;
1109 if ($rstate->{post_size} < $limit_max_post) {
1110 $rstate->{params}->{$rstate->{fieldname}} = $rest;
1111 $rstate->{phase} = $eof ? 100 : 0;
1113 syslog('err', "form data to large
- abort upload
");
1114 $rstate->{phase} = -1; # skip
1118 my $len = length($hdl->{rbuf});
1119 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
1122 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
1124 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
1125 $rstate->{done} = 1; # make sure we dont get called twice
1126 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
1127 die "upload failed
\n";
1129 my $elapsed = tv_interval($rstate->{starttime});
1131 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
1132 syslog('info', "multipart upload complete
" .
1133 "(size
: %d time: %ds rate
: %.2fMiB
/s md5sum
: $rstate->{md5sum
})",
1134 $rstate->{bytes}, $elapsed, $rate);
1135 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1140 syslog('err', $err);
1141 $self->error($reqstate, 501, $err);
1145 sub parse_content_type {
1148 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
1150 foreach my $v (@params) {
1151 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1152 return wantarray ? ($ct, $1) : $ct;
1156 return wantarray ? ($ct) : $ct;
1159 sub parse_content_disposition {
1162 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
1166 foreach my $v (@params) {
1167 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
1169 $name =~ s/^"(.*)"$/$1/;
1170 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
1172 $filename =~ s/^"(.*)"$/$1/;
1176 return wantarray ? ($disp, $name, $filename) : $disp;
1179 my $tmpfile_seq_no = 0;
1181 sub get_upload_filename {
1182 # choose unpredictable tmpfile name
1185 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1188 sub unshift_read_header {
1189 my ($self, $reqstate, $state) = @_;
1191 $state = { size => 0, count => 0 } if !$state;
1193 $reqstate->{hdl}->unshift_read(line => sub {
1194 my ($hdl, $line) = @_;
1197 # print "$$: got header
: $line\n" if $self->{debug};
1199 die "too many http header lines
(> $limit_max_headers)\n" if ++$state->{count} >= $limit_max_headers;
1200 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1202 my $r = $reqstate->{request};
1205 my $path = uri_unescape($r->uri->path());
1206 my $method = $r->method();
1208 $r->push_header($state->{key}, $state->{val})
1211 if (!$known_methods->{$method}) {
1212 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
1213 $self->response($reqstate, $resp);
1217 my $conn = $r->header('Connection');
1218 my $accept_enc = $r->header('Accept-Encoding');
1219 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1222 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1224 if ($reqstate->{proto}->{ver} < 1001) {
1225 $reqstate->{keep_alive} = 0;
1229 my $te = $r->header('Transfer-Encoding');
1230 if ($te && lc($te) eq 'chunked') {
1231 # Handle chunked transfer encoding
1232 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
1235 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
1239 my $pveclientip = $r->header('PVEClientIP');
1240 my $base_uri = $self->{base_uri};
1242 # fixme: how can we make PVEClientIP header trusted?
1243 if ($self->{trusted_env} && $pveclientip) {
1244 $reqstate->{peer_host} = $pveclientip;
1246 $r->header('PVEClientIP', $reqstate->{peer_host});
1249 my $len = $r->header('Content-Length');
1251 my $host_header = $r->header('Host');
1252 if (my $rpcenv = $self->{rpcenv}) {
1253 $rpcenv->set_request_host($host_header);
1256 # header processing complete - authenticate now
1259 if ($self->{spiceproxy}) {
1260 my $connect_str = $host_header;
1261 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
1262 if (!(defined($vmid) && $node && $port)) {
1263 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket
");
1266 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1268 } elsif ($path =~ m/^\Q$base_uri\E/) {
1269 my $token = $r->header('CSRFPreventionToken');
1270 my $cookie = $r->header('Cookie');
1271 my $auth_header = $r->header('Authorization');
1273 # prefer actual cookie
1274 my $ticket = PVE::APIServer::Formatter::extract_auth_value($cookie, $self->{cookie_name});
1276 # fallback to cookie in 'Authorization' header
1277 $ticket = PVE::APIServer::Formatter::extract_auth_value($auth_header, $self->{cookie_name})
1280 # finally, fallback to API token if no ticket has been provided so far
1282 $api_token = PVE::APIServer::Formatter::extract_auth_value($auth_header, $self->{apitoken_name})
1285 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1287 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
1292 $auth = $self->auth_handler($method, $rel_uri, $ticket, $token, $api_token,
1293 $reqstate->{peer_host});
1297 Net::SSLeay::ERR_clear_error();
1298 # always delay unauthorized calls by 3 seconds
1301 if (ref($err) eq "PVE
::Exception
") {
1303 $err->{code} ||= HTTP_INTERNAL_SERVER_ERROR,
1304 my $resp = HTTP::Response->new($err->{code}, $err->{msg});
1305 $self->response($reqstate, $resp, undef, 0, $delay);
1307 } elsif (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
1308 my ($raw, $ct, $nocomp) =
1309 $formatter->($path, $auth, $self->{formatter_config});
1311 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1314 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required
");
1315 $resp->header("Content-Type
" => $ct);
1316 $resp->content($raw);
1318 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1320 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1321 $self->response($reqstate, $resp, undef, 0, $delay);
1327 $reqstate->{log}->{userid} = $auth->{userid};
1331 if (!($method eq 'PUT' || $method eq 'POST')) {
1332 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
1336 my $ctype = $r->header('Content-Type');
1337 my ($ct, $boundary);
1338 ($ct, $boundary)= parse_content_type($ctype) if $ctype;
1340 if ($auth->{isUpload} && !$self->{trusted_env}) {
1341 die "upload
'Content-Type '$ctype' not implemented\n"
1342 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
1344 die "upload without content length header not supported" if !$len;
1346 die "upload without content length header not supported" if !$len;
1348 $self->dprint("start upload $path $ct $boundary");
1350 my $tmpfilename = get_upload_filename();
1351 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1352 die "unable to create temporary upload file '$tmpfilename'";
1354 $reqstate->{keep_alive} = 0;
1356 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1360 boundary => $boundary,
1361 ctx => Digest::MD5->new,
1362 boundlen => $boundlen,
1363 maxheader => 2048 + $boundlen, # should be large enough
1364 params => decode_urlencoded($r->url->query()),
1368 starttime => [gettimeofday],
1371 $reqstate->{tmpfilename} = $tmpfilename;
1372 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $method, $path, $state); });
1376 if ($len > $limit_max_post) {
1377 $self->error($reqstate, 501, "for data too large");
1381 if (!$ct || $ct eq 'application
/x-www-form-urlencoded' || $ct eq 'application/json
') {
1382 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1383 my ($hdl, $data) = @_;
1385 $self->handle_request($reqstate, $auth, $method, $path);
1388 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
1391 $self->handle_request($reqstate, $auth, $method, $path);
1393 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1394 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1395 ($state->{key}, $state->{val}) = ($1, $2);
1396 $self->unshift_read_header($reqstate, $state);
1397 } elsif ($line =~ /^\s+(.*)/) {
1398 $state->{val} .= " $1";
1399 $self->unshift_read_header($reqstate, $state);
1401 $self->error($reqstate, 506, "unable to parse request header
");
1408 sub push_request_header {
1409 my ($self, $reqstate) = @_;
1412 $reqstate->{hdl}->push_read(line => sub {
1413 my ($hdl, $line) = @_;
1416 # print "got request header
: $line\n" if $self->{debug};
1418 $reqstate->{keep_alive}--;
1420 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1421 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1424 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
1428 $self->{request_count}++; # only count valid request headers
1429 if ($self->{request_count} >= $self->{max_requests}) {
1430 $self->{end_loop} = 1;
1432 $reqstate->{log} = { requestline => $line };
1433 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
1434 $reqstate->{proto}->{maj} = $maj;
1435 $reqstate->{proto}->{min} = $min;
1436 $reqstate->{proto}->{ver} = $maj*1000+$min;
1437 $reqstate->{request} = HTTP::Request->new($method, $url);
1438 $reqstate->{starttime} = [gettimeofday],
1440 $self->unshift_read_header($reqstate);
1441 } elsif ($line eq '') {
1442 # ignore empty lines before requests (browser bugs?)
1443 $self->push_request_header($reqstate);
1445 $self->error($reqstate, 400, 'bad request');
1459 return if $self->{end_loop};
1461 # we need to m make sure that only one process calls accept
1462 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1463 next if $! == EINTR;
1464 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
1470 while (!$self->{end_loop} &&
1471 !defined($clientfh = $self->{socket}->accept()) &&
1474 if ($self->{end_loop}) {
1477 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1478 if (!defined($clientfh)) {
1479 $errmsg = "failed to
accept connection
: $!\n";
1485 flock($self->{lockfh}, Fcntl::LOCK_UN());
1487 if (!defined($clientfh)) {
1489 die $errmsg if $errmsg;
1492 fh_nonblocking $clientfh, 1;
1500 $self->{end_loop} = 1;
1502 undef $self->{socket_watch};
1504 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1506 if ($self->{conn_count} <= 0) {
1507 $self->{end_cond}->send(1);
1511 # fork and exit, so that parent starts a new worker
1516 # else we need to wait until all open connections gets closed
1517 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1519 # todo: test for active connections instead (we can abort idle connections)
1520 if ($self->{conn_count} <= 0) {
1522 $self->{end_cond}->send(1);
1530 sub check_host_access {
1531 my ($self, $clientip) = @_;
1533 my $cip = Net::IP->new($clientip);
1536 $self->dprint("client IP
not parsable
: $@");
1540 my $match_allow = 0;
1543 if ($self->{allow_from}) {
1544 foreach my $t (@{$self->{allow_from}}) {
1545 if ($t->overlaps($cip)) {
1547 $self->dprint("client IP allowed
: ". $t->prefix());
1553 if ($self->{deny_from}) {
1554 foreach my $t (@{$self->{deny_from}}) {
1555 if ($t->overlaps($cip)) {
1556 $self->dprint("client IP denied
: ". $t->prefix());
1563 if ($match_allow == $match_deny) {
1564 # match both allow and deny, or no match
1565 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1568 return $match_allow;
1571 sub accept_connections {
1574 my ($clientfh, $handle_creation);
1577 while ($clientfh = $self->accept()) {
1579 my $reqstate = { keep_alive => $self->{keep_alive} };
1581 # stop keep-alive when there are many open connections
1582 if ($self->{conn_count} + 1 >= $self->{max_conn_soft_limit}) {
1583 $reqstate->{keep_alive} = 0;
1586 if (my $sin = getpeername($clientfh)) {
1587 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1588 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1590 $self->dprint("getpeername failed
: $!");
1595 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1596 $self->dprint("ABORT request from
$reqstate->{peer_host
} - access denied
");
1597 $reqstate->{log}->{code} = 403;
1598 $self->log_request($reqstate);
1603 # Increment conn_count before creating new handle, since creation
1604 # triggers callbacks, which can potentialy decrement (e.g.
1605 # on_error) conn_count before AnyEvent::Handle->new() returns.
1606 $handle_creation = 1;
1607 $self->{conn_count}++;
1608 $reqstate->{hdl} = AnyEvent::Handle->new(
1610 rbuf_max => 64*1024,
1611 timeout => $self->{timeout},
1612 linger => 0, # avoid problems with ssh - really needed ?
1616 $self->log_aborted_request($reqstate);
1617 $self->client_do_disconnect($reqstate);
1619 if (my $err = $@) { syslog('err', $err); }
1622 my ($hdl, $fatal, $message) = @_;
1624 $self->log_aborted_request($reqstate, $message);
1625 $self->client_do_disconnect($reqstate);
1627 if (my $err = $@) { syslog('err', "$err"); }
1629 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1630 $handle_creation = 0;
1632 $self->dprint("ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}");
1634 $self->push_request_header($reqstate);
1639 syslog('err', $err);
1640 $self->dprint("connection
accept error
: $err");
1642 if ($handle_creation) {
1643 if ($self->{conn_count} <= 0) {
1644 warn "connection count
<= 0 not decrementing
!\n";
1646 $self->{conn_count}--;
1649 $self->{end_loop} = 1;
1652 $self->wait_end_loop() if $self->{end_loop};
1655 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1656 # because we write from multiple processes, and that would arbitrarily mix output
1658 sub open_access_log {
1659 my ($self, $filename) = @_;
1661 my $old_mask = umask(0137);;
1662 my $logfh = IO::File->new($filename, ">>") ||
1663 die "unable to
open log file
'$filename' - $!\n";
1666 $logfh->autoflush(1);
1668 $self->{logfh} = $logfh;
1672 my ($self, $data) = @_;
1674 return if !defined($self->{logfh}) || !$data;
1676 my $res = $self->{logfh}->print($data);
1679 delete $self->{logfh};
1680 syslog('err', "error writing access
log");
1681 $self->{end_loop} = 1; # terminate asap
1685 sub atfork_handler {
1689 # something else do to ?
1690 close($self->{socket});
1698 $self->{end_cond}->recv;
1702 my ($this, %args) = @_;
1704 my $class = ref($this) || $this;
1706 foreach my $req (qw(socket lockfh lockfile)) {
1707 die "misssing required argument '$req'" if !defined($args{$req});
1710 my $self = bless { %args }, $class;
1712 $self->{cookie_name
} //= 'PVEAuthCookie';
1713 $self->{apitoken_name
} //= 'PVEAPIToken';
1714 $self->{base_uri
} //= "/api2";
1715 $self->{dirs
} //= {};
1716 $self->{title
} //= 'API Inspector';
1717 $self->{compression
} //= 1;
1719 # formatter_config: we pass some configuration values to the Formatter
1720 $self->{formatter_config
} = {};
1721 foreach my $p (qw(apitoken_name cookie_name base_uri title)) {
1722 $self->{formatter_config
}->{$p} = $self->{$p};
1724 $self->{formatter_config
}->{csrfgen_func
} =
1725 $self->can('generate_csrf_prevention_token');
1727 # add default dirs which includes jquery and bootstrap
1728 my $jsbase = '/usr/share/javascript';
1729 add_dirs
($self->{dirs
}, '/js/' => "$jsbase/");
1730 # libjs-bootstrap uses symlinks for this, which we do not want to allow..
1731 my $glyphicons = '/usr/share/fonts/truetype/glyphicons/';
1732 add_dirs
($self->{dirs
}, '/js/bootstrap/fonts/' => "$glyphicons");
1735 PVE
::INotify
::inotify_init
();
1737 fh_nonblocking
($self->{socket}, 1);
1739 $self->{end_loop
} = 0;
1740 $self->{conn_count
} = 0;
1741 $self->{request_count
} = 0;
1742 $self->{timeout
} = 5 if !$self->{timeout
};
1743 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1744 $self->{max_conn
} = 800 if !$self->{max_conn
};
1745 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1747 $self->{policy
} = 'allow' if !$self->{policy
};
1749 $self->{end_cond
} = AnyEvent-
>condvar;
1752 my $ssl_defaults = {
1753 # Note: older versions are considered insecure, for example
1754 # search for "Poodle"-Attack
1758 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',
1759 honor_cipher_order
=> 1,
1762 foreach my $k (keys %$ssl_defaults) {
1763 $self->{ssl
}->{$k} //= $ssl_defaults->{$k};
1766 if (!defined($self->{ssl
}->{dh_file
})) {
1767 $self->{ssl
}->{dh
} = 'skip2048';
1770 my $tls_ctx_flags = &Net
::SSLeay
::OP_NO_COMPRESSION
| &Net
::SSLeay
::OP_SINGLE_ECDH_USE
| &Net
::SSLeay
::OP_SINGLE_DH_USE
;
1771 if ( delete $self->{ssl
}->{honor_cipher_order
} ) {
1772 $tls_ctx_flags |= &Net
::SSLeay
::OP_CIPHER_SERVER_PREFERENCE
;
1775 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
1776 Net
::SSLeay
::CTX_set_options
($self->{tls_ctx
}->{ctx
}, $tls_ctx_flags);
1779 if ($self->{spiceproxy
}) {
1780 $known_methods = { CONNECT
=> 1 };
1783 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
1785 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
1787 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
1789 if ($self->{conn_count
} >= $self->{max_conn
}) {
1790 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
1791 if ($self->{conn_count
} < $self->{max_conn
}) {
1793 $self->accept_connections();
1797 $self->accept_connections();
1803 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
1804 undef $self->{term_watch
};
1805 $self->wait_end_loop();
1808 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
1809 undef $self->{quit_watch
};
1810 $self->wait_end_loop();
1813 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
1814 PVE
::INotify
::poll
(); # read inotify events
1820 # static helper to add directory including all subdirs
1821 # This can be used to setup $self->{dirs}
1823 my ($result_hash, $alias, $subdir) = @_;
1825 $result_hash->{$alias} = $subdir;
1828 my $dir = $File::Find
::dir
;
1829 if ($dir =~m!^$subdir(.*)$!) {
1830 my $name = "$alias$1/";
1831 $result_hash->{$name} = "$dir/";
1835 find
({wanted
=> $wanted, follow
=> 0, no_chdir
=> 1}, $subdir);
1838 # abstract functions - subclass should overwrite/implement them
1840 sub verify_spice_connect_url
{
1841 my ($self, $connect_str) = @_;
1845 #return ($vmid, $node, $port);
1848 # formatters can call this when the generate a new page
1849 sub generate_csrf_prevention_token
{
1850 my ($username) = @_;
1852 return undef; # do nothing by default
1856 my ($self, $method, $rel_uri, $ticket, $token, $api_token, $peer_host) = @_;
1861 # ticket => $ticket,
1863 # userid => $username,
1865 # isUpload => $isUpload,
1866 # api_token => $api_token,
1871 my ($self, $clientip, $method, $rel_uri, $auth, $params, $format) = @_;
1873 # please do not raise exceptions here (always return a result).
1876 status
=> HTTP_NOT_IMPLEMENTED
,
1877 message
=> "Method '$method $rel_uri' not implemented",
1880 # this should return the following properties, which
1881 # are then passed to the Formatter
1883 # status: HTTP status code
1884 # message: Error message
1885 # errors: more detailed error hash (per parameter)
1886 # info: reference to JSON schema definition - useful to format output
1889 # total: additional info passed to output
1890 # changes: additional info passed to output
1892 # if you want to proxy the request to another node return this
1893 # { proxy => $remip, proxynode => $node, proxy_params => $params };
1895 # to pass the request to the local priviledged daemon use:
1896 # { proxy => 'localhost' , proxy_params => $params };
1898 # to download aspecific file use:
1899 # { download => "/path/to/file" };
1902 sub check_cert_fingerprint
{
1903 my ($self, $cert) = @_;
1908 sub initialize_cert_cache
{
1909 my ($self, $node) = @_;
1914 sub remote_node_ip
{
1915 my ($self, $node) = @_;