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);
48 my $limit_max_headers = 30;
49 my $limit_max_header_size = 8*1024;
50 my $limit_max_post = 64*1024;
59 my $split_abs_uri = sub {
60 my ($abs_uri, $base_uri) = @_;
62 my ($format, $rel_uri) = $abs_uri =~ m/^\Q$base_uri\E\/+([a-z
][a-z0-9
]+)(\
/.*)?$/;
63 $rel_uri = '/' if !$rel_uri;
65 return wantarray ?
($rel_uri, $format) : $rel_uri;
69 my ($self, $reqstate) = @_;
71 my $loginfo = $reqstate->{log};
73 # like apache2 common log format
74 # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
76 return if $loginfo->{written
}; # avoid duplicate logs
77 $loginfo->{written
} = 1;
79 my $peerip = $reqstate->{peer_host
} || '-';
80 my $userid = $loginfo->{userid
} || '-';
81 my $content_length = defined($loginfo->{content_length
}) ?
$loginfo->{content_length
} : '-';
82 my $code = $loginfo->{code
} || 500;
83 my $requestline = $loginfo->{requestline
} || '-';
84 my $timestr = strftime
("%d/%m/%Y:%H:%M:%S %z", localtime());
86 my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n";
88 $self->write_log($msg);
91 sub log_aborted_request {
92 my ($self, $reqstate, $error) = @_;
94 my $r = $reqstate->{request};
95 return if !$r; # no active request
98 syslog("err
", "problem with client
$reqstate->{peer_host
}; $error");
101 $self->log_request($reqstate);
104 sub cleanup_reqstate {
107 delete $reqstate->{log};
108 delete $reqstate->{request};
109 delete $reqstate->{proto};
110 delete $reqstate->{accept_gzip};
111 delete $reqstate->{starttime};
113 if ($reqstate->{tmpfilename}) {
114 unlink $reqstate->{tmpfilename};
115 delete $reqstate->{tmpfilename};
119 sub client_do_disconnect {
120 my ($self, $reqstate) = @_;
122 cleanup_reqstate($reqstate);
124 my $shutdown_hdl = sub {
127 shutdown($hdl->{fh}, 1);
129 $hdl->on_drain(undef);
130 $hdl->on_read(undef);
134 if (my $proxyhdl = delete $reqstate->{proxyhdl}) {
135 &$shutdown_hdl($proxyhdl);
138 my $hdl = delete $reqstate->{hdl};
141 syslog('err', "detected empty handle
");
145 print "close connection
$hdl\n" if $self->{debug};
147 &$shutdown_hdl($hdl);
149 $self->{conn_count}--;
151 print "$$: CLOSE FH
" . $hdl->{fh}->fileno() . " CONN
$self->{conn_count
}\n" if $self->{debug};
154 sub finish_response {
155 my ($self, $reqstate) = @_;
157 cleanup_reqstate($reqstate);
159 my $hdl = $reqstate->{hdl};
160 return if !$hdl; # already disconnected
162 if (!$self->{end_loop} && $reqstate->{keep_alive} > 0) {
163 # print "KEEPALIVE
$reqstate->{keep_alive
}\n" if $self->{debug};
165 eval { $self->push_request_header($reqstate); };
169 $hdl->on_drain (sub {
171 $self->client_do_disconnect($reqstate);
179 my ($self, $reqstate, $resp, $mtime, $nocomp, $delay) = @_;
181 #print "$$: send response
: " . Dumper($resp);
184 $reqstate->{hdl}->timeout_reset();
185 $reqstate->{hdl}->timeout($self->{timeout});
187 $nocomp = 1 if !$reqstate->{accept_gzip};
189 my $code = $resp->code;
190 my $msg = $resp->message || HTTP::Status::status_message($code);
191 ($msg) = $msg =~m/^(.*)$/m;
192 my $content = $resp->content;
194 if ($code =~ /^(1\d\d|[23]04)$/) {
195 # make sure content we have no content
199 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
201 $reqstate->{log}->{code} = $code;
203 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
204 my $res = "$proto $code $msg\015\012";
207 my $date = HTTP::Date::time2str($ctime);
208 $resp->header('Date' => $date);
210 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
212 $resp->header('Expires' => $date);
213 $resp->header('Cache-Control' => "max-age
=0");
214 $resp->header("Pragma
", "no-cache
");
217 $resp->header('Server' => "pve-api-daemon
/3.0");
222 $content_length = length($content);
224 if (!$nocomp && ($content_length > 1024)) {
225 my $comp = Compress::Zlib::memGzip($content);
226 $resp->header('Content-Encoding', 'gzip');
228 $content_length = length($content);
230 $resp->header("Content-Length
" => $content_length);
231 $reqstate->{log}->{content_length} = $content_length;
234 $resp->remove_header("Content-Length
");
237 if ($reqstate->{keep_alive} > 0) {
238 $resp->push_header('Connection' => 'Keep-Alive');
240 $resp->header('Connection' => 'close');
243 $res .= $resp->headers_as_string("\015\012");
244 #print "SEND
(without content
) $res\n" if $self->{debug};
247 $res .= $content if $content;
249 $self->log_request($reqstate, $reqstate->{request});
251 if ($delay && $delay > 0) {
252 my $w; $w = AnyEvent->timer(after => $delay, cb => sub {
253 undef $w; # delete reference
254 $reqstate->{hdl}->push_write($res);
255 $self->finish_response($reqstate);
258 $reqstate->{hdl}->push_write($res);
259 $self->finish_response($reqstate);
264 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
267 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
268 $self->response($reqstate, $resp);
273 my $file_extension_info = {
274 css => { ct => 'text/css' },
275 html => { ct => 'text/html' },
276 js => { ct => 'application/javascript' },
277 json => { ct => 'application/json' },
278 map => { ct => 'application/json' },
279 png => { ct => 'image/png' , nocomp => 1 },
280 ico => { ct => 'image/x-icon', nocomp => 1},
281 gif => { ct => 'image/gif', nocomp => 1},
282 svg => { ct => 'image/svg+xml' },
283 jar => { ct => 'application/java-archive', nocomp => 1},
284 woff => { ct => 'application/font-woff', nocomp => 1},
285 woff2 => { ct => 'application/font-woff2', nocomp => 1},
286 ttf => { ct => 'application/font-snft', nocomp => 1},
287 pdf => { ct => 'application/pdf', nocomp => 1},
288 epub => { ct => 'application/epub+zip', nocomp => 1},
289 mp3 => { ct => 'audio/mpeg', nocomp => 1},
290 oga => { ct => 'audio/ogg', nocomp => 1},
291 tgz => { ct => 'application/x-compressed-tar', nocomp => 1},
294 sub send_file_start {
295 my ($self, $reqstate, $filename) = @_;
298 # print "SEND FILE
$filename\n";
299 # Note: aio_load() this is not really async unless we use IO::AIO!
302 my $r = $reqstate->{request};
304 my $fh = IO::File->new($filename, '<') ||
306 my $stat = File::stat::stat($fh) ||
309 my $mtime = $stat->mtime;
311 if (my $ifmod = $r->header('if-modified-since')) {
312 my $iftime = HTTP::Date::str2time($ifmod);
313 if ($mtime <= $iftime) {
314 my $resp = HTTP::Response->new(304, "NOT MODIFIED
");
315 $self->response($reqstate, $resp, $mtime);
321 my $len = sysread($fh, $data, $stat->size);
322 die "got short file
\n" if !defined($len) || $len != $stat->size;
324 my ($ext) = $filename =~ m/\.([^.]*)$/;
325 my $ext_info = $file_extension_info->{$ext};
327 die "unable to detect content type
" if !$ext_info;
329 my $header = HTTP::Headers->new(Content_Type => $ext_info->{ct});
330 my $resp = HTTP::Response->new(200, "OK
", $header, $data);
331 $self->response($reqstate, $resp, $mtime, $ext_info->{nocomp});
334 $self->error($reqstate, 501, $err);
341 sub websocket_proxy {
342 my ($self, $reqstate, $wsaccept, $wsproto, $param) = @_;
348 my $max_payload_size = 65536;
351 if ($wsproto eq 'binary') {
353 } elsif ($wsproto eq 'base64') {
356 die "websocket_proxy
: unsupported protocol
'$wsproto'\n";
359 if ($param->{port}) {
360 $remhost = 'localhost';
361 $remport = $param->{port};
362 } elsif ($param->{socket}) {
364 $remport = $param->{socket};
366 die "websocket_proxy
: missing port
or socket\n";
369 tcp_connect $remhost, $remport, sub {
371 or die "connect to
'$remhost:$remport' failed
: $!";
373 print "$$: CONNECTed to
'$remhost:$remport'\n" if $self->{debug};
375 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
378 wbuf_max => 64*10*1024,
383 $self->log_aborted_request($reqstate);
384 $self->client_do_disconnect($reqstate);
386 if (my $err = $@) { syslog('err', $err); }
389 my ($hdl, $fatal, $message) = @_;
391 $self->log_aborted_request($reqstate, $message);
392 $self->client_do_disconnect($reqstate);
394 if (my $err = $@) { syslog('err', "$err"); }
397 my $proxyhdlreader = sub {
400 my $len = length($hdl->{rbuf});
401 my $data = substr($hdl->{rbuf}, 0, $len, '');
407 $string = "\x82"; # binary frame
410 $string = "\x81"; # text frame
411 $payload = encode_base64($data, '');
414 my $payload_len = length($payload);
415 if ($payload_len <= 125) {
416 $string .= pack 'C', $payload_len;
417 } elsif ($payload_len <= 0xffff) {
418 $string .= pack 'C', 126;
419 $string .= pack 'n', $payload_len;
421 $string .= pack 'C', 127;
422 $string .= pack 'Q>', $payload_len;
426 $reqstate->{hdl}->push_write($string) if $reqstate->{hdl};
429 my $hdlreader = sub {
432 my $len = length($hdl->{rbuf});
435 my $hdr = unpack('C', substr($hdl->{rbuf}, 0, 1));
436 my $opcode = $hdr & 0b00001111;
437 my $fin = $hdr & 0b10000000;
439 die "received fragmented websocket frame
\n" if !$fin;
441 my $rsv = $hdr & 0b01110000;
442 die "received websocket frame with RSV flags
\n" if $rsv;
444 my $payload_len = unpack 'C', substr($hdl->{rbuf}, 1, 1);
446 my $masked = $payload_len & 0b10000000;
447 die "received unmasked websocket frame from client
\n" if !$masked;
450 $payload_len = $payload_len & 0b01111111;
451 if ($payload_len == 126) {
453 $payload_len = unpack('n', substr($hdl->{rbuf}, $offset, 2));
455 } elsif ($payload_len == 127) {
457 $payload_len = unpack('Q>', substr($hdl->{rbuf}, $offset, 8));
461 die "received too large websocket frame
(len
= $payload_len)\n"
462 if ($payload_len > $max_payload_size) || ($payload_len < 0);
464 return if $len < ($offset + 4 + $payload_len);
466 my $data = substr($hdl->{rbuf}, 0, $len, ''); # now consume data
468 my @mask = (unpack('C', substr($data, $offset+0, 1)),
469 unpack('C', substr($data, $offset+1, 1)),
470 unpack('C', substr($data, $offset+2, 1)),
471 unpack('C', substr($data, $offset+3, 1)));
475 my $payload = substr($data, $offset, $payload_len);
477 for (my $i = 0; $i < $payload_len; $i++) {
478 my $d = unpack('C', substr($payload, $i, 1));
479 my $n = $d ^ $mask[$i % 4];
480 substr($payload, $i, 1, pack('C', $n));
483 $payload = decode_base64($payload) if !$binary;
485 if ($opcode == 1 || $opcode == 2) {
486 $reqstate->{proxyhdl}->push_write($payload) if $reqstate->{proxyhdl};
487 } elsif ($opcode == 8) {
488 my $statuscode = unpack ("n
", $payload);
489 print "websocket received
close. status code
: '$statuscode'\n" if $self->{debug};
490 if ($reqstate->{proxyhdl}) {
491 $reqstate->{proxyhdl}->push_shutdown();
493 $hdl->push_shutdown();
495 die "received unhandled websocket opcode
$opcode\n";
499 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.1';
501 $reqstate->{proxyhdl}->timeout(0);
502 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
503 $reqstate->{hdl}->on_read($hdlreader);
505 # todo: use stop_read/start_read if write buffer grows to much
507 my $res = "$proto 101 Switching Protocols
\015\012" .
508 "Upgrade
: websocket
\015\012" .
509 "Connection
: upgrade
\015\012" .
510 "Sec-WebSocket-Accept
: $wsaccept\015\012" .
511 "Sec-WebSocket-Protocol
: $wsproto\015\012" .
514 print $res if $self->{debug};
516 $reqstate->{hdl}->push_write($res);
519 $reqstate->{log}->{code} = 101;
520 $self->log_request($reqstate);
526 $self->log_aborted_request($reqstate, $err);
527 $self->client_do_disconnect($reqstate);
532 my ($self, $reqstate, $clientip, $host, $node, $method, $uri, $ticket, $token, $params) = @_;
537 if ($host eq 'localhost') {
538 $target = "http
://$host:85$uri";
539 # keep alive for localhost is not worth (connection setup is about 0.2ms)
541 } elsif (Net::IP::ip_is_ipv6($host)) {
542 $target = "https
://[$host]:8006$uri";
544 $target = "https
://$host:8006$uri";
548 PVEDisableProxy => 'true',
549 PVEClientIP => $clientip,
552 $headers->{'cookie'} = PVE::APIServer::Formatter::create_auth_cookie($ticket, $self->{cookie_name}) if $ticket;
553 $headers->{'CSRFPreventionToken'} = $token if $token;
554 $headers->{'Accept-Encoding'} = 'gzip' if $reqstate->{accept_gzip};
558 if ($method eq 'POST' || $method eq 'PUT') {
559 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
560 # use URI object to format application/x-www-form-urlencoded content.
561 my $url = URI->new('http:');
562 $url->query_form(%$params);
563 $content = $url->query;
564 if (defined($content)) {
565 $headers->{'Content-Length'} = length($content);
570 # TLS 1.x only, with certificate pinning
576 my (undef, undef, undef, $depth, undef, undef, $cert) = @_;
577 # we don't care about intermediate or root certificates
578 return 1 if $depth != 0;
579 # check server certificate against cache of pinned FPs
580 return $self->check_cert_fingerprint($cert);
584 # load and cache cert fingerprint if first time we proxy to this node
585 $self->initialize_cert_cache($node);
587 my $w; $w = http_request(
592 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
593 keepalive => $keep_alive,
595 tls_ctx => AnyEvent::TLS->new(%{$tls}),
597 my ($body, $hdr) = @_;
601 if (!$reqstate->{hdl}) {
602 warn "proxy detected vanished client connection
\n";
607 my $code = delete $hdr->{Status};
608 my $msg = delete $hdr->{Reason};
610 delete $hdr->{HTTPVersion};
611 my $header = HTTP::Headers->new(%$hdr);
612 if (my $location = $header->header('Location')) {
613 $location =~ s|^http://localhost:85||;
614 $header->header(Location => $location);
616 my $resp = HTTP::Response->new($code, $msg, $header, $body);
617 # Note: disable compression, because body is already compressed
618 $self->response($reqstate, $resp, undef, 1);
626 # return arrays as \0 separated strings (like CGI.pm)
627 # assume data is UTF8 encoded
628 sub decode_urlencoded {
633 return $res if !$data;
635 foreach my $kv (split(/[\&\;]/, $data)) {
636 my ($k, $v) = split(/=/, $kv);
638 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
640 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
642 $v = Encode::decode('utf8', $v);
644 if (defined(my $old = $res->{$k})) {
645 $res->{$k} = "$old\0$v";
654 my ($r, $method) = @_;
658 if ($method eq 'PUT' || $method eq 'POST') {
659 $params = decode_urlencoded($r->content);
662 my $query_params = decode_urlencoded($r->url->query());
664 foreach my $k (keys %{$query_params}) {
665 $params->{$k} = $query_params->{$k};
671 sub handle_api2_request {
672 my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
675 my $r = $reqstate->{request};
677 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
679 my $formatter = PVE::APIServer::Formatter::get_formatter($format, $method, $rel_uri);
681 if (!defined($formatter)) {
682 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no formatter
for uri
$rel_uri, $format");
686 #print Dumper($upload_state) if $upload_state;
691 $params = $upload_state->{params};
693 $params = extract_params($r, $method);
696 delete $params->{_dc}; # remove disable cache parameter
698 my $clientip = $reqstate->{peer_host};
700 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
703 Net::SSLeay::ERR_clear_error();
705 AnyEvent->now_update(); # in case somebody called sleep()
707 my $upgrade = $r->header('upgrade');
708 $upgrade = lc($upgrade) if $upgrade;
710 if (my $host = $res->{proxy}) {
712 if ($self->{trusted_env}) {
713 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
717 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
718 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
722 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
724 $self->proxy_request($reqstate, $clientip, $host, $res->{proxynode}, $method,
725 $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params}, $res->{proxynode});
728 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
729 die "unable to upgrade to protocol
'$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
730 my $wsver = $r->header('sec-websocket-version');
731 die "unsupported websocket-version
'$wsver'\n" if !$wsver || ($wsver ne '13');
732 my $wsproto_str = $r->header('sec-websocket-protocol');
733 die "missing websocket-protocol header
" if !$wsproto_str;
735 foreach my $p (PVE::Tools::split_list($wsproto_str)) {
736 $wsproto = $p if !$wsproto && $p eq 'base64';
737 $wsproto = $p if $p eq 'binary';
739 die "unsupported websocket-protocol protocol
'$wsproto_str'\n" if !$wsproto;
740 my $wskey = $r->header('sec-websocket-key');
741 die "missing websocket-key
\n" if !$wskey;
742 # Note: Digest::SHA::sha1_base64 has wrong padding
743 my $wsaccept = Digest::SHA::sha1_base64("${wskey
}258EAFA5-E914-47DA-95CA-C5AB0DC85B11
") . "=";
744 if ($res->{status} == HTTP_OK) {
745 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
751 if ($res->{status} == HTTP_UNAUTHORIZED) {
752 # always delay unauthorized calls by 3 seconds
753 $delay = 3 - tv_interval($reqstate->{starttime});
754 $delay = 0 if $delay < 0;
757 if (defined(my $filename = $res->{download})) {
758 my $fh = IO::File->new($filename) ||
759 die "unable to
open file
'$filename' - $!\n";
760 send_file_start($self, $reqstate, $filename);
764 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
765 $auth, $self->{formatter_config});
768 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
771 $resp = HTTP::Response->new($res->{status}, $res->{message});
772 $resp->header("Content-Type
" => $ct);
773 $resp->content($raw);
775 $self->response($reqstate, $resp, undef, $nocomp, $delay);
778 $self->error($reqstate, 501, $err);
782 sub handle_spice_proxy_request {
783 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
787 die "Port
$spiceport is not allowed
" if ($spiceport < 61000 || $spiceport > 61099);
789 my $clientip = $reqstate->{peer_host};
790 my $r = $reqstate->{request};
794 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
795 $remip = $self->remote_node_ip($node);
796 print "REMOTE CONNECT
$vmid, $remip, $connect_str\n" if $self->{debug};
798 print "$$: CONNECT
$vmid, $node, $spiceport\n" if $self->{debug};
801 if ($remip && $r->header('PVEDisableProxy')) {
802 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
806 $reqstate->{hdl}->timeout(0);
807 $reqstate->{hdl}->wbuf_max(64*10*1024);
809 my $remhost = $remip ? $remip : "localhost
";
810 my $remport = $remip ? 3128 : $spiceport;
812 tcp_connect $remhost, $remport, sub {
814 or die "connect to
'$remhost:$remport' failed
: $!";
816 print "$$: CONNECTed to
'$remhost:$remport'\n" if $self->{debug};
817 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
820 wbuf_max => 64*10*1024,
825 $self->log_aborted_request($reqstate);
826 $self->client_do_disconnect($reqstate);
828 if (my $err = $@) { syslog('err', $err); }
831 my ($hdl, $fatal, $message) = @_;
833 $self->log_aborted_request($reqstate, $message);
834 $self->client_do_disconnect($reqstate);
836 if (my $err = $@) { syslog('err', "$err"); }
840 my $proxyhdlreader = sub {
843 my $len = length($hdl->{rbuf});
844 my $data = substr($hdl->{rbuf}, 0, $len, '');
846 #print "READ1
$len\n";
847 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
850 my $hdlreader = sub {
853 my $len = length($hdl->{rbuf});
854 my $data = substr($hdl->{rbuf}, 0, $len, '');
856 #print "READ0
$len\n";
857 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
860 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
862 my $startproxy = sub {
863 $reqstate->{proxyhdl}->timeout(0);
864 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
865 $reqstate->{hdl}->on_read($hdlreader);
867 # todo: use stop_read/start_read if write buffer grows to much
869 my $res = "$proto 200 OK
\015\012"; # hope this is the right answer?
870 $reqstate->{hdl}->push_write($res);
873 $reqstate->{log}->{code} = 200;
874 $self->log_request($reqstate);
878 my $header = "CONNECT
${connect_str
} $proto\015\012" .
879 "Host
: ${connect_str
}\015\012" .
880 "Proxy-Connection
: keep-alive
\015\012" .
881 "User-Agent
: spiceproxy
\015\012" .
882 "PVEDisableProxy
: true
\015\012" .
883 "PVEClientIP
: $clientip\015\012" .
886 $reqstate->{proxyhdl}->push_write($header);
887 $reqstate->{proxyhdl}->push_read(line => sub {
888 my ($hdl, $line) = @_;
890 if ($line =~ m!^$proto 200 OK$!) {
893 $reqstate->{hdl}->push_write($line);
894 $self->client_do_disconnect($reqstate);
905 $self->log_aborted_request($reqstate, $err);
906 $self->client_do_disconnect($reqstate);
911 my ($self, $reqstate, $auth, $method, $path) = @_;
913 my $base_uri = $self->{base_uri};
916 my $r = $reqstate->{request};
918 # disable timeout on handle (we already have all data we need)
919 # we re-enable timeout in response()
920 $reqstate->{hdl}->timeout(0);
922 if ($path =~ m/^\Q$base_uri\E/) {
923 $self->handle_api2_request($reqstate, $auth, $method, $path);
927 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
928 if (ref($handler) eq 'CODE') {
929 my $params = decode_urlencoded($r->url->query());
930 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
932 Net::SSLeay::ERR_clear_error();
933 $self->response($reqstate, $resp);
934 } elsif (ref($handler) eq 'HASH') {
935 if (my $filename = $handler->{file}) {
936 my $fh = IO::File->new($filename) ||
937 die "unable to
open file
'$filename' - $!\n";
938 send_file_start($self, $reqstate, $filename);
940 die "internal error
- no handler
";
943 die "internal error
- no handler
";
948 if ($self->{dirs} && ($method eq 'GET')) {
949 # we only allow simple names
950 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
951 my ($subdir, $file) = ($1, $2);
952 if (my $dir = $self->{dirs}->{$subdir}) {
953 my $filename = "$dir$file";
954 my $fh = IO::File->new($filename) ||
955 die "unable to
open file
'$filename' - $!\n";
956 send_file_start($self, $reqstate, $filename);
962 die "no such file
'$path'\n";
965 $self->error($reqstate, 501, $err);
969 sub file_upload_multipart {
970 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
973 my $boundary = $rstate->{boundary};
974 my $hdl = $reqstate->{hdl};
976 my $startlen = length($hdl->{rbuf});
978 if ($rstate->{phase} == 0) { # skip everything until start
979 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
980 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
982 my ($ct, $disp, $name, $filename);
983 foreach my $line (split(/\015?\012/, $header)) {
984 # assume we have single line headers
985 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
986 $ct = parse_content_type($1);
987 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
988 ($disp, $name, $filename) = parse_content_disposition($1);
992 if (!($disp && $disp eq 'form-data' && $name)) {
993 syslog('err', "wrong content disposition
in multipart
- abort upload
");
994 $rstate->{phase} = -1;
997 $rstate->{fieldname} = $name;
1000 if ($name eq 'filename') {
1001 # found file upload data
1002 $rstate->{phase} = 1;
1003 $rstate->{filename} = $filename;
1005 syslog('err', "wrong field name
for file upload
- abort upload
");
1006 $rstate->{phase} = -1;
1009 # found form data for field $name
1010 $rstate->{phase} = 2;
1014 my $len = length($hdl->{rbuf});
1015 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
1016 if $len > $rstate->{maxheader}; # skip garbage
1018 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
1019 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1020 my ($rest, $eof) = ($1, $3);
1021 my $len = length($rest);
1022 die "write to temporary file failed
- $!"
1023 if syswrite($rstate->{outfh}, $rest) != $len;
1024 $rstate->{ctx}->add($rest);
1025 $rstate->{params}->{filename} = $rstate->{filename};
1026 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
1027 $rstate->{bytes} += $len;
1028 $rstate->{phase} = $eof ? 100 : 0;
1030 my $len = length($hdl->{rbuf});
1031 my $wlen = $len - $rstate->{boundlen};
1033 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
1034 die "write to temporary file failed
- $!"
1035 if syswrite($rstate->{outfh}, $data) != $wlen;
1036 $rstate->{bytes} += $wlen;
1037 $rstate->{ctx}->add($data);
1040 } elsif ($rstate->{phase} == 2) { # inside normal field
1042 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1043 my ($rest, $eof) = ($1, $3);
1044 my $len = length($rest);
1045 $rstate->{post_size} += $len;
1046 if ($rstate->{post_size} < $limit_max_post) {
1047 $rstate->{params}->{$rstate->{fieldname}} = $rest;
1048 $rstate->{phase} = $eof ? 100 : 0;
1050 syslog('err', "form data to large
- abort upload
");
1051 $rstate->{phase} = -1; # skip
1055 my $len = length($hdl->{rbuf});
1056 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
1059 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
1061 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
1062 $rstate->{done} = 1; # make sure we dont get called twice
1063 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
1064 die "upload failed
\n";
1066 my $elapsed = tv_interval($rstate->{starttime});
1068 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
1069 syslog('info', "multipart upload complete
" .
1070 "(size
: %d time: %ds rate
: %.2fMiB
/s md5sum
: $rstate->{md5sum
})",
1071 $rstate->{bytes}, $elapsed, $rate);
1072 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1077 syslog('err', $err);
1078 $self->error($reqstate, 501, $err);
1082 sub parse_content_type {
1085 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
1087 foreach my $v (@params) {
1088 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1089 return wantarray ? ($ct, $1) : $ct;
1093 return wantarray ? ($ct) : $ct;
1096 sub parse_content_disposition {
1099 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
1103 foreach my $v (@params) {
1104 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
1106 $name =~ s/^"(.*)"$/$1/;
1107 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
1109 $filename =~ s/^"(.*)"$/$1/;
1113 return wantarray ? ($disp, $name, $filename) : $disp;
1116 my $tmpfile_seq_no = 0;
1118 sub get_upload_filename {
1119 # choose unpredictable tmpfile name
1122 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1125 sub unshift_read_header {
1126 my ($self, $reqstate, $state) = @_;
1128 $state = { size => 0, count => 0 } if !$state;
1130 $reqstate->{hdl}->unshift_read(line => sub {
1131 my ($hdl, $line) = @_;
1134 # print "$$: got header
: $line\n" if $self->{debug};
1136 die "to many http header lines
\n" if ++$state->{count} >= $limit_max_headers;
1137 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1139 my $r = $reqstate->{request};
1142 my $path = uri_unescape($r->uri->path());
1143 my $method = $r->method();
1145 $r->push_header($state->{key}, $state->{val})
1148 if (!$known_methods->{$method}) {
1149 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
1150 $self->response($reqstate, $resp);
1154 my $conn = $r->header('Connection');
1155 my $accept_enc = $r->header('Accept-Encoding');
1156 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1159 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1161 if ($reqstate->{proto}->{ver} < 1001) {
1162 $reqstate->{keep_alive} = 0;
1166 my $te = $r->header('Transfer-Encoding');
1167 if ($te && lc($te) eq 'chunked') {
1168 # Handle chunked transfer encoding
1169 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
1172 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
1176 my $pveclientip = $r->header('PVEClientIP');
1177 my $base_uri = $self->{base_uri};
1179 # fixme: how can we make PVEClientIP header trusted?
1180 if ($self->{trusted_env} && $pveclientip) {
1181 $reqstate->{peer_host} = $pveclientip;
1183 $r->header('PVEClientIP', $reqstate->{peer_host});
1186 my $len = $r->header('Content-Length');
1188 # header processing complete - authenticate now
1191 if ($self->{spiceproxy}) {
1192 my $connect_str = $r->header('Host');
1193 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
1194 if (!(defined($vmid) && $node && $port)) {
1195 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket
");
1198 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1200 } elsif ($path =~ m/^\Q$base_uri\E/) {
1201 my $token = $r->header('CSRFPreventionToken');
1202 my $cookie = $r->header('Cookie');
1203 my $ticket = PVE::APIServer::Formatter::extract_auth_cookie($cookie, $self->{cookie_name});
1205 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1207 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
1212 $auth = $self->auth_handler($method, $rel_uri, $ticket, $token,
1213 $reqstate->{peer_host});
1217 Net::SSLeay::ERR_clear_error();
1218 # always delay unauthorized calls by 3 seconds
1221 if (ref($err) eq "PVE
::Exception
") {
1223 $err->{code} ||= HTTP_INTERNAL_SERVER_ERROR,
1224 my $resp = HTTP::Response->new($err->{code}, $err->{msg});
1225 $self->response($reqstate, $resp, undef, 0, $delay);
1227 } elsif (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
1228 my ($raw, $ct, $nocomp) =
1229 $formatter->($path, $auth, $self->{formatter_config});
1231 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1234 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required
");
1235 $resp->header("Content-Type
" => $ct);
1236 $resp->content($raw);
1238 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1240 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1241 $self->response($reqstate, $resp, undef, 0, $delay);
1247 $reqstate->{log}->{userid} = $auth->{userid};
1251 if (!($method eq 'PUT' || $method eq 'POST')) {
1252 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
1256 my $ctype = $r->header('Content-Type');
1257 my ($ct, $boundary) = parse_content_type($ctype) if $ctype;
1259 if ($auth->{isUpload} && !$self->{trusted_env}) {
1260 die "upload
'Content-Type '$ctype' not implemented\n"
1261 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
1263 die "upload without content length header not supported" if !$len;
1265 die "upload without content length header not supported" if !$len;
1267 print "start upload $path $ct $boundary\n" if $self->{debug};
1269 my $tmpfilename = get_upload_filename();
1270 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1271 die "unable to create temporary upload file '$tmpfilename'";
1273 $reqstate->{keep_alive} = 0;
1275 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1279 boundary => $boundary,
1280 ctx => Digest::MD5->new,
1281 boundlen => $boundlen,
1282 maxheader => 2048 + $boundlen, # should be large enough
1283 params => decode_urlencoded($r->url->query()),
1287 starttime => [gettimeofday],
1290 $reqstate->{tmpfilename} = $tmpfilename;
1291 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $method, $path, $state); });
1295 if ($len > $limit_max_post) {
1296 $self->error($reqstate, 501, "for data too large");
1300 if (!$ct || $ct eq 'application
/x-www-form-urlencoded
') {
1301 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1302 my ($hdl, $data) = @_;
1304 $self->handle_request($reqstate, $auth, $method, $path);
1307 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
1310 $self->handle_request($reqstate, $auth, $method, $path);
1312 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1313 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1314 ($state->{key}, $state->{val}) = ($1, $2);
1315 $self->unshift_read_header($reqstate, $state);
1316 } elsif ($line =~ /^\s+(.*)/) {
1317 $state->{val} .= " $1";
1318 $self->unshift_read_header($reqstate, $state);
1320 $self->error($reqstate, 506, "unable to parse request header
");
1327 sub push_request_header {
1328 my ($self, $reqstate) = @_;
1331 $reqstate->{hdl}->push_read(line => sub {
1332 my ($hdl, $line) = @_;
1335 # print "got request header
: $line\n" if $self->{debug};
1337 $reqstate->{keep_alive}--;
1339 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1340 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1343 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
1347 $self->{request_count}++; # only count valid request headers
1348 if ($self->{request_count} >= $self->{max_requests}) {
1349 $self->{end_loop} = 1;
1351 $reqstate->{log} = { requestline => $line };
1352 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
1353 $reqstate->{proto}->{maj} = $maj;
1354 $reqstate->{proto}->{min} = $min;
1355 $reqstate->{proto}->{ver} = $maj*1000+$min;
1356 $reqstate->{request} = HTTP::Request->new($method, $url);
1357 $reqstate->{starttime} = [gettimeofday],
1359 $self->unshift_read_header($reqstate);
1360 } elsif ($line eq '') {
1361 # ignore empty lines before requests (browser bugs?)
1362 $self->push_request_header($reqstate);
1364 $self->error($reqstate, 400, 'bad request');
1378 return if $self->{end_loop};
1380 # we need to m make sure that only one process calls accept
1381 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1382 next if $! == EINTR;
1383 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
1389 while (!$self->{end_loop} &&
1390 !defined($clientfh = $self->{socket}->accept()) &&
1393 if ($self->{end_loop}) {
1396 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1397 if (!defined($clientfh)) {
1398 $errmsg = "failed to
accept connection
: $!\n";
1404 flock($self->{lockfh}, Fcntl::LOCK_UN());
1406 if (!defined($clientfh)) {
1408 die $errmsg if $errmsg;
1411 fh_nonblocking $clientfh, 1;
1413 $self->{conn_count}++;
1421 $self->{end_loop} = 1;
1423 undef $self->{socket_watch};
1425 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1427 if ($self->{conn_count} <= 0) {
1428 $self->{end_cond}->send(1);
1432 # fork and exit, so that parent starts a new worker
1437 # else we need to wait until all open connections gets closed
1438 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1440 # todo: test for active connections instead (we can abort idle connections)
1441 if ($self->{conn_count} <= 0) {
1443 $self->{end_cond}->send(1);
1451 sub check_host_access {
1452 my ($self, $clientip) = @_;
1454 my $cip = Net::IP->new($clientip);
1456 my $match_allow = 0;
1459 if ($self->{allow_from}) {
1460 foreach my $t (@{$self->{allow_from}}) {
1461 if ($t->overlaps($cip)) {
1468 if ($self->{deny_from}) {
1469 foreach my $t (@{$self->{deny_from}}) {
1470 if ($t->overlaps($cip)) {
1477 if ($match_allow == $match_deny) {
1478 # match both allow and deny, or no match
1479 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1482 return $match_allow;
1485 sub accept_connections {
1490 while (my $clientfh = $self->accept()) {
1492 my $reqstate = { keep_alive => $self->{keep_alive} };
1494 # stop keep-alive when there are many open connections
1495 if ($self->{conn_count} >= $self->{max_conn_soft_limit}) {
1496 $reqstate->{keep_alive} = 0;
1499 if (my $sin = getpeername($clientfh)) {
1500 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1501 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1504 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1505 print "$$: ABORT request from
$reqstate->{peer_host
} - access denied
\n" if $self->{debug};
1506 $reqstate->{log}->{code} = 403;
1507 $self->log_request($reqstate);
1511 $reqstate->{hdl} = AnyEvent::Handle->new(
1513 rbuf_max => 64*1024,
1514 timeout => $self->{timeout},
1515 linger => 0, # avoid problems with ssh - really needed ?
1519 $self->log_aborted_request($reqstate);
1520 $self->client_do_disconnect($reqstate);
1522 if (my $err = $@) { syslog('err', $err); }
1525 my ($hdl, $fatal, $message) = @_;
1527 $self->log_aborted_request($reqstate, $message);
1528 $self->client_do_disconnect($reqstate);
1530 if (my $err = $@) { syslog('err', "$err"); }
1532 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1534 print "$$: ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}\n" if $self->{debug};
1536 $self->push_request_header($reqstate);
1541 syslog('err', $err);
1542 $self->{end_loop} = 1;
1545 $self->wait_end_loop() if $self->{end_loop};
1548 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1549 # because we write from multiple processes, and that would arbitrarily mix output
1551 sub open_access_log {
1552 my ($self, $filename) = @_;
1554 my $old_mask = umask(0137);;
1555 my $logfh = IO::File->new($filename, ">>") ||
1556 die "unable to
open log file
'$filename' - $!\n";
1559 $logfh->autoflush(1);
1561 $self->{logfh} = $logfh;
1565 my ($self, $data) = @_;
1567 return if !defined($self->{logfh}) || !$data;
1569 my $res = $self->{logfh}->print($data);
1572 delete $self->{logfh};
1573 syslog('err', "error writing access
log");
1574 $self->{end_loop} = 1; # terminate asap
1578 sub atfork_handler {
1582 # something else do to ?
1583 close($self->{socket});
1591 $self->{end_cond}->recv;
1595 my ($this, %args) = @_;
1597 my $class = ref($this) || $this;
1599 foreach my $req (qw(socket lockfh lockfile)) {
1600 die "misssing required argument '$req'" if !defined($args{$req});
1603 my $self = bless { %args }, $class;
1605 $self->{cookie_name
} //= 'PVEAuthCookie';
1606 $self->{base_uri
} //= "/api2";
1607 $self->{dirs
} //= {};
1608 $self->{title
} //= 'API Inspector';
1610 # formatter_config: we pass some configuration values to the Formatter
1611 $self->{formatter_config
} = {};
1612 foreach my $p (qw(cookie_name base_uri title)) {
1613 $self->{formatter_config
}->{$p} = $self->{$p};
1615 $self->{formatter_config
}->{csrfgen_func
} =
1616 $self->can('generate_csrf_prevention_token');
1618 # add default dirs which includes jquery and bootstrap
1619 my $base = '/usr/share/libpve-http-server-perl';
1620 add_dirs
($self->{dirs
}, '/css/' => "$base/css/");
1621 add_dirs
($self->{dirs
}, '/js/' => "$base/js/");
1622 add_dirs
($self->{dirs
}, '/fonts/' => "$base/fonts/");
1625 PVE
::INotify
::inotify_init
();
1627 fh_nonblocking
($self->{socket}, 1);
1629 $self->{end_loop
} = 0;
1630 $self->{conn_count
} = 0;
1631 $self->{request_count
} = 0;
1632 $self->{timeout
} = 5 if !$self->{timeout
};
1633 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1634 $self->{max_conn
} = 800 if !$self->{max_conn
};
1635 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1637 $self->{policy
} = 'allow' if !$self->{policy
};
1639 $self->{end_cond
} = AnyEvent-
>condvar;
1642 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
1643 Net
::SSLeay
::CTX_set_options
($self->{tls_ctx
}->{ctx
}, &Net
::SSLeay
::OP_NO_COMPRESSION
| &Net
::SSLeay
::OP_SINGLE_ECDH_USE
| &Net
::SSLeay
::OP_SINGLE_DH_USE
);
1646 if ($self->{spiceproxy
}) {
1647 $known_methods = { CONNECT
=> 1 };
1650 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
1652 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
1654 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
1656 if ($self->{conn_count
} >= $self->{max_conn
}) {
1657 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
1658 if ($self->{conn_count
} < $self->{max_conn
}) {
1660 $self->accept_connections();
1664 $self->accept_connections();
1670 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
1671 undef $self->{term_watch
};
1672 $self->wait_end_loop();
1675 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
1676 undef $self->{quit_watch
};
1677 $self->wait_end_loop();
1680 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
1681 PVE
::INotify
::poll
(); # read inotify events
1687 # static helper to add directory including all subdirs
1688 # This can be used to setup $self->{dirs}
1690 my ($result_hash, $alias, $subdir) = @_;
1692 $result_hash->{$alias} = $subdir;
1695 my $dir = $File::Find
::dir
;
1696 if ($dir =~m!^$subdir(.*)$!) {
1697 my $name = "$alias$1/";
1698 $result_hash->{$name} = "$dir/";
1702 find
({wanted
=> $wanted, follow
=> 0, no_chdir
=> 1}, $subdir);
1705 # abstract functions - subclass should overwrite/implement them
1707 sub verify_spice_connect_url
{
1708 my ($self, $connect_str) = @_;
1712 #return ($vmid, $node, $port);
1715 # formatters can call this when the generate a new page
1716 sub generate_csrf_prevention_token
{
1717 my ($username) = @_;
1719 return undef; # do nothing by default
1723 my ($self, $method, $rel_uri, $ticket, $token, $peer_host) = @_;
1728 # ticket => $ticket,
1730 # userid => $username,
1732 # isUpload => $isUpload,
1737 my ($self, $clientip, $method, $rel_uri, $auth, $params, $format) = @_;
1739 # please do not raise exceptions here (always return a result).
1742 status
=> HTTP_NOT_IMPLEMENTED
,
1743 message
=> "Method '$method $rel_uri' not implemented",
1746 # this should return the following properties, which
1747 # are then passed to the Formatter
1749 # status: HTTP status code
1750 # message: Error message
1751 # errors: more detailed error hash (per parameter)
1752 # info: reference to JSON schema definition - useful to format output
1755 # total: additional info passed to output
1756 # changes: additional info passed to output
1758 # if you want to proxy the request to another node return this
1759 # { proxy => $remip, proxynode => $node, proxy_params => $params };
1761 # to pass the request to the local priviledged daemon use:
1762 # { proxy => 'localhost' , proxy_params => $params };
1764 # to download aspecific file use:
1765 # { download => "/path/to/file" };
1768 sub check_cert_fingerprint
{
1769 my ($self, $cert) = @_;
1774 sub initialize_cert_cache
{
1775 my ($self, $node) = @_;
1780 sub remote_node_ip
{
1781 my ($self, $node) = @_;