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 //= !$self->{compression};
188 $nocomp = 1 if !$reqstate->{accept_gzip};
190 my $code = $resp->code;
191 my $msg = $resp->message || HTTP::Status::status_message($code);
192 ($msg) = $msg =~m/^(.*)$/m;
193 my $content = $resp->content;
195 if ($code =~ /^(1\d\d|[23]04)$/) {
196 # make sure content we have no content
200 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
202 $reqstate->{log}->{code} = $code;
204 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
205 my $res = "$proto $code $msg\015\012";
208 my $date = HTTP::Date::time2str($ctime);
209 $resp->header('Date' => $date);
211 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
213 $resp->header('Expires' => $date);
214 $resp->header('Cache-Control' => "max-age
=0");
215 $resp->header("Pragma
", "no-cache
");
218 $resp->header('Server' => "pve-api-daemon
/3.0");
223 $content_length = length($content);
225 if (!$nocomp && ($content_length > 1024)) {
226 my $comp = Compress::Zlib::memGzip($content);
227 $resp->header('Content-Encoding', 'gzip');
229 $content_length = length($content);
231 $resp->header("Content-Length
" => $content_length);
232 $reqstate->{log}->{content_length} = $content_length;
235 $resp->remove_header("Content-Length
");
238 if ($reqstate->{keep_alive} > 0) {
239 $resp->push_header('Connection' => 'Keep-Alive');
241 $resp->header('Connection' => 'close');
244 $res .= $resp->headers_as_string("\015\012");
245 #print "SEND
(without content
) $res\n" if $self->{debug};
248 $res .= $content if $content;
250 $self->log_request($reqstate, $reqstate->{request});
252 if ($delay && $delay > 0) {
253 my $w; $w = AnyEvent->timer(after => $delay, cb => sub {
254 undef $w; # delete reference
255 $reqstate->{hdl}->push_write($res);
256 $self->finish_response($reqstate);
259 $reqstate->{hdl}->push_write($res);
260 $self->finish_response($reqstate);
265 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
268 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
269 $self->response($reqstate, $resp);
274 my $file_extension_info = {
275 css => { ct => 'text/css' },
276 html => { ct => 'text/html' },
277 js => { ct => 'application/javascript' },
278 json => { ct => 'application/json' },
279 map => { ct => 'application/json' },
280 png => { ct => 'image/png' , nocomp => 1 },
281 ico => { ct => 'image/x-icon', nocomp => 1},
282 gif => { ct => 'image/gif', nocomp => 1},
283 svg => { ct => 'image/svg+xml' },
284 jar => { ct => 'application/java-archive', nocomp => 1},
285 woff => { ct => 'application/font-woff', nocomp => 1},
286 woff2 => { ct => 'application/font-woff2', nocomp => 1},
287 ttf => { ct => 'application/font-snft', nocomp => 1},
288 pdf => { ct => 'application/pdf', nocomp => 1},
289 epub => { ct => 'application/epub+zip', nocomp => 1},
290 mp3 => { ct => 'audio/mpeg', nocomp => 1},
291 oga => { ct => 'audio/ogg', nocomp => 1},
292 tgz => { ct => 'application/x-compressed-tar', nocomp => 1},
295 sub send_file_start {
296 my ($self, $reqstate, $filename) = @_;
299 # print "SEND FILE
$filename\n";
300 # Note: aio_load() this is not really async unless we use IO::AIO!
303 my $r = $reqstate->{request};
305 my $fh = IO::File->new($filename, '<') ||
307 my $stat = File::stat::stat($fh) ||
310 my $mtime = $stat->mtime;
312 if (my $ifmod = $r->header('if-modified-since')) {
313 my $iftime = HTTP::Date::str2time($ifmod);
314 if ($mtime <= $iftime) {
315 my $resp = HTTP::Response->new(304, "NOT MODIFIED
");
316 $self->response($reqstate, $resp, $mtime);
322 my $len = sysread($fh, $data, $stat->size);
323 die "got short file
\n" if !defined($len) || $len != $stat->size;
325 my ($ext) = $filename =~ m/\.([^.]*)$/;
326 my $ext_info = $file_extension_info->{$ext};
328 die "unable to detect content type
" if !$ext_info;
330 my $header = HTTP::Headers->new(Content_Type => $ext_info->{ct});
331 my $resp = HTTP::Response->new(200, "OK
", $header, $data);
332 $self->response($reqstate, $resp, $mtime, $ext_info->{nocomp});
335 $self->error($reqstate, 501, $err);
342 sub websocket_proxy {
343 my ($self, $reqstate, $wsaccept, $wsproto, $param) = @_;
349 my $max_payload_size = 128*1024;
352 if ($wsproto eq 'binary') {
354 } elsif ($wsproto eq 'base64') {
357 die "websocket_proxy
: unsupported protocol
'$wsproto'\n";
360 if ($param->{port}) {
361 $remhost = 'localhost';
362 $remport = $param->{port};
363 } elsif ($param->{socket}) {
365 $remport = $param->{socket};
367 die "websocket_proxy
: missing port
or socket\n";
370 tcp_connect $remhost, $remport, sub {
372 or die "connect to
'$remhost:$remport' failed
: $!";
374 print "$$: CONNECTed to
'$remhost:$remport'\n" if $self->{debug};
376 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
378 rbuf_max => $max_payload_size,
379 wbuf_max => $max_payload_size*5,
384 $self->log_aborted_request($reqstate);
385 $self->client_do_disconnect($reqstate);
387 if (my $err = $@) { syslog('err', $err); }
390 my ($hdl, $fatal, $message) = @_;
392 $self->log_aborted_request($reqstate, $message);
393 $self->client_do_disconnect($reqstate);
395 if (my $err = $@) { syslog('err', "$err"); }
398 my $proxyhdlreader = sub {
401 my $len = length($hdl->{rbuf});
402 my $data = substr($hdl->{rbuf}, 0, $len > $max_payload_size ? $max_payload_size : $len, '');
408 $string = "\x82"; # binary frame
411 $string = "\x81"; # text frame
412 $payload = encode_base64($data, '');
415 my $payload_len = length($payload);
416 if ($payload_len <= 125) {
417 $string .= pack 'C', $payload_len;
418 } elsif ($payload_len <= 0xffff) {
419 $string .= pack 'C', 126;
420 $string .= pack 'n', $payload_len;
422 $string .= pack 'C', 127;
423 $string .= pack 'Q>', $payload_len;
427 $reqstate->{hdl}->push_write($string) if $reqstate->{hdl};
430 my $hdlreader = sub {
433 while (my $len = length($hdl->{rbuf})) {
436 my $hdr = unpack('C', substr($hdl->{rbuf}, 0, 1));
437 my $opcode = $hdr & 0b00001111;
438 my $fin = $hdr & 0b10000000;
440 die "received fragmented websocket frame
\n" if !$fin;
442 my $rsv = $hdr & 0b01110000;
443 die "received websocket frame with RSV flags
\n" if $rsv;
445 my $payload_len = unpack 'C', substr($hdl->{rbuf}, 1, 1);
447 my $masked = $payload_len & 0b10000000;
448 die "received unmasked websocket frame from client
\n" if !$masked;
451 $payload_len = $payload_len & 0b01111111;
452 if ($payload_len == 126) {
454 $payload_len = unpack('n', substr($hdl->{rbuf}, $offset, 2));
456 } elsif ($payload_len == 127) {
458 $payload_len = unpack('Q>', substr($hdl->{rbuf}, $offset, 8));
462 die "received too large websocket frame
(len
= $payload_len)\n"
463 if ($payload_len > $max_payload_size) || ($payload_len < 0);
465 return if $len < ($offset + 4 + $payload_len);
467 my $data = substr($hdl->{rbuf}, 0, $offset + 4 + $payload_len, ''); # now consume data
469 my @mask = (unpack('C', substr($data, $offset+0, 1)),
470 unpack('C', substr($data, $offset+1, 1)),
471 unpack('C', substr($data, $offset+2, 1)),
472 unpack('C', substr($data, $offset+3, 1)));
476 my $payload = substr($data, $offset, $payload_len);
478 for (my $i = 0; $i < $payload_len; $i++) {
479 my $d = unpack('C', substr($payload, $i, 1));
480 my $n = $d ^ $mask[$i % 4];
481 substr($payload, $i, 1, pack('C', $n));
484 $payload = decode_base64($payload) if !$binary;
486 if ($opcode == 1 || $opcode == 2) {
487 $reqstate->{proxyhdl}->push_write($payload) if $reqstate->{proxyhdl};
488 } elsif ($opcode == 8) {
489 my $statuscode = unpack ("n
", $payload);
490 print "websocket received
close. status code
: '$statuscode'\n" if $self->{debug};
491 if ($reqstate->{proxyhdl}) {
492 $reqstate->{proxyhdl}->push_shutdown();
494 $hdl->push_shutdown();
496 die "received unhandled websocket opcode
$opcode\n";
501 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.1';
503 $reqstate->{proxyhdl}->timeout(0);
504 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
505 $reqstate->{hdl}->on_read($hdlreader);
507 # todo: use stop_read/start_read if write buffer grows to much
509 my $res = "$proto 101 Switching Protocols
\015\012" .
510 "Upgrade
: websocket
\015\012" .
511 "Connection
: upgrade
\015\012" .
512 "Sec-WebSocket-Accept
: $wsaccept\015\012" .
513 "Sec-WebSocket-Protocol
: $wsproto\015\012" .
516 print $res if $self->{debug};
518 $reqstate->{hdl}->push_write($res);
521 $reqstate->{log}->{code} = 101;
522 $self->log_request($reqstate);
528 $self->log_aborted_request($reqstate, $err);
529 $self->client_do_disconnect($reqstate);
534 my ($self, $reqstate, $clientip, $host, $node, $method, $uri, $ticket, $token, $params) = @_;
539 if ($host eq 'localhost') {
540 $target = "http
://$host:85$uri";
541 # keep alive for localhost is not worth (connection setup is about 0.2ms)
543 } elsif (Net::IP::ip_is_ipv6($host)) {
544 $target = "https
://[$host]:8006$uri";
546 $target = "https
://$host:8006$uri";
550 PVEDisableProxy => 'true',
551 PVEClientIP => $clientip,
554 $headers->{'cookie'} = PVE::APIServer::Formatter::create_auth_cookie($ticket, $self->{cookie_name}) if $ticket;
555 $headers->{'CSRFPreventionToken'} = $token if $token;
556 $headers->{'Accept-Encoding'} = 'gzip' if ($reqstate->{accept_gzip} && $self->{compression});
560 if ($method eq 'POST' || $method eq 'PUT') {
561 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
562 # use URI object to format application/x-www-form-urlencoded content.
563 my $url = URI->new('http:');
564 $url->query_form(%$params);
565 $content = $url->query;
566 if (defined($content)) {
567 $headers->{'Content-Length'} = length($content);
572 # TLS 1.x only, with certificate pinning
578 my (undef, undef, undef, $depth, undef, undef, $cert) = @_;
579 # we don't care about intermediate or root certificates
580 return 1 if $depth != 0;
581 # check server certificate against cache of pinned FPs
582 return $self->check_cert_fingerprint($cert);
586 # load and cache cert fingerprint if first time we proxy to this node
587 $self->initialize_cert_cache($node);
589 my $w; $w = http_request(
594 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
595 keepalive => $keep_alive,
597 tls_ctx => AnyEvent::TLS->new(%{$tls}),
599 my ($body, $hdr) = @_;
603 if (!$reqstate->{hdl}) {
604 warn "proxy detected vanished client connection
\n";
609 my $code = delete $hdr->{Status};
610 my $msg = delete $hdr->{Reason};
612 delete $hdr->{HTTPVersion};
613 my $header = HTTP::Headers->new(%$hdr);
614 if (my $location = $header->header('Location')) {
615 $location =~ s|^http://localhost:85||;
616 $header->header(Location => $location);
618 my $resp = HTTP::Response->new($code, $msg, $header, $body);
619 # Note: disable compression, because body is already compressed
620 $self->response($reqstate, $resp, undef, 1);
628 # return arrays as \0 separated strings (like CGI.pm)
629 # assume data is UTF8 encoded
630 sub decode_urlencoded {
635 return $res if !$data;
637 foreach my $kv (split(/[\&\;]/, $data)) {
638 my ($k, $v) = split(/=/, $kv);
640 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
642 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
644 $v = Encode::decode('utf8', $v);
646 if (defined(my $old = $res->{$k})) {
647 $res->{$k} = "$old\0$v";
656 my ($r, $method) = @_;
660 if ($method eq 'PUT' || $method eq 'POST') {
661 $params = decode_urlencoded($r->content);
664 my $query_params = decode_urlencoded($r->url->query());
666 foreach my $k (keys %{$query_params}) {
667 $params->{$k} = $query_params->{$k};
673 sub handle_api2_request {
674 my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
677 my $r = $reqstate->{request};
679 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
681 my $formatter = PVE::APIServer::Formatter::get_formatter($format, $method, $rel_uri);
683 if (!defined($formatter)) {
684 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no formatter
for uri
$rel_uri, $format");
688 #print Dumper($upload_state) if $upload_state;
693 $params = $upload_state->{params};
695 $params = extract_params($r, $method);
698 delete $params->{_dc}; # remove disable cache parameter
700 my $clientip = $reqstate->{peer_host};
702 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
705 Net::SSLeay::ERR_clear_error();
707 AnyEvent->now_update(); # in case somebody called sleep()
709 my $upgrade = $r->header('upgrade');
710 $upgrade = lc($upgrade) if $upgrade;
712 if (my $host = $res->{proxy}) {
714 if ($self->{trusted_env}) {
715 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
719 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
720 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
724 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
726 $self->proxy_request($reqstate, $clientip, $host, $res->{proxynode}, $method,
727 $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params}, $res->{proxynode});
730 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
731 die "unable to upgrade to protocol
'$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
732 my $wsver = $r->header('sec-websocket-version');
733 die "unsupported websocket-version
'$wsver'\n" if !$wsver || ($wsver ne '13');
734 my $wsproto_str = $r->header('sec-websocket-protocol');
735 die "missing websocket-protocol header
" if !$wsproto_str;
737 foreach my $p (PVE::Tools::split_list($wsproto_str)) {
738 $wsproto = $p if !$wsproto && $p eq 'base64';
739 $wsproto = $p if $p eq 'binary';
741 die "unsupported websocket-protocol protocol
'$wsproto_str'\n" if !$wsproto;
742 my $wskey = $r->header('sec-websocket-key');
743 die "missing websocket-key
\n" if !$wskey;
744 # Note: Digest::SHA::sha1_base64 has wrong padding
745 my $wsaccept = Digest::SHA::sha1_base64("${wskey
}258EAFA5-E914-47DA-95CA-C5AB0DC85B11
") . "=";
746 if ($res->{status} == HTTP_OK) {
747 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
753 if ($res->{status} == HTTP_UNAUTHORIZED) {
754 # always delay unauthorized calls by 3 seconds
755 $delay = 3 - tv_interval($reqstate->{starttime});
756 $delay = 0 if $delay < 0;
759 if (defined(my $filename = $res->{download})) {
760 my $fh = IO::File->new($filename) ||
761 die "unable to
open file
'$filename' - $!\n";
762 send_file_start($self, $reqstate, $filename);
766 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
767 $auth, $self->{formatter_config});
770 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
773 $resp = HTTP::Response->new($res->{status}, $res->{message});
774 $resp->header("Content-Type
" => $ct);
775 $resp->content($raw);
777 $self->response($reqstate, $resp, undef, $nocomp, $delay);
780 $self->error($reqstate, 501, $err);
784 sub handle_spice_proxy_request {
785 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
789 die "Port
$spiceport is not allowed
" if ($spiceport < 61000 || $spiceport > 61099);
791 my $clientip = $reqstate->{peer_host};
792 my $r = $reqstate->{request};
796 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
797 $remip = $self->remote_node_ip($node);
798 print "REMOTE CONNECT
$vmid, $remip, $connect_str\n" if $self->{debug};
800 print "$$: CONNECT
$vmid, $node, $spiceport\n" if $self->{debug};
803 if ($remip && $r->header('PVEDisableProxy')) {
804 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
808 $reqstate->{hdl}->timeout(0);
809 $reqstate->{hdl}->wbuf_max(64*10*1024);
811 my $remhost = $remip ? $remip : "localhost
";
812 my $remport = $remip ? 3128 : $spiceport;
814 tcp_connect $remhost, $remport, sub {
816 or die "connect to
'$remhost:$remport' failed
: $!";
818 print "$$: CONNECTed to
'$remhost:$remport'\n" if $self->{debug};
819 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
822 wbuf_max => 64*10*1024,
827 $self->log_aborted_request($reqstate);
828 $self->client_do_disconnect($reqstate);
830 if (my $err = $@) { syslog('err', $err); }
833 my ($hdl, $fatal, $message) = @_;
835 $self->log_aborted_request($reqstate, $message);
836 $self->client_do_disconnect($reqstate);
838 if (my $err = $@) { syslog('err', "$err"); }
842 my $proxyhdlreader = sub {
845 my $len = length($hdl->{rbuf});
846 my $data = substr($hdl->{rbuf}, 0, $len, '');
848 #print "READ1
$len\n";
849 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
852 my $hdlreader = sub {
855 my $len = length($hdl->{rbuf});
856 my $data = substr($hdl->{rbuf}, 0, $len, '');
858 #print "READ0
$len\n";
859 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
862 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
864 my $startproxy = sub {
865 $reqstate->{proxyhdl}->timeout(0);
866 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
867 $reqstate->{hdl}->on_read($hdlreader);
869 # todo: use stop_read/start_read if write buffer grows to much
871 # a response must be followed by an empty line
872 my $res = "$proto 200 OK
\015\012\015\012";
873 $reqstate->{hdl}->push_write($res);
876 $reqstate->{log}->{code} = 200;
877 $self->log_request($reqstate);
881 my $header = "CONNECT
${connect_str
} $proto\015\012" .
882 "Host
: ${connect_str
}\015\012" .
883 "Proxy-Connection
: keep-alive
\015\012" .
884 "User-Agent
: spiceproxy
\015\012" .
885 "PVEDisableProxy
: true
\015\012" .
886 "PVEClientIP
: $clientip\015\012" .
889 $reqstate->{proxyhdl}->push_write($header);
890 $reqstate->{proxyhdl}->push_read(line => sub {
891 my ($hdl, $line) = @_;
893 if ($line =~ m!^$proto 200 OK$!) {
894 # read the empty line after the 200 OK
895 $reqstate->{proxyhdl}->unshift_read(line => sub{
899 $reqstate->{hdl}->push_write($line);
900 $self->client_do_disconnect($reqstate);
911 $self->log_aborted_request($reqstate, $err);
912 $self->client_do_disconnect($reqstate);
917 my ($self, $reqstate, $auth, $method, $path) = @_;
919 my $base_uri = $self->{base_uri};
922 my $r = $reqstate->{request};
924 # disable timeout on handle (we already have all data we need)
925 # we re-enable timeout in response()
926 $reqstate->{hdl}->timeout(0);
928 if ($path =~ m/^\Q$base_uri\E/) {
929 $self->handle_api2_request($reqstate, $auth, $method, $path);
933 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
934 if (ref($handler) eq 'CODE') {
935 my $params = decode_urlencoded($r->url->query());
936 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
938 Net::SSLeay::ERR_clear_error();
939 $self->response($reqstate, $resp);
940 } elsif (ref($handler) eq 'HASH') {
941 if (my $filename = $handler->{file}) {
942 my $fh = IO::File->new($filename) ||
943 die "unable to
open file
'$filename' - $!\n";
944 send_file_start($self, $reqstate, $filename);
946 die "internal error
- no handler
";
949 die "internal error
- no handler
";
954 if ($self->{dirs} && ($method eq 'GET')) {
955 # we only allow simple names
956 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
957 my ($subdir, $file) = ($1, $2);
958 if (my $dir = $self->{dirs}->{$subdir}) {
959 my $filename = "$dir$file";
960 my $fh = IO::File->new($filename) ||
961 die "unable to
open file
'$filename' - $!\n";
962 send_file_start($self, $reqstate, $filename);
968 die "no such file
'$path'\n";
971 $self->error($reqstate, 501, $err);
975 sub file_upload_multipart {
976 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
979 my $boundary = $rstate->{boundary};
980 my $hdl = $reqstate->{hdl};
982 my $startlen = length($hdl->{rbuf});
984 if ($rstate->{phase} == 0) { # skip everything until start
985 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
986 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
988 my ($ct, $disp, $name, $filename);
989 foreach my $line (split(/\015?\012/, $header)) {
990 # assume we have single line headers
991 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
992 $ct = parse_content_type($1);
993 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
994 ($disp, $name, $filename) = parse_content_disposition($1);
998 if (!($disp && $disp eq 'form-data' && $name)) {
999 syslog('err', "wrong content disposition
in multipart
- abort upload
");
1000 $rstate->{phase} = -1;
1003 $rstate->{fieldname} = $name;
1006 if ($name eq 'filename') {
1007 # found file upload data
1008 $rstate->{phase} = 1;
1009 $rstate->{filename} = $filename;
1011 syslog('err', "wrong field name
for file upload
- abort upload
");
1012 $rstate->{phase} = -1;
1015 # found form data for field $name
1016 $rstate->{phase} = 2;
1020 my $len = length($hdl->{rbuf});
1021 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
1022 if $len > $rstate->{maxheader}; # skip garbage
1024 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
1025 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1026 my ($rest, $eof) = ($1, $3);
1027 my $len = length($rest);
1028 die "write to temporary file failed
- $!"
1029 if syswrite($rstate->{outfh}, $rest) != $len;
1030 $rstate->{ctx}->add($rest);
1031 $rstate->{params}->{filename} = $rstate->{filename};
1032 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
1033 $rstate->{bytes} += $len;
1034 $rstate->{phase} = $eof ? 100 : 0;
1036 my $len = length($hdl->{rbuf});
1037 my $wlen = $len - $rstate->{boundlen};
1039 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
1040 die "write to temporary file failed
- $!"
1041 if syswrite($rstate->{outfh}, $data) != $wlen;
1042 $rstate->{bytes} += $wlen;
1043 $rstate->{ctx}->add($data);
1046 } elsif ($rstate->{phase} == 2) { # inside normal field
1048 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1049 my ($rest, $eof) = ($1, $3);
1050 my $len = length($rest);
1051 $rstate->{post_size} += $len;
1052 if ($rstate->{post_size} < $limit_max_post) {
1053 $rstate->{params}->{$rstate->{fieldname}} = $rest;
1054 $rstate->{phase} = $eof ? 100 : 0;
1056 syslog('err', "form data to large
- abort upload
");
1057 $rstate->{phase} = -1; # skip
1061 my $len = length($hdl->{rbuf});
1062 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
1065 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
1067 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
1068 $rstate->{done} = 1; # make sure we dont get called twice
1069 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
1070 die "upload failed
\n";
1072 my $elapsed = tv_interval($rstate->{starttime});
1074 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
1075 syslog('info', "multipart upload complete
" .
1076 "(size
: %d time: %ds rate
: %.2fMiB
/s md5sum
: $rstate->{md5sum
})",
1077 $rstate->{bytes}, $elapsed, $rate);
1078 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1083 syslog('err', $err);
1084 $self->error($reqstate, 501, $err);
1088 sub parse_content_type {
1091 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
1093 foreach my $v (@params) {
1094 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1095 return wantarray ? ($ct, $1) : $ct;
1099 return wantarray ? ($ct) : $ct;
1102 sub parse_content_disposition {
1105 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
1109 foreach my $v (@params) {
1110 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
1112 $name =~ s/^"(.*)"$/$1/;
1113 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
1115 $filename =~ s/^"(.*)"$/$1/;
1119 return wantarray ? ($disp, $name, $filename) : $disp;
1122 my $tmpfile_seq_no = 0;
1124 sub get_upload_filename {
1125 # choose unpredictable tmpfile name
1128 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1131 sub unshift_read_header {
1132 my ($self, $reqstate, $state) = @_;
1134 $state = { size => 0, count => 0 } if !$state;
1136 $reqstate->{hdl}->unshift_read(line => sub {
1137 my ($hdl, $line) = @_;
1140 # print "$$: got header
: $line\n" if $self->{debug};
1142 die "to many http header lines
\n" if ++$state->{count} >= $limit_max_headers;
1143 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1145 my $r = $reqstate->{request};
1148 my $path = uri_unescape($r->uri->path());
1149 my $method = $r->method();
1151 $r->push_header($state->{key}, $state->{val})
1154 if (!$known_methods->{$method}) {
1155 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
1156 $self->response($reqstate, $resp);
1160 my $conn = $r->header('Connection');
1161 my $accept_enc = $r->header('Accept-Encoding');
1162 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1165 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1167 if ($reqstate->{proto}->{ver} < 1001) {
1168 $reqstate->{keep_alive} = 0;
1172 my $te = $r->header('Transfer-Encoding');
1173 if ($te && lc($te) eq 'chunked') {
1174 # Handle chunked transfer encoding
1175 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
1178 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
1182 my $pveclientip = $r->header('PVEClientIP');
1183 my $base_uri = $self->{base_uri};
1185 # fixme: how can we make PVEClientIP header trusted?
1186 if ($self->{trusted_env} && $pveclientip) {
1187 $reqstate->{peer_host} = $pveclientip;
1189 $r->header('PVEClientIP', $reqstate->{peer_host});
1192 my $len = $r->header('Content-Length');
1194 # header processing complete - authenticate now
1197 if ($self->{spiceproxy}) {
1198 my $connect_str = $r->header('Host');
1199 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
1200 if (!(defined($vmid) && $node && $port)) {
1201 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket
");
1204 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1206 } elsif ($path =~ m/^\Q$base_uri\E/) {
1207 my $token = $r->header('CSRFPreventionToken');
1208 my $cookie = $r->header('Cookie');
1209 my $ticket = PVE::APIServer::Formatter::extract_auth_cookie($cookie, $self->{cookie_name});
1211 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1213 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
1218 $auth = $self->auth_handler($method, $rel_uri, $ticket, $token,
1219 $reqstate->{peer_host});
1223 Net::SSLeay::ERR_clear_error();
1224 # always delay unauthorized calls by 3 seconds
1227 if (ref($err) eq "PVE
::Exception
") {
1229 $err->{code} ||= HTTP_INTERNAL_SERVER_ERROR,
1230 my $resp = HTTP::Response->new($err->{code}, $err->{msg});
1231 $self->response($reqstate, $resp, undef, 0, $delay);
1233 } elsif (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
1234 my ($raw, $ct, $nocomp) =
1235 $formatter->($path, $auth, $self->{formatter_config});
1237 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1240 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required
");
1241 $resp->header("Content-Type
" => $ct);
1242 $resp->content($raw);
1244 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1246 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1247 $self->response($reqstate, $resp, undef, 0, $delay);
1253 $reqstate->{log}->{userid} = $auth->{userid};
1257 if (!($method eq 'PUT' || $method eq 'POST')) {
1258 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
1262 my $ctype = $r->header('Content-Type');
1263 my ($ct, $boundary) = parse_content_type($ctype) if $ctype;
1265 if ($auth->{isUpload} && !$self->{trusted_env}) {
1266 die "upload
'Content-Type '$ctype' not implemented\n"
1267 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
1269 die "upload without content length header not supported" if !$len;
1271 die "upload without content length header not supported" if !$len;
1273 print "start upload $path $ct $boundary\n" if $self->{debug};
1275 my $tmpfilename = get_upload_filename();
1276 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1277 die "unable to create temporary upload file '$tmpfilename'";
1279 $reqstate->{keep_alive} = 0;
1281 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1285 boundary => $boundary,
1286 ctx => Digest::MD5->new,
1287 boundlen => $boundlen,
1288 maxheader => 2048 + $boundlen, # should be large enough
1289 params => decode_urlencoded($r->url->query()),
1293 starttime => [gettimeofday],
1296 $reqstate->{tmpfilename} = $tmpfilename;
1297 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $method, $path, $state); });
1301 if ($len > $limit_max_post) {
1302 $self->error($reqstate, 501, "for data too large");
1306 if (!$ct || $ct eq 'application
/x-www-form-urlencoded
') {
1307 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1308 my ($hdl, $data) = @_;
1310 $self->handle_request($reqstate, $auth, $method, $path);
1313 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
1316 $self->handle_request($reqstate, $auth, $method, $path);
1318 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1319 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1320 ($state->{key}, $state->{val}) = ($1, $2);
1321 $self->unshift_read_header($reqstate, $state);
1322 } elsif ($line =~ /^\s+(.*)/) {
1323 $state->{val} .= " $1";
1324 $self->unshift_read_header($reqstate, $state);
1326 $self->error($reqstate, 506, "unable to parse request header
");
1333 sub push_request_header {
1334 my ($self, $reqstate) = @_;
1337 $reqstate->{hdl}->push_read(line => sub {
1338 my ($hdl, $line) = @_;
1341 # print "got request header
: $line\n" if $self->{debug};
1343 $reqstate->{keep_alive}--;
1345 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1346 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1349 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
1353 $self->{request_count}++; # only count valid request headers
1354 if ($self->{request_count} >= $self->{max_requests}) {
1355 $self->{end_loop} = 1;
1357 $reqstate->{log} = { requestline => $line };
1358 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
1359 $reqstate->{proto}->{maj} = $maj;
1360 $reqstate->{proto}->{min} = $min;
1361 $reqstate->{proto}->{ver} = $maj*1000+$min;
1362 $reqstate->{request} = HTTP::Request->new($method, $url);
1363 $reqstate->{starttime} = [gettimeofday],
1365 $self->unshift_read_header($reqstate);
1366 } elsif ($line eq '') {
1367 # ignore empty lines before requests (browser bugs?)
1368 $self->push_request_header($reqstate);
1370 $self->error($reqstate, 400, 'bad request');
1384 return if $self->{end_loop};
1386 # we need to m make sure that only one process calls accept
1387 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1388 next if $! == EINTR;
1389 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
1395 while (!$self->{end_loop} &&
1396 !defined($clientfh = $self->{socket}->accept()) &&
1399 if ($self->{end_loop}) {
1402 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1403 if (!defined($clientfh)) {
1404 $errmsg = "failed to
accept connection
: $!\n";
1410 flock($self->{lockfh}, Fcntl::LOCK_UN());
1412 if (!defined($clientfh)) {
1414 die $errmsg if $errmsg;
1417 fh_nonblocking $clientfh, 1;
1419 $self->{conn_count}++;
1427 $self->{end_loop} = 1;
1429 undef $self->{socket_watch};
1431 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1433 if ($self->{conn_count} <= 0) {
1434 $self->{end_cond}->send(1);
1438 # fork and exit, so that parent starts a new worker
1443 # else we need to wait until all open connections gets closed
1444 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1446 # todo: test for active connections instead (we can abort idle connections)
1447 if ($self->{conn_count} <= 0) {
1449 $self->{end_cond}->send(1);
1457 sub check_host_access {
1458 my ($self, $clientip) = @_;
1460 my $cip = Net::IP->new($clientip);
1462 my $match_allow = 0;
1465 if ($self->{allow_from}) {
1466 foreach my $t (@{$self->{allow_from}}) {
1467 if ($t->overlaps($cip)) {
1474 if ($self->{deny_from}) {
1475 foreach my $t (@{$self->{deny_from}}) {
1476 if ($t->overlaps($cip)) {
1483 if ($match_allow == $match_deny) {
1484 # match both allow and deny, or no match
1485 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1488 return $match_allow;
1491 sub accept_connections {
1496 while (my $clientfh = $self->accept()) {
1498 my $reqstate = { keep_alive => $self->{keep_alive} };
1500 # stop keep-alive when there are many open connections
1501 if ($self->{conn_count} >= $self->{max_conn_soft_limit}) {
1502 $reqstate->{keep_alive} = 0;
1505 if (my $sin = getpeername($clientfh)) {
1506 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1507 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1510 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1511 print "$$: ABORT request from
$reqstate->{peer_host
} - access denied
\n" if $self->{debug};
1512 $reqstate->{log}->{code} = 403;
1513 $self->log_request($reqstate);
1517 $reqstate->{hdl} = AnyEvent::Handle->new(
1519 rbuf_max => 64*1024,
1520 timeout => $self->{timeout},
1521 linger => 0, # avoid problems with ssh - really needed ?
1525 $self->log_aborted_request($reqstate);
1526 $self->client_do_disconnect($reqstate);
1528 if (my $err = $@) { syslog('err', $err); }
1531 my ($hdl, $fatal, $message) = @_;
1533 $self->log_aborted_request($reqstate, $message);
1534 $self->client_do_disconnect($reqstate);
1536 if (my $err = $@) { syslog('err', "$err"); }
1538 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1540 print "$$: ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}\n" if $self->{debug};
1542 $self->push_request_header($reqstate);
1547 syslog('err', $err);
1548 $self->{end_loop} = 1;
1551 $self->wait_end_loop() if $self->{end_loop};
1554 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1555 # because we write from multiple processes, and that would arbitrarily mix output
1557 sub open_access_log {
1558 my ($self, $filename) = @_;
1560 my $old_mask = umask(0137);;
1561 my $logfh = IO::File->new($filename, ">>") ||
1562 die "unable to
open log file
'$filename' - $!\n";
1565 $logfh->autoflush(1);
1567 $self->{logfh} = $logfh;
1571 my ($self, $data) = @_;
1573 return if !defined($self->{logfh}) || !$data;
1575 my $res = $self->{logfh}->print($data);
1578 delete $self->{logfh};
1579 syslog('err', "error writing access
log");
1580 $self->{end_loop} = 1; # terminate asap
1584 sub atfork_handler {
1588 # something else do to ?
1589 close($self->{socket});
1597 $self->{end_cond}->recv;
1601 my ($this, %args) = @_;
1603 my $class = ref($this) || $this;
1605 foreach my $req (qw(socket lockfh lockfile)) {
1606 die "misssing required argument '$req'" if !defined($args{$req});
1609 my $self = bless { %args }, $class;
1611 $self->{cookie_name
} //= 'PVEAuthCookie';
1612 $self->{base_uri
} //= "/api2";
1613 $self->{dirs
} //= {};
1614 $self->{title
} //= 'API Inspector';
1615 $self->{compression
} //= 1;
1617 # formatter_config: we pass some configuration values to the Formatter
1618 $self->{formatter_config
} = {};
1619 foreach my $p (qw(cookie_name base_uri title)) {
1620 $self->{formatter_config
}->{$p} = $self->{$p};
1622 $self->{formatter_config
}->{csrfgen_func
} =
1623 $self->can('generate_csrf_prevention_token');
1625 # add default dirs which includes jquery and bootstrap
1626 my $base = '/usr/share/libpve-http-server-perl';
1627 add_dirs
($self->{dirs
}, '/css/' => "$base/css/");
1628 add_dirs
($self->{dirs
}, '/js/' => "$base/js/");
1629 add_dirs
($self->{dirs
}, '/fonts/' => "$base/fonts/");
1632 PVE
::INotify
::inotify_init
();
1634 fh_nonblocking
($self->{socket}, 1);
1636 $self->{end_loop
} = 0;
1637 $self->{conn_count
} = 0;
1638 $self->{request_count
} = 0;
1639 $self->{timeout
} = 5 if !$self->{timeout
};
1640 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1641 $self->{max_conn
} = 800 if !$self->{max_conn
};
1642 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1644 $self->{policy
} = 'allow' if !$self->{policy
};
1646 $self->{end_cond
} = AnyEvent-
>condvar;
1649 my $tls_ctx_flags = &Net
::SSLeay
::OP_NO_COMPRESSION
| &Net
::SSLeay
::OP_SINGLE_ECDH_USE
| &Net
::SSLeay
::OP_SINGLE_DH_USE
;
1650 if ( delete $self->{ssl
}->{honor_cipher_order
} ) {
1651 $tls_ctx_flags |= &Net
::SSLeay
::OP_CIPHER_SERVER_PREFERENCE
;
1654 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
1655 Net
::SSLeay
::CTX_set_options
($self->{tls_ctx
}->{ctx
}, $tls_ctx_flags);
1658 if ($self->{spiceproxy
}) {
1659 $known_methods = { CONNECT
=> 1 };
1662 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
1664 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
1666 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
1668 if ($self->{conn_count
} >= $self->{max_conn
}) {
1669 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
1670 if ($self->{conn_count
} < $self->{max_conn
}) {
1672 $self->accept_connections();
1676 $self->accept_connections();
1682 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
1683 undef $self->{term_watch
};
1684 $self->wait_end_loop();
1687 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
1688 undef $self->{quit_watch
};
1689 $self->wait_end_loop();
1692 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
1693 PVE
::INotify
::poll
(); # read inotify events
1699 # static helper to add directory including all subdirs
1700 # This can be used to setup $self->{dirs}
1702 my ($result_hash, $alias, $subdir) = @_;
1704 $result_hash->{$alias} = $subdir;
1707 my $dir = $File::Find
::dir
;
1708 if ($dir =~m!^$subdir(.*)$!) {
1709 my $name = "$alias$1/";
1710 $result_hash->{$name} = "$dir/";
1714 find
({wanted
=> $wanted, follow
=> 0, no_chdir
=> 1}, $subdir);
1717 # abstract functions - subclass should overwrite/implement them
1719 sub verify_spice_connect_url
{
1720 my ($self, $connect_str) = @_;
1724 #return ($vmid, $node, $port);
1727 # formatters can call this when the generate a new page
1728 sub generate_csrf_prevention_token
{
1729 my ($username) = @_;
1731 return undef; # do nothing by default
1735 my ($self, $method, $rel_uri, $ticket, $token, $peer_host) = @_;
1740 # ticket => $ticket,
1742 # userid => $username,
1744 # isUpload => $isUpload,
1749 my ($self, $clientip, $method, $rel_uri, $auth, $params, $format) = @_;
1751 # please do not raise exceptions here (always return a result).
1754 status
=> HTTP_NOT_IMPLEMENTED
,
1755 message
=> "Method '$method $rel_uri' not implemented",
1758 # this should return the following properties, which
1759 # are then passed to the Formatter
1761 # status: HTTP status code
1762 # message: Error message
1763 # errors: more detailed error hash (per parameter)
1764 # info: reference to JSON schema definition - useful to format output
1767 # total: additional info passed to output
1768 # changes: additional info passed to output
1770 # if you want to proxy the request to another node return this
1771 # { proxy => $remip, proxynode => $node, proxy_params => $params };
1773 # to pass the request to the local priviledged daemon use:
1774 # { proxy => 'localhost' , proxy_params => $params };
1776 # to download aspecific file use:
1777 # { download => "/path/to/file" };
1780 sub check_cert_fingerprint
{
1781 my ($self, $cert) = @_;
1786 sub initialize_cert_cache
{
1787 my ($self, $node) = @_;
1792 sub remote_node_ip
{
1793 my ($self, $node) = @_;