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 = 128*1024;
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(
377 rbuf_max => $max_payload_size,
378 wbuf_max => $max_payload_size*5,
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 > $max_payload_size ? $max_payload_size : $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 while (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, $offset + 4 + $payload_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";
500 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.1';
502 $reqstate->{proxyhdl}->timeout(0);
503 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
504 $reqstate->{hdl}->on_read($hdlreader);
506 # todo: use stop_read/start_read if write buffer grows to much
508 my $res = "$proto 101 Switching Protocols
\015\012" .
509 "Upgrade
: websocket
\015\012" .
510 "Connection
: upgrade
\015\012" .
511 "Sec-WebSocket-Accept
: $wsaccept\015\012" .
512 "Sec-WebSocket-Protocol
: $wsproto\015\012" .
515 print $res if $self->{debug};
517 $reqstate->{hdl}->push_write($res);
520 $reqstate->{log}->{code} = 101;
521 $self->log_request($reqstate);
527 $self->log_aborted_request($reqstate, $err);
528 $self->client_do_disconnect($reqstate);
533 my ($self, $reqstate, $clientip, $host, $node, $method, $uri, $ticket, $token, $params) = @_;
538 if ($host eq 'localhost') {
539 $target = "http
://$host:85$uri";
540 # keep alive for localhost is not worth (connection setup is about 0.2ms)
542 } elsif (Net::IP::ip_is_ipv6($host)) {
543 $target = "https
://[$host]:8006$uri";
545 $target = "https
://$host:8006$uri";
549 PVEDisableProxy => 'true',
550 PVEClientIP => $clientip,
553 $headers->{'cookie'} = PVE::APIServer::Formatter::create_auth_cookie($ticket, $self->{cookie_name}) if $ticket;
554 $headers->{'CSRFPreventionToken'} = $token if $token;
555 $headers->{'Accept-Encoding'} = 'gzip' if $reqstate->{accept_gzip};
559 if ($method eq 'POST' || $method eq 'PUT') {
560 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
561 # use URI object to format application/x-www-form-urlencoded content.
562 my $url = URI->new('http:');
563 $url->query_form(%$params);
564 $content = $url->query;
565 if (defined($content)) {
566 $headers->{'Content-Length'} = length($content);
571 # TLS 1.x only, with certificate pinning
577 my (undef, undef, undef, $depth, undef, undef, $cert) = @_;
578 # we don't care about intermediate or root certificates
579 return 1 if $depth != 0;
580 # check server certificate against cache of pinned FPs
581 return $self->check_cert_fingerprint($cert);
585 # load and cache cert fingerprint if first time we proxy to this node
586 $self->initialize_cert_cache($node);
588 my $w; $w = http_request(
593 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
594 keepalive => $keep_alive,
596 tls_ctx => AnyEvent::TLS->new(%{$tls}),
598 my ($body, $hdr) = @_;
602 if (!$reqstate->{hdl}) {
603 warn "proxy detected vanished client connection
\n";
608 my $code = delete $hdr->{Status};
609 my $msg = delete $hdr->{Reason};
611 delete $hdr->{HTTPVersion};
612 my $header = HTTP::Headers->new(%$hdr);
613 if (my $location = $header->header('Location')) {
614 $location =~ s|^http://localhost:85||;
615 $header->header(Location => $location);
617 my $resp = HTTP::Response->new($code, $msg, $header, $body);
618 # Note: disable compression, because body is already compressed
619 $self->response($reqstate, $resp, undef, 1);
627 # return arrays as \0 separated strings (like CGI.pm)
628 # assume data is UTF8 encoded
629 sub decode_urlencoded {
634 return $res if !$data;
636 foreach my $kv (split(/[\&\;]/, $data)) {
637 my ($k, $v) = split(/=/, $kv);
639 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
641 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
643 $v = Encode::decode('utf8', $v);
645 if (defined(my $old = $res->{$k})) {
646 $res->{$k} = "$old\0$v";
655 my ($r, $method) = @_;
659 if ($method eq 'PUT' || $method eq 'POST') {
660 $params = decode_urlencoded($r->content);
663 my $query_params = decode_urlencoded($r->url->query());
665 foreach my $k (keys %{$query_params}) {
666 $params->{$k} = $query_params->{$k};
672 sub handle_api2_request {
673 my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
676 my $r = $reqstate->{request};
678 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
680 my $formatter = PVE::APIServer::Formatter::get_formatter($format, $method, $rel_uri);
682 if (!defined($formatter)) {
683 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no formatter
for uri
$rel_uri, $format");
687 #print Dumper($upload_state) if $upload_state;
692 $params = $upload_state->{params};
694 $params = extract_params($r, $method);
697 delete $params->{_dc}; # remove disable cache parameter
699 my $clientip = $reqstate->{peer_host};
701 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
704 Net::SSLeay::ERR_clear_error();
706 AnyEvent->now_update(); # in case somebody called sleep()
708 my $upgrade = $r->header('upgrade');
709 $upgrade = lc($upgrade) if $upgrade;
711 if (my $host = $res->{proxy}) {
713 if ($self->{trusted_env}) {
714 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
718 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
719 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
723 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
725 $self->proxy_request($reqstate, $clientip, $host, $res->{proxynode}, $method,
726 $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params}, $res->{proxynode});
729 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
730 die "unable to upgrade to protocol
'$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
731 my $wsver = $r->header('sec-websocket-version');
732 die "unsupported websocket-version
'$wsver'\n" if !$wsver || ($wsver ne '13');
733 my $wsproto_str = $r->header('sec-websocket-protocol');
734 die "missing websocket-protocol header
" if !$wsproto_str;
736 foreach my $p (PVE::Tools::split_list($wsproto_str)) {
737 $wsproto = $p if !$wsproto && $p eq 'base64';
738 $wsproto = $p if $p eq 'binary';
740 die "unsupported websocket-protocol protocol
'$wsproto_str'\n" if !$wsproto;
741 my $wskey = $r->header('sec-websocket-key');
742 die "missing websocket-key
\n" if !$wskey;
743 # Note: Digest::SHA::sha1_base64 has wrong padding
744 my $wsaccept = Digest::SHA::sha1_base64("${wskey
}258EAFA5-E914-47DA-95CA-C5AB0DC85B11
") . "=";
745 if ($res->{status} == HTTP_OK) {
746 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
752 if ($res->{status} == HTTP_UNAUTHORIZED) {
753 # always delay unauthorized calls by 3 seconds
754 $delay = 3 - tv_interval($reqstate->{starttime});
755 $delay = 0 if $delay < 0;
758 if (defined(my $filename = $res->{download})) {
759 my $fh = IO::File->new($filename) ||
760 die "unable to
open file
'$filename' - $!\n";
761 send_file_start($self, $reqstate, $filename);
765 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
766 $auth, $self->{formatter_config});
769 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
772 $resp = HTTP::Response->new($res->{status}, $res->{message});
773 $resp->header("Content-Type
" => $ct);
774 $resp->content($raw);
776 $self->response($reqstate, $resp, undef, $nocomp, $delay);
779 $self->error($reqstate, 501, $err);
783 sub handle_spice_proxy_request {
784 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
788 die "Port
$spiceport is not allowed
" if ($spiceport < 61000 || $spiceport > 61099);
790 my $clientip = $reqstate->{peer_host};
791 my $r = $reqstate->{request};
795 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
796 $remip = $self->remote_node_ip($node);
797 print "REMOTE CONNECT
$vmid, $remip, $connect_str\n" if $self->{debug};
799 print "$$: CONNECT
$vmid, $node, $spiceport\n" if $self->{debug};
802 if ($remip && $r->header('PVEDisableProxy')) {
803 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
807 $reqstate->{hdl}->timeout(0);
808 $reqstate->{hdl}->wbuf_max(64*10*1024);
810 my $remhost = $remip ? $remip : "localhost
";
811 my $remport = $remip ? 3128 : $spiceport;
813 tcp_connect $remhost, $remport, sub {
815 or die "connect to
'$remhost:$remport' failed
: $!";
817 print "$$: CONNECTed to
'$remhost:$remport'\n" if $self->{debug};
818 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
821 wbuf_max => 64*10*1024,
826 $self->log_aborted_request($reqstate);
827 $self->client_do_disconnect($reqstate);
829 if (my $err = $@) { syslog('err', $err); }
832 my ($hdl, $fatal, $message) = @_;
834 $self->log_aborted_request($reqstate, $message);
835 $self->client_do_disconnect($reqstate);
837 if (my $err = $@) { syslog('err', "$err"); }
841 my $proxyhdlreader = sub {
844 my $len = length($hdl->{rbuf});
845 my $data = substr($hdl->{rbuf}, 0, $len, '');
847 #print "READ1
$len\n";
848 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
851 my $hdlreader = sub {
854 my $len = length($hdl->{rbuf});
855 my $data = substr($hdl->{rbuf}, 0, $len, '');
857 #print "READ0
$len\n";
858 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
861 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
863 my $startproxy = sub {
864 $reqstate->{proxyhdl}->timeout(0);
865 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
866 $reqstate->{hdl}->on_read($hdlreader);
868 # todo: use stop_read/start_read if write buffer grows to much
870 # a response must be followed by an empty line
871 my $res = "$proto 200 OK
\015\012\015\012";
872 $reqstate->{hdl}->push_write($res);
875 $reqstate->{log}->{code} = 200;
876 $self->log_request($reqstate);
880 my $header = "CONNECT
${connect_str
} $proto\015\012" .
881 "Host
: ${connect_str
}\015\012" .
882 "Proxy-Connection
: keep-alive
\015\012" .
883 "User-Agent
: spiceproxy
\015\012" .
884 "PVEDisableProxy
: true
\015\012" .
885 "PVEClientIP
: $clientip\015\012" .
888 $reqstate->{proxyhdl}->push_write($header);
889 $reqstate->{proxyhdl}->push_read(line => sub {
890 my ($hdl, $line) = @_;
892 if ($line =~ m!^$proto 200 OK$!) {
893 # read the empty line after the 200 OK
894 $reqstate->{proxyhdl}->unshift_read(line => sub{
898 $reqstate->{hdl}->push_write($line);
899 $self->client_do_disconnect($reqstate);
910 $self->log_aborted_request($reqstate, $err);
911 $self->client_do_disconnect($reqstate);
916 my ($self, $reqstate, $auth, $method, $path) = @_;
918 my $base_uri = $self->{base_uri};
921 my $r = $reqstate->{request};
923 # disable timeout on handle (we already have all data we need)
924 # we re-enable timeout in response()
925 $reqstate->{hdl}->timeout(0);
927 if ($path =~ m/^\Q$base_uri\E/) {
928 $self->handle_api2_request($reqstate, $auth, $method, $path);
932 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
933 if (ref($handler) eq 'CODE') {
934 my $params = decode_urlencoded($r->url->query());
935 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
937 Net::SSLeay::ERR_clear_error();
938 $self->response($reqstate, $resp);
939 } elsif (ref($handler) eq 'HASH') {
940 if (my $filename = $handler->{file}) {
941 my $fh = IO::File->new($filename) ||
942 die "unable to
open file
'$filename' - $!\n";
943 send_file_start($self, $reqstate, $filename);
945 die "internal error
- no handler
";
948 die "internal error
- no handler
";
953 if ($self->{dirs} && ($method eq 'GET')) {
954 # we only allow simple names
955 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
956 my ($subdir, $file) = ($1, $2);
957 if (my $dir = $self->{dirs}->{$subdir}) {
958 my $filename = "$dir$file";
959 my $fh = IO::File->new($filename) ||
960 die "unable to
open file
'$filename' - $!\n";
961 send_file_start($self, $reqstate, $filename);
967 die "no such file
'$path'\n";
970 $self->error($reqstate, 501, $err);
974 sub file_upload_multipart {
975 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
978 my $boundary = $rstate->{boundary};
979 my $hdl = $reqstate->{hdl};
981 my $startlen = length($hdl->{rbuf});
983 if ($rstate->{phase} == 0) { # skip everything until start
984 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
985 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
987 my ($ct, $disp, $name, $filename);
988 foreach my $line (split(/\015?\012/, $header)) {
989 # assume we have single line headers
990 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
991 $ct = parse_content_type($1);
992 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
993 ($disp, $name, $filename) = parse_content_disposition($1);
997 if (!($disp && $disp eq 'form-data' && $name)) {
998 syslog('err', "wrong content disposition
in multipart
- abort upload
");
999 $rstate->{phase} = -1;
1002 $rstate->{fieldname} = $name;
1005 if ($name eq 'filename') {
1006 # found file upload data
1007 $rstate->{phase} = 1;
1008 $rstate->{filename} = $filename;
1010 syslog('err', "wrong field name
for file upload
- abort upload
");
1011 $rstate->{phase} = -1;
1014 # found form data for field $name
1015 $rstate->{phase} = 2;
1019 my $len = length($hdl->{rbuf});
1020 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
1021 if $len > $rstate->{maxheader}; # skip garbage
1023 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
1024 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1025 my ($rest, $eof) = ($1, $3);
1026 my $len = length($rest);
1027 die "write to temporary file failed
- $!"
1028 if syswrite($rstate->{outfh}, $rest) != $len;
1029 $rstate->{ctx}->add($rest);
1030 $rstate->{params}->{filename} = $rstate->{filename};
1031 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
1032 $rstate->{bytes} += $len;
1033 $rstate->{phase} = $eof ? 100 : 0;
1035 my $len = length($hdl->{rbuf});
1036 my $wlen = $len - $rstate->{boundlen};
1038 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
1039 die "write to temporary file failed
- $!"
1040 if syswrite($rstate->{outfh}, $data) != $wlen;
1041 $rstate->{bytes} += $wlen;
1042 $rstate->{ctx}->add($data);
1045 } elsif ($rstate->{phase} == 2) { # inside normal field
1047 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1048 my ($rest, $eof) = ($1, $3);
1049 my $len = length($rest);
1050 $rstate->{post_size} += $len;
1051 if ($rstate->{post_size} < $limit_max_post) {
1052 $rstate->{params}->{$rstate->{fieldname}} = $rest;
1053 $rstate->{phase} = $eof ? 100 : 0;
1055 syslog('err', "form data to large
- abort upload
");
1056 $rstate->{phase} = -1; # skip
1060 my $len = length($hdl->{rbuf});
1061 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
1064 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
1066 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
1067 $rstate->{done} = 1; # make sure we dont get called twice
1068 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
1069 die "upload failed
\n";
1071 my $elapsed = tv_interval($rstate->{starttime});
1073 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
1074 syslog('info', "multipart upload complete
" .
1075 "(size
: %d time: %ds rate
: %.2fMiB
/s md5sum
: $rstate->{md5sum
})",
1076 $rstate->{bytes}, $elapsed, $rate);
1077 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1082 syslog('err', $err);
1083 $self->error($reqstate, 501, $err);
1087 sub parse_content_type {
1090 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
1092 foreach my $v (@params) {
1093 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1094 return wantarray ? ($ct, $1) : $ct;
1098 return wantarray ? ($ct) : $ct;
1101 sub parse_content_disposition {
1104 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
1108 foreach my $v (@params) {
1109 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
1111 $name =~ s/^"(.*)"$/$1/;
1112 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
1114 $filename =~ s/^"(.*)"$/$1/;
1118 return wantarray ? ($disp, $name, $filename) : $disp;
1121 my $tmpfile_seq_no = 0;
1123 sub get_upload_filename {
1124 # choose unpredictable tmpfile name
1127 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1130 sub unshift_read_header {
1131 my ($self, $reqstate, $state) = @_;
1133 $state = { size => 0, count => 0 } if !$state;
1135 $reqstate->{hdl}->unshift_read(line => sub {
1136 my ($hdl, $line) = @_;
1139 # print "$$: got header
: $line\n" if $self->{debug};
1141 die "to many http header lines
\n" if ++$state->{count} >= $limit_max_headers;
1142 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1144 my $r = $reqstate->{request};
1147 my $path = uri_unescape($r->uri->path());
1148 my $method = $r->method();
1150 $r->push_header($state->{key}, $state->{val})
1153 if (!$known_methods->{$method}) {
1154 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
1155 $self->response($reqstate, $resp);
1159 my $conn = $r->header('Connection');
1160 my $accept_enc = $r->header('Accept-Encoding');
1161 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1164 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1166 if ($reqstate->{proto}->{ver} < 1001) {
1167 $reqstate->{keep_alive} = 0;
1171 my $te = $r->header('Transfer-Encoding');
1172 if ($te && lc($te) eq 'chunked') {
1173 # Handle chunked transfer encoding
1174 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
1177 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
1181 my $pveclientip = $r->header('PVEClientIP');
1182 my $base_uri = $self->{base_uri};
1184 # fixme: how can we make PVEClientIP header trusted?
1185 if ($self->{trusted_env} && $pveclientip) {
1186 $reqstate->{peer_host} = $pveclientip;
1188 $r->header('PVEClientIP', $reqstate->{peer_host});
1191 my $len = $r->header('Content-Length');
1193 # header processing complete - authenticate now
1196 if ($self->{spiceproxy}) {
1197 my $connect_str = $r->header('Host');
1198 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
1199 if (!(defined($vmid) && $node && $port)) {
1200 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket
");
1203 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1205 } elsif ($path =~ m/^\Q$base_uri\E/) {
1206 my $token = $r->header('CSRFPreventionToken');
1207 my $cookie = $r->header('Cookie');
1208 my $ticket = PVE::APIServer::Formatter::extract_auth_cookie($cookie, $self->{cookie_name});
1210 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1212 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
1217 $auth = $self->auth_handler($method, $rel_uri, $ticket, $token,
1218 $reqstate->{peer_host});
1222 Net::SSLeay::ERR_clear_error();
1223 # always delay unauthorized calls by 3 seconds
1226 if (ref($err) eq "PVE
::Exception
") {
1228 $err->{code} ||= HTTP_INTERNAL_SERVER_ERROR,
1229 my $resp = HTTP::Response->new($err->{code}, $err->{msg});
1230 $self->response($reqstate, $resp, undef, 0, $delay);
1232 } elsif (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
1233 my ($raw, $ct, $nocomp) =
1234 $formatter->($path, $auth, $self->{formatter_config});
1236 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1239 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required
");
1240 $resp->header("Content-Type
" => $ct);
1241 $resp->content($raw);
1243 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1245 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1246 $self->response($reqstate, $resp, undef, 0, $delay);
1252 $reqstate->{log}->{userid} = $auth->{userid};
1256 if (!($method eq 'PUT' || $method eq 'POST')) {
1257 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
1261 my $ctype = $r->header('Content-Type');
1262 my ($ct, $boundary) = parse_content_type($ctype) if $ctype;
1264 if ($auth->{isUpload} && !$self->{trusted_env}) {
1265 die "upload
'Content-Type '$ctype' not implemented\n"
1266 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
1268 die "upload without content length header not supported" if !$len;
1270 die "upload without content length header not supported" if !$len;
1272 print "start upload $path $ct $boundary\n" if $self->{debug};
1274 my $tmpfilename = get_upload_filename();
1275 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1276 die "unable to create temporary upload file '$tmpfilename'";
1278 $reqstate->{keep_alive} = 0;
1280 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1284 boundary => $boundary,
1285 ctx => Digest::MD5->new,
1286 boundlen => $boundlen,
1287 maxheader => 2048 + $boundlen, # should be large enough
1288 params => decode_urlencoded($r->url->query()),
1292 starttime => [gettimeofday],
1295 $reqstate->{tmpfilename} = $tmpfilename;
1296 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $method, $path, $state); });
1300 if ($len > $limit_max_post) {
1301 $self->error($reqstate, 501, "for data too large");
1305 if (!$ct || $ct eq 'application
/x-www-form-urlencoded
') {
1306 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1307 my ($hdl, $data) = @_;
1309 $self->handle_request($reqstate, $auth, $method, $path);
1312 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
1315 $self->handle_request($reqstate, $auth, $method, $path);
1317 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1318 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1319 ($state->{key}, $state->{val}) = ($1, $2);
1320 $self->unshift_read_header($reqstate, $state);
1321 } elsif ($line =~ /^\s+(.*)/) {
1322 $state->{val} .= " $1";
1323 $self->unshift_read_header($reqstate, $state);
1325 $self->error($reqstate, 506, "unable to parse request header
");
1332 sub push_request_header {
1333 my ($self, $reqstate) = @_;
1336 $reqstate->{hdl}->push_read(line => sub {
1337 my ($hdl, $line) = @_;
1340 # print "got request header
: $line\n" if $self->{debug};
1342 $reqstate->{keep_alive}--;
1344 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1345 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1348 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
1352 $self->{request_count}++; # only count valid request headers
1353 if ($self->{request_count} >= $self->{max_requests}) {
1354 $self->{end_loop} = 1;
1356 $reqstate->{log} = { requestline => $line };
1357 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
1358 $reqstate->{proto}->{maj} = $maj;
1359 $reqstate->{proto}->{min} = $min;
1360 $reqstate->{proto}->{ver} = $maj*1000+$min;
1361 $reqstate->{request} = HTTP::Request->new($method, $url);
1362 $reqstate->{starttime} = [gettimeofday],
1364 $self->unshift_read_header($reqstate);
1365 } elsif ($line eq '') {
1366 # ignore empty lines before requests (browser bugs?)
1367 $self->push_request_header($reqstate);
1369 $self->error($reqstate, 400, 'bad request');
1383 return if $self->{end_loop};
1385 # we need to m make sure that only one process calls accept
1386 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1387 next if $! == EINTR;
1388 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
1394 while (!$self->{end_loop} &&
1395 !defined($clientfh = $self->{socket}->accept()) &&
1398 if ($self->{end_loop}) {
1401 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1402 if (!defined($clientfh)) {
1403 $errmsg = "failed to
accept connection
: $!\n";
1409 flock($self->{lockfh}, Fcntl::LOCK_UN());
1411 if (!defined($clientfh)) {
1413 die $errmsg if $errmsg;
1416 fh_nonblocking $clientfh, 1;
1418 $self->{conn_count}++;
1426 $self->{end_loop} = 1;
1428 undef $self->{socket_watch};
1430 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1432 if ($self->{conn_count} <= 0) {
1433 $self->{end_cond}->send(1);
1437 # fork and exit, so that parent starts a new worker
1442 # else we need to wait until all open connections gets closed
1443 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1445 # todo: test for active connections instead (we can abort idle connections)
1446 if ($self->{conn_count} <= 0) {
1448 $self->{end_cond}->send(1);
1456 sub check_host_access {
1457 my ($self, $clientip) = @_;
1459 my $cip = Net::IP->new($clientip);
1461 my $match_allow = 0;
1464 if ($self->{allow_from}) {
1465 foreach my $t (@{$self->{allow_from}}) {
1466 if ($t->overlaps($cip)) {
1473 if ($self->{deny_from}) {
1474 foreach my $t (@{$self->{deny_from}}) {
1475 if ($t->overlaps($cip)) {
1482 if ($match_allow == $match_deny) {
1483 # match both allow and deny, or no match
1484 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1487 return $match_allow;
1490 sub accept_connections {
1495 while (my $clientfh = $self->accept()) {
1497 my $reqstate = { keep_alive => $self->{keep_alive} };
1499 # stop keep-alive when there are many open connections
1500 if ($self->{conn_count} >= $self->{max_conn_soft_limit}) {
1501 $reqstate->{keep_alive} = 0;
1504 if (my $sin = getpeername($clientfh)) {
1505 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1506 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1509 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1510 print "$$: ABORT request from
$reqstate->{peer_host
} - access denied
\n" if $self->{debug};
1511 $reqstate->{log}->{code} = 403;
1512 $self->log_request($reqstate);
1516 $reqstate->{hdl} = AnyEvent::Handle->new(
1518 rbuf_max => 64*1024,
1519 timeout => $self->{timeout},
1520 linger => 0, # avoid problems with ssh - really needed ?
1524 $self->log_aborted_request($reqstate);
1525 $self->client_do_disconnect($reqstate);
1527 if (my $err = $@) { syslog('err', $err); }
1530 my ($hdl, $fatal, $message) = @_;
1532 $self->log_aborted_request($reqstate, $message);
1533 $self->client_do_disconnect($reqstate);
1535 if (my $err = $@) { syslog('err', "$err"); }
1537 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1539 print "$$: ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}\n" if $self->{debug};
1541 $self->push_request_header($reqstate);
1546 syslog('err', $err);
1547 $self->{end_loop} = 1;
1550 $self->wait_end_loop() if $self->{end_loop};
1553 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1554 # because we write from multiple processes, and that would arbitrarily mix output
1556 sub open_access_log {
1557 my ($self, $filename) = @_;
1559 my $old_mask = umask(0137);;
1560 my $logfh = IO::File->new($filename, ">>") ||
1561 die "unable to
open log file
'$filename' - $!\n";
1564 $logfh->autoflush(1);
1566 $self->{logfh} = $logfh;
1570 my ($self, $data) = @_;
1572 return if !defined($self->{logfh}) || !$data;
1574 my $res = $self->{logfh}->print($data);
1577 delete $self->{logfh};
1578 syslog('err', "error writing access
log");
1579 $self->{end_loop} = 1; # terminate asap
1583 sub atfork_handler {
1587 # something else do to ?
1588 close($self->{socket});
1596 $self->{end_cond}->recv;
1600 my ($this, %args) = @_;
1602 my $class = ref($this) || $this;
1604 foreach my $req (qw(socket lockfh lockfile)) {
1605 die "misssing required argument '$req'" if !defined($args{$req});
1608 my $self = bless { %args }, $class;
1610 $self->{cookie_name
} //= 'PVEAuthCookie';
1611 $self->{base_uri
} //= "/api2";
1612 $self->{dirs
} //= {};
1613 $self->{title
} //= 'API Inspector';
1615 # formatter_config: we pass some configuration values to the Formatter
1616 $self->{formatter_config
} = {};
1617 foreach my $p (qw(cookie_name base_uri title)) {
1618 $self->{formatter_config
}->{$p} = $self->{$p};
1620 $self->{formatter_config
}->{csrfgen_func
} =
1621 $self->can('generate_csrf_prevention_token');
1623 # add default dirs which includes jquery and bootstrap
1624 my $base = '/usr/share/libpve-http-server-perl';
1625 add_dirs
($self->{dirs
}, '/css/' => "$base/css/");
1626 add_dirs
($self->{dirs
}, '/js/' => "$base/js/");
1627 add_dirs
($self->{dirs
}, '/fonts/' => "$base/fonts/");
1630 PVE
::INotify
::inotify_init
();
1632 fh_nonblocking
($self->{socket}, 1);
1634 $self->{end_loop
} = 0;
1635 $self->{conn_count
} = 0;
1636 $self->{request_count
} = 0;
1637 $self->{timeout
} = 5 if !$self->{timeout
};
1638 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1639 $self->{max_conn
} = 800 if !$self->{max_conn
};
1640 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1642 $self->{policy
} = 'allow' if !$self->{policy
};
1644 $self->{end_cond
} = AnyEvent-
>condvar;
1647 my $tls_ctx_flags = &Net
::SSLeay
::OP_NO_COMPRESSION
| &Net
::SSLeay
::OP_SINGLE_ECDH_USE
| &Net
::SSLeay
::OP_SINGLE_DH_USE
;
1648 if ( delete $self->{ssl
}->{honor_cipher_order
} ) {
1649 $tls_ctx_flags |= &Net
::SSLeay
::OP_CIPHER_SERVER_PREFERENCE
;
1652 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
1653 Net
::SSLeay
::CTX_set_options
($self->{tls_ctx
}->{ctx
}, $tls_ctx_flags);
1656 if ($self->{spiceproxy
}) {
1657 $known_methods = { CONNECT
=> 1 };
1660 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
1662 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
1664 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
1666 if ($self->{conn_count
} >= $self->{max_conn
}) {
1667 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
1668 if ($self->{conn_count
} < $self->{max_conn
}) {
1670 $self->accept_connections();
1674 $self->accept_connections();
1680 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
1681 undef $self->{term_watch
};
1682 $self->wait_end_loop();
1685 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
1686 undef $self->{quit_watch
};
1687 $self->wait_end_loop();
1690 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
1691 PVE
::INotify
::poll
(); # read inotify events
1697 # static helper to add directory including all subdirs
1698 # This can be used to setup $self->{dirs}
1700 my ($result_hash, $alias, $subdir) = @_;
1702 $result_hash->{$alias} = $subdir;
1705 my $dir = $File::Find
::dir
;
1706 if ($dir =~m!^$subdir(.*)$!) {
1707 my $name = "$alias$1/";
1708 $result_hash->{$name} = "$dir/";
1712 find
({wanted
=> $wanted, follow
=> 0, no_chdir
=> 1}, $subdir);
1715 # abstract functions - subclass should overwrite/implement them
1717 sub verify_spice_connect_url
{
1718 my ($self, $connect_str) = @_;
1722 #return ($vmid, $node, $port);
1725 # formatters can call this when the generate a new page
1726 sub generate_csrf_prevention_token
{
1727 my ($username) = @_;
1729 return undef; # do nothing by default
1733 my ($self, $method, $rel_uri, $ticket, $token, $peer_host) = @_;
1738 # ticket => $ticket,
1740 # userid => $username,
1742 # isUpload => $isUpload,
1747 my ($self, $clientip, $method, $rel_uri, $auth, $params, $format) = @_;
1749 # please do not raise exceptions here (always return a result).
1752 status
=> HTTP_NOT_IMPLEMENTED
,
1753 message
=> "Method '$method $rel_uri' not implemented",
1756 # this should return the following properties, which
1757 # are then passed to the Formatter
1759 # status: HTTP status code
1760 # message: Error message
1761 # errors: more detailed error hash (per parameter)
1762 # info: reference to JSON schema definition - useful to format output
1765 # total: additional info passed to output
1766 # changes: additional info passed to output
1768 # if you want to proxy the request to another node return this
1769 # { proxy => $remip, proxynode => $node, proxy_params => $params };
1771 # to pass the request to the local priviledged daemon use:
1772 # { proxy => 'localhost' , proxy_params => $params };
1774 # to download aspecific file use:
1775 # { download => "/path/to/file" };
1778 sub check_cert_fingerprint
{
1779 my ($self, $cert) = @_;
1784 sub initialize_cert_cache
{
1785 my ($self, $node) = @_;
1790 sub remote_node_ip
{
1791 my ($self, $node) = @_;