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();
17 # use AnyEvent::Strict; # only use this for debugging
19 use AnyEvent
::Util
qw(guard fh_nonblocking WSAEWOULDBLOCK WSAEINPROGRESS);
32 use POSIX
qw(strftime EINTR EAGAIN);
33 use Socket
qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
34 use Time
::HiRes
qw(usleep ualarm gettimeofday tv_interval);
36 #use Data::Dumper; # FIXME: remove, just use: print to_json([$var], {pretty => 1}) ."\n";
41 use HTTP
::Status
qw(:constants);
51 use PVE
::APIServer
::Formatter
;
52 use PVE
::APIServer
::Utils
;
54 my $limit_max_headers = 64;
55 my $limit_max_header_size = 8*1024;
56 my $limit_max_post = 64*1024;
65 my $split_abs_uri = sub {
66 my ($abs_uri, $base_uri) = @_;
68 my ($format, $rel_uri) = $abs_uri =~ m/^\Q$base_uri\E\/+([a-z
][a-z0-9
]+)(\
/.*)?$/;
69 $rel_uri = '/' if !$rel_uri;
71 return wantarray ?
($rel_uri, $format) : $rel_uri;
75 my ($self, $message) = @_;
77 return if !$self->{debug
};
79 my ($pkg, $pkgfile, $line, $sub) = caller(1);
80 $sub =~ s/^(?:.+::)+//;
81 print "worker[$$]: $pkg +$line: $sub: $message\n";
85 my ($self, $reqstate) = @_;
87 my $loginfo = $reqstate->{log};
89 # like apache2 common log format
90 # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
92 return if $loginfo->{written
}; # avoid duplicate logs
93 $loginfo->{written
} = 1;
95 my $peerip = $reqstate->{peer_host
} || '-';
96 my $userid = $loginfo->{userid
} || '-';
97 my $content_length = defined($loginfo->{content_length
}) ?
$loginfo->{content_length
} : '-';
98 my $code = $loginfo->{code
} || 500;
99 my $requestline = $loginfo->{requestline
} || '-';
100 my $timestr = strftime
("%d/%m/%Y:%H:%M:%S %z", localtime());
102 my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n";
104 $self->write_log($msg);
107 sub log_aborted_request {
108 my ($self, $reqstate, $error) = @_;
110 my $r = $reqstate->{request};
111 return if !$r; # no active request
114 syslog("err
", "problem with client
$reqstate->{peer_host
}; $error");
117 $self->log_request($reqstate);
120 sub cleanup_reqstate {
121 my ($reqstate, $deletetmpfile) = @_;
123 delete $reqstate->{log};
124 delete $reqstate->{request};
125 delete $reqstate->{proto};
126 delete $reqstate->{accept_gzip};
127 delete $reqstate->{starttime};
129 if ($reqstate->{tmpfilename}) {
130 unlink $reqstate->{tmpfilename} if $deletetmpfile;
131 delete $reqstate->{tmpfilename};
135 sub client_do_disconnect {
136 my ($self, $reqstate) = @_;
138 cleanup_reqstate($reqstate, 1);
140 my $shutdown_hdl = sub {
143 shutdown($hdl->{fh}, 1);
145 $hdl->on_drain(undef);
146 $hdl->on_read(undef);
150 if (my $proxyhdl = delete $reqstate->{proxyhdl}) {
151 &$shutdown_hdl($proxyhdl)
152 if !$proxyhdl->{block_disconnect};
155 my $hdl = delete $reqstate->{hdl};
158 syslog('err', "detected empty handle
");
162 $self->dprint("close connection
$hdl");
164 &$shutdown_hdl($hdl);
166 warn "connection count
<= 0!\n" if $self->{conn_count} <= 0;
168 $self->{conn_count}--;
170 $self->dprint("CLOSE FH
" . $hdl->{fh}->fileno() . " CONN
$self->{conn_count
}");
173 sub finish_response {
174 my ($self, $reqstate) = @_;
176 cleanup_reqstate($reqstate, 0);
178 my $hdl = $reqstate->{hdl};
179 return if !$hdl; # already disconnected
181 if (!$self->{end_loop} && $reqstate->{keep_alive} > 0) {
182 # print "KEEPALIVE
$reqstate->{keep_alive
}\n" if $self->{debug};
184 eval { $self->push_request_header($reqstate); };
188 $hdl->on_drain (sub {
190 $self->client_do_disconnect($reqstate);
197 sub response_stream {
198 my ($self, $reqstate, $stream_fh) = @_;
200 # disable timeout, we don't know how big the data is
201 $reqstate->{hdl}->timeout(0);
203 my $buf_size = 4*1024*1024;
208 my $reqhdl = $reqstate->{hdl};
211 my $wbuf_len = length($reqhdl->{wbuf});
212 my $rbuf_len = length($hdl->{rbuf});
213 # TODO: Take into account $reqhdl->{wbuf_max} ? Right now
214 # that's unbounded, so just assume $buf_size
215 my $to_read = $buf_size - $wbuf_len;
216 $to_read = $rbuf_len if $rbuf_len < $to_read;
218 my $data = substr($hdl->{rbuf}, 0, $to_read, '');
219 $reqhdl->push_write($data);
220 $rbuf_len -= $to_read;
221 } elsif ($hdl->{_eof}) {
222 # workaround: AnyEvent gives us a fake EPIPE if we don't consume
223 # any data when called at EOF, so unregister ourselves - data is
224 # flushed by on_eof anyway
225 # see: https://sources.debian.org/src/libanyevent-perl/7.170-2/lib/AnyEvent/Handle.pm/#L1329
230 # apply backpressure so we don't accept any more data into
231 # buffer if the client isn't downloading fast enough
232 # note: read_size can double upon read, and we also need to
233 # account for one more read after start_read, so *4
234 if ($rbuf_len + $hdl->{read_size}*4 > $buf_size) {
235 # stop reading until write buffer is empty
237 my $prev_on_drain = $reqhdl->{on_drain};
238 $reqhdl->on_drain(sub {
240 # on_drain called because write buffer is empty, continue reading
241 $hdl->on_read($on_read);
242 if ($prev_on_drain) {
243 $wrhdl->on_drain($prev_on_drain);
244 $prev_on_drain->($wrhdl);
250 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
252 rbuf_max => $buf_size,
258 if (my $reqhdl = $reqstate->{hdl}) {
259 $self->log_aborted_request($reqstate);
260 # write out any remaining data
261 $reqhdl->push_write($hdl->{rbuf}) if length($hdl->{rbuf}) > 0;
263 $reqhdl->push_shutdown();
264 $self->finish_response($reqstate);
267 if (my $err = $@) { syslog('err', "$err"); }
271 my ($hdl, $fatal, $message) = @_;
273 $self->log_aborted_request($reqstate, $message);
274 $self->client_do_disconnect($reqstate);
276 if (my $err = $@) { syslog('err', "$err"); }
283 my ($self, $reqstate, $resp, $mtime, $nocomp, $delay, $stream_fh) = @_;
285 #print "$$: send response
: " . Dumper($resp);
288 $reqstate->{hdl}->timeout_reset();
289 $reqstate->{hdl}->timeout($self->{timeout});
291 $nocomp = 1 if !$self->{compression};
292 $nocomp = 1 if !$reqstate->{accept_gzip};
294 my $code = $resp->code;
295 my $msg = $resp->message || HTTP::Status::status_message($code);
296 ($msg) = $msg =~m/^(.*)$/m;
297 my $content = $resp->content;
299 if ($code =~ /^(1\d\d|[23]04)$/) {
300 # make sure content we have no content
304 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
306 $reqstate->{log}->{code} = $code;
308 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
309 my $res = "$proto $code $msg\015\012";
312 my $date = HTTP::Date::time2str($ctime);
313 $resp->header('Date' => $date);
315 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
317 $resp->header('Expires' => $date);
318 $resp->header('Cache-Control' => "max-age
=0");
319 $resp->header("Pragma
", "no-cache
");
322 $resp->header('Server' => "pve-api-daemon
/3.0");
325 if ($content && !$stream_fh) {
327 $content_length = length($content);
329 if (!$nocomp && ($content_length > 1024)) {
330 my $comp = Compress::Zlib::memGzip($content);
331 $resp->header('Content-Encoding', 'gzip');
333 $content_length = length($content);
335 $resp->header("Content-Length
" => $content_length);
336 $reqstate->{log}->{content_length} = $content_length;
339 $resp->remove_header("Content-Length
");
342 if ($reqstate->{keep_alive} > 0) {
343 $resp->push_header('Connection' => 'Keep-Alive');
345 $resp->header('Connection' => 'close');
348 $res .= $resp->headers_as_string("\015\012");
349 #print "SEND
(without content
) $res\n" if $self->{debug};
352 $res .= $content if $content && !$stream_fh;
354 $self->log_request($reqstate, $reqstate->{request});
357 # write headers and preamble...
358 $reqstate->{hdl}->push_write($res);
359 # ...then stream data via an AnyEvent::Handle
360 $self->response_stream($reqstate, $stream_fh);
361 } elsif ($delay && $delay > 0) {
362 my $w; $w = AnyEvent->timer(after => $delay, cb => sub {
363 undef $w; # delete reference
364 $reqstate->{hdl}->push_write($res);
365 $self->finish_response($reqstate);
368 $reqstate->{hdl}->push_write($res);
369 $self->finish_response($reqstate);
374 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
377 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
378 $self->response($reqstate, $resp);
383 my $file_extension_info = {
384 css => { ct => 'text/css' },
385 html => { ct => 'text/html' },
386 js => { ct => 'application/javascript' },
387 json => { ct => 'application/json' },
388 map => { ct => 'application/json' },
389 png => { ct => 'image/png' , nocomp => 1 },
390 ico => { ct => 'image/x-icon', nocomp => 1},
391 gif => { ct => 'image/gif', nocomp => 1},
392 svg => { ct => 'image/svg+xml' },
393 jar => { ct => 'application/java-archive', nocomp => 1},
394 woff => { ct => 'application/font-woff', nocomp => 1},
395 woff2 => { ct => 'application/font-woff2', nocomp => 1},
396 ttf => { ct => 'application/font-snft', nocomp => 1},
397 pdf => { ct => 'application/pdf', nocomp => 1},
398 epub => { ct => 'application/epub+zip', nocomp => 1},
399 mp3 => { ct => 'audio/mpeg', nocomp => 1},
400 oga => { ct => 'audio/ogg', nocomp => 1},
401 tgz => { ct => 'application/x-compressed-tar', nocomp => 1},
404 sub send_file_start {
405 my ($self, $reqstate, $download) = @_;
408 # print "SEND FILE
$filename\n";
409 # Note: aio_load() this is not really async unless we use IO::AIO!
412 my $r = $reqstate->{request};
418 if (ref($download) eq 'HASH') {
419 $mime = $download->{'content-type'};
420 my $encoding = $download->{'content-encoding'};
422 if ($download->{path} && $download->{stream} &&
423 $reqstate->{request}->header('PVEDisableProxy'))
425 # avoid double stream from a file, let the proxy handle it
426 die "internal error
: file proxy streaming only available
for pvedaemon
\n"
427 if !$self->{trusted_env};
428 my $header = HTTP::Headers->new(
429 pvestreamfile => $download->{path},
430 Content_Type => $mime,
432 $header->header('Content-Encoding' => $encoding) if defined($encoding);
433 # we need some data so Content-Length gets set correctly and
434 # the proxy doesn't wait for more data - place a canary
435 my $resp = HTTP::Response->new(200, "OK
", $header, "error canary
");
436 $self->response($reqstate, $resp);
440 if (!($fh = $download->{fh})) {
441 my $path = $download->{path};
442 die "internal error
: {download
} returned but neither fh
not path
given\n"
444 sysopen($fh, "$path", O_NONBLOCK | O_RDONLY)
445 or die "open stream path
'$path' for reading failed
: $!\n";
448 if ($download->{stream}) {
449 my $header = HTTP::Headers->new(Content_Type => $mime);
450 $header->header('Content-Encoding' => $encoding) if defined($encoding);
451 my $resp = HTTP::Response->new(200, "OK
", $header);
452 $self->response($reqstate, $resp, undef, 1, 0, $fh);
456 my $filename = $download;
457 $fh = IO::File->new($filename, '<') ||
458 die "unable to
open file
'$filename' - $!\n";
460 my ($ext) = $filename =~ m/\.([^.]*)$/;
461 my $ext_info = $file_extension_info->{$ext};
463 die "unable to detect content type
" if !$ext_info;
464 $mime = $ext_info->{ct};
465 $nocomp = $ext_info->{nocomp};
468 my $stat = File::stat::stat($fh) ||
471 my $mtime = $stat->mtime;
473 if (my $ifmod = $r->header('if-modified-since')) {
474 my $iftime = HTTP::Date::str2time($ifmod);
475 if ($mtime <= $iftime) {
476 my $resp = HTTP::Response->new(304, "NOT MODIFIED
");
477 $self->response($reqstate, $resp, $mtime);
483 my $len = sysread($fh, $data, $stat->size);
484 die "got short file
\n" if !defined($len) || $len != $stat->size;
486 my $header = HTTP::Headers->new(Content_Type => $mime);
487 my $resp = HTTP::Response->new(200, "OK
", $header, $data);
488 $self->response($reqstate, $resp, $mtime, $nocomp);
491 $self->error($reqstate, 501, $err);
498 sub websocket_proxy {
499 my ($self, $reqstate, $wsaccept, $wsproto, $param) = @_;
505 my $max_payload_size = 128*1024;
507 if ($param->{port}) {
508 $remhost = 'localhost';
509 $remport = $param->{port};
510 } elsif ($param->{socket}) {
512 $remport = $param->{socket};
514 die "websocket_proxy
: missing port
or socket\n";
518 my ($data, $opcode) = @_;
523 $string = $opcode ? $opcode : "\x82"; # binary frame
526 my $payload_len = length($payload);
527 if ($payload_len <= 125) {
528 $string .= pack 'C', $payload_len;
529 } elsif ($payload_len <= 0xffff) {
530 $string .= pack 'C', 126;
531 $string .= pack 'n', $payload_len;
533 $string .= pack 'C', 127;
534 $string .= pack 'Q>', $payload_len;
540 tcp_connect $remhost, $remport, sub {
542 or die "connect to
'$remhost:$remport' failed
: $!";
544 $self->dprint("CONNECTed to
'$remhost:$remport'");
546 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
548 rbuf_max => $max_payload_size,
549 wbuf_max => $max_payload_size*5,
554 $self->log_aborted_request($reqstate);
555 $self->client_do_disconnect($reqstate);
557 if (my $err = $@) { syslog('err', $err); }
560 my ($hdl, $fatal, $message) = @_;
562 $self->log_aborted_request($reqstate, $message);
563 $self->client_do_disconnect($reqstate);
565 if (my $err = $@) { syslog('err', "$err"); }
568 my $proxyhdlreader = sub {
571 my $len = length($hdl->{rbuf});
572 my $data = substr($hdl->{rbuf}, 0, $len > $max_payload_size ? $max_payload_size : $len, '');
574 my $string = $encode->(\$data);
576 $reqstate->{hdl}->push_write($string) if $reqstate->{hdl};
579 my $hdlreader = sub {
582 while (my $len = length($hdl->{rbuf})) {
585 my $hdr = unpack('C', substr($hdl->{rbuf}, 0, 1));
586 my $opcode = $hdr & 0b00001111;
587 my $fin = $hdr & 0b10000000;
589 die "received fragmented websocket frame
\n" if !$fin;
591 my $rsv = $hdr & 0b01110000;
592 die "received websocket frame with RSV flags
\n" if $rsv;
594 my $payload_len = unpack 'C', substr($hdl->{rbuf}, 1, 1);
596 my $masked = $payload_len & 0b10000000;
597 die "received unmasked websocket frame from client
\n" if !$masked;
600 $payload_len = $payload_len & 0b01111111;
601 if ($payload_len == 126) {
603 $payload_len = unpack('n', substr($hdl->{rbuf}, $offset, 2));
605 } elsif ($payload_len == 127) {
607 $payload_len = unpack('Q>', substr($hdl->{rbuf}, $offset, 8));
611 die "received too large websocket frame
(len
= $payload_len)\n"
612 if ($payload_len > $max_payload_size) || ($payload_len < 0);
614 return if $len < ($offset + 4 + $payload_len);
616 my $data = substr($hdl->{rbuf}, 0, $offset + 4 + $payload_len, ''); # now consume data
618 my $mask = substr($data, $offset, 4);
621 my $payload = substr($data, $offset, $payload_len);
623 # NULL-mask might be used over TLS, skip to increase performance
624 if ($mask ne pack('N', 0)) {
625 # repeat 4 byte mask to payload length + up to 4 byte
626 $mask = $mask x (int($payload_len / 4) + 1);
627 # truncate mask to payload length
628 substr($mask, $payload_len) = "";
633 if ($opcode == 1 || $opcode == 2) {
634 $reqstate->{proxyhdl}->push_write($payload) if $reqstate->{proxyhdl};
635 } elsif ($opcode == 8) {
636 my $statuscode = unpack ("n
", $payload);
637 $self->dprint("websocket received
close. status code
: '$statuscode'");
638 if (my $proxyhdl = $reqstate->{proxyhdl}) {
639 $proxyhdl->{block_disconnect} = 1 if length $proxyhdl->{wbuf};
641 $proxyhdl->push_shutdown();
643 $hdl->push_shutdown();
644 } elsif ($opcode == 9) {
645 # ping received, schedule pong
646 $reqstate->{hdl}->push_write($encode->(\$payload, "\x8A")) if $reqstate->{hdl};
647 } elsif ($opcode == 0xA) {
648 # pong received, continue
650 die "received unhandled websocket opcode
$opcode\n";
655 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.1';
657 $reqstate->{proxyhdl}->timeout(0);
658 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
659 $reqstate->{hdl}->on_read($hdlreader);
661 # todo: use stop_read/start_read if write buffer grows to much
663 # FIXME: remove protocol in PVE/PMG 8.x
665 # for backwards, compatibility, we have to reply with the websocket
666 # subprotocol from the request
667 my $res = "$proto 101 Switching Protocols
\015\012" .
668 "Upgrade
: websocket
\015\012" .
669 "Connection
: upgrade
\015\012" .
670 "Sec-WebSocket-Accept
: $wsaccept\015\012" .
671 ($wsproto ne "" ? "Sec-WebSocket-Protocol
: $wsproto\015\012" : "") .
676 $reqstate->{hdl}->push_write($res);
679 $reqstate->{log}->{code} = 101;
680 $self->log_request($reqstate);
686 $self->log_aborted_request($reqstate, $err);
687 $self->client_do_disconnect($reqstate);
692 my ($self, $reqstate, $clientip, $host, $node, $method, $uri, $auth, $params) = @_;
697 if ($host eq 'localhost') {
698 $target = "http
://$host:85$uri";
699 # keep alive for localhost is not worth (connection setup is about 0.2ms)
701 } elsif (Net::IP::ip_is_ipv6($host)) {
702 $target = "https
://[$host]:8006$uri";
704 $target = "https
://$host:8006$uri";
708 PVEDisableProxy => 'true',
709 PVEClientIP => $clientip,
712 $headers->{'cookie'} = PVE::APIServer::Formatter::create_auth_cookie($auth->{ticket}, $self->{cookie_name})
714 $headers->{'Authorization'} = PVE::APIServer::Formatter::create_auth_header($auth->{api_token}, $self->{apitoken_name})
715 if $auth->{api_token};
716 $headers->{'CSRFPreventionToken'} = $auth->{token}
718 $headers->{'Accept-Encoding'} = 'gzip' if ($reqstate->{accept_gzip} && $self->{compression});
720 if (defined(my $host = $reqstate->{request}->header('Host'))) {
721 $headers->{Host} = $host;
726 if ($method eq 'POST' || $method eq 'PUT') {
727 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
728 # use URI object to format application/x-www-form-urlencoded content.
729 my $url = URI->new('http:');
730 $url->query_form(%$params);
731 $content = $url->query;
732 if (defined($content)) {
733 $headers->{'Content-Length'} = length($content);
738 # TLS 1.x only, with certificate pinning
744 my (undef, undef, undef, $depth, undef, undef, $cert) = @_;
745 # we don't care about intermediate or root certificates
746 return 1 if $depth != 0;
747 # check server certificate against cache of pinned FPs
748 return $self->check_cert_fingerprint($cert);
752 # load and cache cert fingerprint if first time we proxy to this node
753 $self->initialize_cert_cache($node);
755 my $w; $w = http_request(
760 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
761 keepalive => $keep_alive,
763 tls_ctx => AnyEvent::TLS->new(%{$tls}),
765 my ($body, $hdr) = @_;
769 if (!$reqstate->{hdl}) {
770 warn "proxy detected vanished client connection
\n";
775 my $code = delete $hdr->{Status};
776 my $msg = delete $hdr->{Reason};
777 my $stream = delete $hdr->{pvestreamfile};
779 delete $hdr->{HTTPVersion};
780 my $header = HTTP::Headers->new(%$hdr);
781 if (my $location = $header->header('Location')) {
782 $location =~ s|^http://localhost:85||;
783 $header->header(Location => $location);
786 sysopen(my $fh, "$stream", O_NONBLOCK | O_RDONLY)
787 or die "open stream path
'$stream' for forwarding failed
: $!\n";
788 my $resp = HTTP::Response->new($code, $msg, $header, undef);
789 $self->response($reqstate, $resp, undef, 1, 0, $fh);
791 my $resp = HTTP::Response->new($code, $msg, $header, $body);
792 # Note: disable compression, because body is already compressed
793 $self->response($reqstate, $resp, undef, 1);
802 # return arrays as \0 separated strings (like CGI.pm)
803 # assume data is UTF8 encoded
804 sub decode_urlencoded {
809 return $res if !$data;
811 foreach my $kv (split(/[\&\;]/, $data)) {
812 my ($k, $v) = split(/=/, $kv);
814 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
818 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
820 $v = Encode::decode('utf8', $v);
822 if (defined(my $old = $res->{$k})) {
833 my ($r, $method) = @_;
837 if ($method eq 'PUT' || $method eq 'POST') {
839 if (my $ctype = $r->header('Content-Type')) {
840 $ct = parse_content_type($ctype);
842 if (defined($ct) && $ct eq 'application/json') {
843 $params = decode_json($r->content);
845 $params = decode_urlencoded($r->content);
849 my $query_params = decode_urlencoded($r->url->query());
851 foreach my $k (keys %{$query_params}) {
852 $params->{$k} = $query_params->{$k};
858 sub handle_api2_request {
859 my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
862 my $r = $reqstate->{request};
864 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
866 my $formatter = PVE::APIServer::Formatter::get_formatter($format, $method, $rel_uri);
868 if (!defined($formatter)) {
869 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no formatter
for uri
$rel_uri, $format");
873 #print Dumper($upload_state) if $upload_state;
878 $params = $upload_state->{params};
880 $params = extract_params($r, $method);
883 delete $params->{_dc}; # remove disable cache parameter
885 my $clientip = $reqstate->{peer_host};
887 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
890 Net::SSLeay::ERR_clear_error();
892 AnyEvent->now_update(); # in case somebody called sleep()
894 my $upgrade = $r->header('upgrade');
895 $upgrade = lc($upgrade) if $upgrade;
897 if (my $host = $res->{proxy}) {
899 if ($self->{trusted_env}) {
900 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
904 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
905 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
909 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
911 $self->proxy_request($reqstate, $clientip, $host, $res->{proxynode}, $method,
912 $r->uri, $auth, $res->{proxy_params});
915 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
916 die "unable to upgrade to protocol
'$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
917 my $wsver = $r->header('sec-websocket-version');
918 die "unsupported websocket-version
'$wsver'\n" if !$wsver || ($wsver ne '13');
919 my $wsproto = $r->header('sec-websocket-protocol') // "";
920 my $wskey = $r->header('sec-websocket-key');
921 die "missing websocket-key
\n" if !$wskey;
922 # Note: Digest::SHA::sha1_base64 has wrong padding
923 my $wsaccept = Digest::SHA::sha1_base64("${wskey
}258EAFA5-E914-47DA-95CA-C5AB0DC85B11
") . "=";
924 if ($res->{status} == HTTP_OK) {
925 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
931 if ($res->{status} == HTTP_UNAUTHORIZED) {
932 # always delay unauthorized calls by 3 seconds
933 $delay = 3 - tv_interval($reqstate->{starttime});
934 $delay = 0 if $delay < 0;
937 my $download = $res->{download};
938 $download //= $res->{data}->{download}
939 if defined($res->{data}) && ref($res->{data}) eq 'HASH';
940 if (defined($download)) {
941 send_file_start($self, $reqstate, $download);
945 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
946 $auth, $self->{formatter_config});
949 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
952 $resp = HTTP::Response->new($res->{status}, $res->{message});
953 $resp->header("Content-Type
" => $ct);
954 $resp->content($raw);
956 $self->response($reqstate, $resp, undef, $nocomp, $delay);
959 $self->error($reqstate, 501, $err);
963 sub handle_spice_proxy_request {
964 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
968 my ($minport, $maxport) = PVE::Tools::spice_port_range();
969 if ($spiceport < $minport || $spiceport > $maxport) {
970 die "SPICE Port
$spiceport is not in allowed range
($minport, $maxport)\n";
973 my $clientip = $reqstate->{peer_host};
974 my $r = $reqstate->{request};
978 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
979 $remip = $self->remote_node_ip($node);
980 $self->dprint("REMOTE CONNECT
$vmid, $remip, $connect_str");
982 $self->dprint("CONNECT
$vmid, $node, $spiceport");
985 if ($remip && $r->header('PVEDisableProxy')) {
986 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
990 $reqstate->{hdl}->timeout(0);
991 $reqstate->{hdl}->wbuf_max(64*10*1024);
993 my $remhost = $remip ? $remip : "localhost
";
994 my $remport = $remip ? 3128 : $spiceport;
996 tcp_connect $remhost, $remport, sub {
998 or die "connect to
'$remhost:$remport' failed
: $!";
1000 $self->dprint("CONNECTed to
'$remhost:$remport'");
1001 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
1003 rbuf_max => 64*1024,
1004 wbuf_max => 64*10*1024,
1009 $self->log_aborted_request($reqstate);
1010 $self->client_do_disconnect($reqstate);
1012 if (my $err = $@) { syslog('err', $err); }
1015 my ($hdl, $fatal, $message) = @_;
1017 $self->log_aborted_request($reqstate, $message);
1018 $self->client_do_disconnect($reqstate);
1020 if (my $err = $@) { syslog('err', "$err"); }
1024 my $proxyhdlreader = sub {
1027 my $len = length($hdl->{rbuf});
1028 my $data = substr($hdl->{rbuf}, 0, $len, '');
1030 #print "READ1
$len\n";
1031 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
1034 my $hdlreader = sub {
1037 my $len = length($hdl->{rbuf});
1038 my $data = substr($hdl->{rbuf}, 0, $len, '');
1040 #print "READ0
$len\n";
1041 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
1044 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
1046 my $startproxy = sub {
1047 $reqstate->{proxyhdl}->timeout(0);
1048 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
1049 $reqstate->{hdl}->on_read($hdlreader);
1051 # todo: use stop_read/start_read if write buffer grows to much
1053 # a response must be followed by an empty line
1054 my $res = "$proto 200 OK
\015\012\015\012";
1055 $reqstate->{hdl}->push_write($res);
1058 $reqstate->{log}->{code} = 200;
1059 $self->log_request($reqstate);
1063 my $header = "CONNECT
${connect_str
} $proto\015\012" .
1064 "Host
: ${connect_str
}\015\012" .
1065 "Proxy-Connection
: keep-alive
\015\012" .
1066 "User-Agent
: spiceproxy
\015\012" .
1067 "PVEDisableProxy
: true
\015\012" .
1068 "PVEClientIP
: $clientip\015\012" .
1071 $reqstate->{proxyhdl}->push_write($header);
1072 $reqstate->{proxyhdl}->push_read(line => sub {
1073 my ($hdl, $line) = @_;
1075 if ($line =~ m!^$proto 200 OK$!) {
1076 # read the empty line after the 200 OK
1077 $reqstate->{proxyhdl}->unshift_read(line => sub{
1081 $reqstate->{hdl}->push_write($line);
1082 $self->client_do_disconnect($reqstate);
1093 $self->log_aborted_request($reqstate, $err);
1094 $self->client_do_disconnect($reqstate);
1098 sub handle_request {
1099 my ($self, $reqstate, $auth, $method, $path) = @_;
1101 my $base_uri = $self->{base_uri};
1104 my $r = $reqstate->{request};
1106 # disable timeout on handle (we already have all data we need)
1107 # we re-enable timeout in response()
1108 $reqstate->{hdl}->timeout(0);
1110 if ($path =~ m/^\Q$base_uri\E/) {
1111 $self->handle_api2_request($reqstate, $auth, $method, $path);
1115 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
1116 if (ref($handler) eq 'CODE') {
1117 my $params = decode_urlencoded($r->url->query());
1118 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
1120 Net::SSLeay::ERR_clear_error();
1121 $self->response($reqstate, $resp);
1122 } elsif (ref($handler) eq 'HASH') {
1123 if (my $filename = $handler->{file}) {
1124 my $fh = IO::File->new($filename) ||
1125 die "unable to
open file
'$filename' - $!\n";
1126 send_file_start($self, $reqstate, $filename);
1128 die "internal error
- no handler
";
1131 die "internal error
- no handler
";
1136 if ($self->{dirs} && ($method eq 'GET')) {
1137 # we only allow simple names
1138 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
1139 my ($subdir, $file) = ($1, $2);
1140 if (my $dir = $self->{dirs}->{$subdir}) {
1141 my $filename = "$dir$file";
1142 my $fh = IO::File->new($filename) ||
1143 die "unable to
open file
'$filename' - $!\n";
1144 send_file_start($self, $reqstate, $filename);
1150 die "no such file
'$path'\n";
1153 $self->error($reqstate, 501, $err);
1157 sub file_upload_multipart {
1158 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
1161 my $boundary = $rstate->{boundary};
1162 my $hdl = $reqstate->{hdl};
1164 my $startlen = length($hdl->{rbuf});
1166 if ($rstate->{phase} == 0) { # skip everything until start
1167 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
1168 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
1170 my ($ct, $disp, $name, $filename);
1171 foreach my $line (split(/\015?\012/, $header)) {
1172 # assume we have single line headers
1173 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
1174 $ct = parse_content_type($1);
1175 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
1176 ($disp, $name, $filename) = parse_content_disposition($1);
1180 if (!($disp && $disp eq 'form-data' && $name)) {
1181 syslog('err', "wrong content disposition
in multipart
- abort upload
");
1182 $rstate->{phase} = -1;
1185 $rstate->{fieldname} = $name;
1188 if ($name eq 'filename') {
1189 # found file upload data
1190 $rstate->{phase} = 1;
1191 $rstate->{filename} = $filename;
1193 syslog('err', "wrong field name
for file upload
- abort upload
");
1194 $rstate->{phase} = -1;
1197 # found form data for field $name
1198 $rstate->{phase} = 2;
1202 my $len = length($hdl->{rbuf});
1203 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
1204 if $len > $rstate->{maxheader}; # skip garbage
1206 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
1207 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1208 my ($rest, $eof) = ($1, $3);
1209 my $len = length($rest);
1210 die "write to temporary file failed
- $!"
1211 if syswrite($rstate->{outfh}, $rest) != $len;
1212 $rstate->{ctx}->add($rest);
1213 $rstate->{params}->{filename} = $rstate->{filename};
1214 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
1215 $rstate->{bytes} += $len;
1216 $rstate->{phase} = $eof ? 100 : 0;
1218 my $len = length($hdl->{rbuf});
1219 my $wlen = $len - $rstate->{boundlen};
1221 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
1222 die "write to temporary file failed
- $!"
1223 if syswrite($rstate->{outfh}, $data) != $wlen;
1224 $rstate->{bytes} += $wlen;
1225 $rstate->{ctx}->add($data);
1228 } elsif ($rstate->{phase} == 2) { # inside normal field
1230 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1231 my ($rest, $eof) = ($1, $3);
1232 my $len = length($rest);
1233 $rstate->{post_size} += $len;
1234 if ($rstate->{post_size} < $limit_max_post) {
1235 $rstate->{params}->{$rstate->{fieldname}} = $rest;
1236 $rstate->{phase} = $eof ? 100 : 0;
1238 syslog('err', "form data to large
- abort upload
");
1239 $rstate->{phase} = -1; # skip
1243 my $len = length($hdl->{rbuf});
1244 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
1247 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
1249 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
1250 $rstate->{done} = 1; # make sure we dont get called twice
1251 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
1252 die "upload failed
\n";
1254 my $elapsed = tv_interval($rstate->{starttime});
1256 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
1257 syslog('info', "multipart upload complete
" .
1258 "(size
: %d time: %ds rate
: %.2fMiB
/s md5sum
: $rstate->{md5sum
})",
1259 $rstate->{bytes}, $elapsed, $rate);
1260 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1265 syslog('err', $err);
1266 $self->error($reqstate, 501, $err);
1270 sub parse_content_type {
1273 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
1275 foreach my $v (@params) {
1276 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1277 return wantarray ? ($ct, $1) : $ct;
1281 return wantarray ? ($ct) : $ct;
1284 sub parse_content_disposition {
1287 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
1291 foreach my $v (@params) {
1292 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
1294 $name =~ s/^"(.*)"$/$1/;
1295 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
1297 $filename =~ s/^"(.*)"$/$1/;
1301 return wantarray ? ($disp, $name, $filename) : $disp;
1304 my $tmpfile_seq_no = 0;
1306 sub get_upload_filename {
1307 # choose unpredictable tmpfile name
1310 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1313 sub unshift_read_header {
1314 my ($self, $reqstate, $state) = @_;
1316 $state = { size => 0, count => 0 } if !$state;
1318 $reqstate->{hdl}->unshift_read(line => sub {
1319 my ($hdl, $line) = @_;
1322 # print "$$: got header
: $line\n" if $self->{debug};
1324 die "too many http header lines
(> $limit_max_headers)\n" if ++$state->{count} >= $limit_max_headers;
1325 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1327 my $r = $reqstate->{request};
1330 my $path = uri_unescape($r->uri->path());
1331 my $method = $r->method();
1333 $r->push_header($state->{key}, $state->{val})
1336 if (!$known_methods->{$method}) {
1337 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
1338 $self->response($reqstate, $resp);
1342 my $conn = $r->header('Connection');
1343 my $accept_enc = $r->header('Accept-Encoding');
1344 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1347 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1349 if ($reqstate->{proto}->{ver} < 1001) {
1350 $reqstate->{keep_alive} = 0;
1354 my $te = $r->header('Transfer-Encoding');
1355 if ($te && lc($te) eq 'chunked') {
1356 # Handle chunked transfer encoding
1357 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
1360 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
1364 my $pveclientip = $r->header('PVEClientIP');
1365 my $base_uri = $self->{base_uri};
1367 # fixme: how can we make PVEClientIP header trusted?
1368 if ($self->{trusted_env} && $pveclientip) {
1369 $reqstate->{peer_host} = $pveclientip;
1371 $r->header('PVEClientIP', $reqstate->{peer_host});
1374 my $len = $r->header('Content-Length');
1376 my $host_header = $r->header('Host');
1377 if (my $rpcenv = $self->{rpcenv}) {
1378 $rpcenv->set_request_host($host_header);
1381 # header processing complete - authenticate now
1384 if ($self->{spiceproxy}) {
1385 my $connect_str = $host_header;
1386 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
1387 if (!(defined($vmid) && $node && $port)) {
1388 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket
");
1391 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1393 } elsif ($path =~ m/^\Q$base_uri\E/) {
1394 my $token = $r->header('CSRFPreventionToken');
1395 my $cookie = $r->header('Cookie');
1396 my $auth_header = $r->header('Authorization');
1398 # prefer actual cookie
1399 my $ticket = PVE::APIServer::Formatter::extract_auth_value($cookie, $self->{cookie_name});
1401 # fallback to cookie in 'Authorization' header
1402 $ticket = PVE::APIServer::Formatter::extract_auth_value($auth_header, $self->{cookie_name})
1405 # finally, fallback to API token if no ticket has been provided so far
1407 $api_token = PVE::APIServer::Formatter::extract_auth_value($auth_header, $self->{apitoken_name})
1410 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1412 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
1417 $auth = $self->auth_handler($method, $rel_uri, $ticket, $token, $api_token,
1418 $reqstate->{peer_host});
1422 Net::SSLeay::ERR_clear_error();
1423 # always delay unauthorized calls by 3 seconds
1426 if (ref($err) eq "PVE
::Exception
") {
1428 $err->{code} ||= HTTP_INTERNAL_SERVER_ERROR,
1429 my $resp = HTTP::Response->new($err->{code}, $err->{msg});
1430 $self->response($reqstate, $resp, undef, 0, $delay);
1432 } elsif (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
1433 my ($raw, $ct, $nocomp) =
1434 $formatter->($path, $auth, $self->{formatter_config});
1436 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1439 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required
");
1440 $resp->header("Content-Type
" => $ct);
1441 $resp->content($raw);
1443 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1445 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1446 $self->response($reqstate, $resp, undef, 0, $delay);
1452 $reqstate->{log}->{userid} = $auth->{userid};
1456 if (!($method eq 'PUT' || $method eq 'POST')) {
1457 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
1461 my $ctype = $r->header('Content-Type');
1462 my ($ct, $boundary);
1463 ($ct, $boundary)= parse_content_type($ctype) if $ctype;
1465 if ($auth->{isUpload} && !$self->{trusted_env}) {
1466 die "upload
'Content-Type '$ctype' not implemented\n"
1467 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
1469 die "upload without content length header not supported" if !$len;
1471 die "upload without content length header not supported" if !$len;
1473 $self->dprint("start upload $path $ct $boundary");
1475 my $tmpfilename = get_upload_filename();
1476 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1477 die "unable to create temporary upload file '$tmpfilename'";
1479 $reqstate->{keep_alive} = 0;
1481 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1485 boundary => $boundary,
1486 ctx => Digest::MD5->new,
1487 boundlen => $boundlen,
1488 maxheader => 2048 + $boundlen, # should be large enough
1489 params => decode_urlencoded($r->url->query()),
1493 starttime => [gettimeofday],
1496 $reqstate->{tmpfilename} = $tmpfilename;
1497 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $method, $path, $state); });
1501 if ($len > $limit_max_post) {
1502 $self->error($reqstate, 501, "for data too large");
1506 if (!$ct || $ct eq 'application
/x-www-form-urlencoded' || $ct eq 'application/json
') {
1507 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1508 my ($hdl, $data) = @_;
1510 $self->handle_request($reqstate, $auth, $method, $path);
1513 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
1516 $self->handle_request($reqstate, $auth, $method, $path);
1518 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1519 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1520 ($state->{key}, $state->{val}) = ($1, $2);
1521 $self->unshift_read_header($reqstate, $state);
1522 } elsif ($line =~ /^\s+(.*)/) {
1523 $state->{val} .= " $1";
1524 $self->unshift_read_header($reqstate, $state);
1526 $self->error($reqstate, 506, "unable to parse request header
");
1533 sub push_request_header {
1534 my ($self, $reqstate) = @_;
1537 $reqstate->{hdl}->push_read(line => sub {
1538 my ($hdl, $line) = @_;
1541 # print "got request header
: $line\n" if $self->{debug};
1543 $reqstate->{keep_alive}--;
1545 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1546 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1549 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
1553 $self->{request_count}++; # only count valid request headers
1554 if ($self->{request_count} >= $self->{max_requests}) {
1555 $self->{end_loop} = 1;
1557 $reqstate->{log} = { requestline => $line };
1558 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
1559 $reqstate->{proto}->{maj} = $maj;
1560 $reqstate->{proto}->{min} = $min;
1561 $reqstate->{proto}->{ver} = $maj*1000+$min;
1562 $reqstate->{request} = HTTP::Request->new($method, $url);
1563 $reqstate->{starttime} = [gettimeofday],
1565 $self->unshift_read_header($reqstate);
1566 } elsif ($line eq '') {
1567 # ignore empty lines before requests (browser bugs?)
1568 $self->push_request_header($reqstate);
1570 $self->error($reqstate, 400, 'bad request');
1584 return if $self->{end_loop};
1586 # we need to m make sure that only one process calls accept
1587 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1588 next if $! == EINTR;
1589 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
1595 while (!$self->{end_loop} &&
1596 !defined($clientfh = $self->{socket}->accept()) &&
1599 if ($self->{end_loop}) {
1602 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1603 if (!defined($clientfh)) {
1604 $errmsg = "failed to
accept connection
: $!\n";
1610 flock($self->{lockfh}, Fcntl::LOCK_UN());
1612 if (!defined($clientfh)) {
1614 die $errmsg if $errmsg;
1617 fh_nonblocking $clientfh, 1;
1625 $self->{end_loop} = 1;
1627 undef $self->{socket_watch};
1629 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1631 if ($self->{conn_count} <= 0) {
1632 $self->{end_cond}->send(1);
1636 # fork and exit, so that parent starts a new worker
1641 # else we need to wait until all open connections gets closed
1642 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1644 # todo: test for active connections instead (we can abort idle connections)
1645 if ($self->{conn_count} <= 0) {
1647 $self->{end_cond}->send(1);
1655 sub check_host_access {
1656 my ($self, $clientip) = @_;
1658 $clientip = PVE::APIServer::Utils::normalize_v4_in_v6($clientip);
1659 my $cip = Net::IP->new($clientip);
1662 $self->dprint("client IP
not parsable
: $@");
1666 my $match_allow = 0;
1669 if ($self->{allow_from}) {
1670 foreach my $t (@{$self->{allow_from}}) {
1671 if ($t->overlaps($cip)) {
1673 $self->dprint("client IP allowed
: ". $t->prefix());
1679 if ($self->{deny_from}) {
1680 foreach my $t (@{$self->{deny_from}}) {
1681 if ($t->overlaps($cip)) {
1682 $self->dprint("client IP denied
: ". $t->prefix());
1689 if ($match_allow == $match_deny) {
1690 # match both allow and deny, or no match
1691 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1694 return $match_allow;
1697 sub accept_connections {
1700 my ($clientfh, $handle_creation);
1703 while ($clientfh = $self->accept()) {
1705 my $reqstate = { keep_alive => $self->{keep_alive} };
1707 # stop keep-alive when there are many open connections
1708 if ($self->{conn_count} + 1 >= $self->{max_conn_soft_limit}) {
1709 $reqstate->{keep_alive} = 0;
1712 if (my $sin = getpeername($clientfh)) {
1713 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1714 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1716 $self->dprint("getpeername failed
: $!");
1721 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1722 $self->dprint("ABORT request from
$reqstate->{peer_host
} - access denied
");
1723 $reqstate->{log}->{code} = 403;
1724 $self->log_request($reqstate);
1729 # Increment conn_count before creating new handle, since creation
1730 # triggers callbacks, which can potentialy decrement (e.g.
1731 # on_error) conn_count before AnyEvent::Handle->new() returns.
1732 $handle_creation = 1;
1733 $self->{conn_count}++;
1734 $reqstate->{hdl} = AnyEvent::Handle->new(
1736 rbuf_max => 64*1024,
1737 timeout => $self->{timeout},
1738 linger => 0, # avoid problems with ssh - really needed ?
1742 $self->log_aborted_request($reqstate);
1743 $self->client_do_disconnect($reqstate);
1745 if (my $err = $@) { syslog('err', $err); }
1748 my ($hdl, $fatal, $message) = @_;
1750 $self->log_aborted_request($reqstate, $message);
1751 $self->client_do_disconnect($reqstate);
1753 if (my $err = $@) { syslog('err', "$err"); }
1755 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1756 $handle_creation = 0;
1758 $self->dprint("ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}");
1760 $self->push_request_header($reqstate);
1765 syslog('err', $err);
1766 $self->dprint("connection
accept error
: $err");
1768 if ($handle_creation) {
1769 if ($self->{conn_count} <= 0) {
1770 warn "connection count
<= 0 not decrementing
!\n";
1772 $self->{conn_count}--;
1775 $self->{end_loop} = 1;
1778 $self->wait_end_loop() if $self->{end_loop};
1781 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1782 # because we write from multiple processes, and that would arbitrarily mix output
1784 sub open_access_log {
1785 my ($self, $filename) = @_;
1787 my $old_mask = umask(0137);;
1788 my $logfh = IO::File->new($filename, ">>") ||
1789 die "unable to
open log file
'$filename' - $!\n";
1792 $logfh->autoflush(1);
1794 $self->{logfh} = $logfh;
1798 my ($self, $data) = @_;
1800 return if !defined($self->{logfh}) || !$data;
1802 my $res = $self->{logfh}->print($data);
1805 delete $self->{logfh};
1806 syslog('err', "error writing access
log");
1807 $self->{end_loop} = 1; # terminate asap
1811 sub atfork_handler {
1815 # something else do to ?
1816 close($self->{socket});
1824 $self->{end_cond}->recv;
1828 my ($this, %args) = @_;
1830 my $class = ref($this) || $this;
1832 foreach my $req (qw(socket lockfh lockfile)) {
1833 die "misssing required argument '$req'" if !defined($args{$req});
1836 my $self = bless { %args }, $class;
1838 $self->{cookie_name
} //= 'PVEAuthCookie';
1839 $self->{apitoken_name
} //= 'PVEAPIToken';
1840 $self->{base_uri
} //= "/api2";
1841 $self->{dirs
} //= {};
1842 $self->{title
} //= 'API Inspector';
1843 $self->{compression
} //= 1;
1845 # formatter_config: we pass some configuration values to the Formatter
1846 $self->{formatter_config
} = {};
1847 foreach my $p (qw(apitoken_name cookie_name base_uri title)) {
1848 $self->{formatter_config
}->{$p} = $self->{$p};
1850 $self->{formatter_config
}->{csrfgen_func
} =
1851 $self->can('generate_csrf_prevention_token');
1853 # add default dirs which includes jquery and bootstrap
1854 my $jsbase = '/usr/share/javascript';
1855 add_dirs
($self->{dirs
}, '/js/' => "$jsbase/");
1856 # libjs-bootstrap uses symlinks for this, which we do not want to allow..
1857 my $glyphicons = '/usr/share/fonts/truetype/glyphicons/';
1858 add_dirs
($self->{dirs
}, '/js/bootstrap/fonts/' => "$glyphicons");
1861 PVE
::INotify
::inotify_init
();
1863 fh_nonblocking
($self->{socket}, 1);
1865 $self->{end_loop
} = 0;
1866 $self->{conn_count
} = 0;
1867 $self->{request_count
} = 0;
1868 $self->{timeout
} = 5 if !$self->{timeout
};
1869 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1870 $self->{max_conn
} = 800 if !$self->{max_conn
};
1871 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1873 $self->{policy
} = 'allow' if !$self->{policy
};
1875 $self->{end_cond
} = AnyEvent-
>condvar;
1878 my $ssl_defaults = {
1879 # Note: older versions are considered insecure, for example
1880 # search for "Poodle"-Attack
1884 cipher_list
=> 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256',
1885 honor_cipher_order
=> 1,
1888 foreach my $k (keys %$ssl_defaults) {
1889 $self->{ssl
}->{$k} //= $ssl_defaults->{$k};
1892 if (!defined($self->{ssl
}->{dh_file
})) {
1893 $self->{ssl
}->{dh
} = 'skip2048';
1896 my $tls_ctx_flags = 0;
1897 $tls_ctx_flags |= &Net
::SSLeay
::OP_NO_COMPRESSION
;
1898 $tls_ctx_flags |= &Net
::SSLeay
::OP_SINGLE_ECDH_USE
;
1899 $tls_ctx_flags |= &Net
::SSLeay
::OP_SINGLE_DH_USE
;
1900 $tls_ctx_flags |= &Net
::SSLeay
::OP_NO_RENEGOTIATION
;
1901 if (delete $self->{ssl
}->{honor_cipher_order
}) {
1902 $tls_ctx_flags |= &Net
::SSLeay
::OP_CIPHER_SERVER_PREFERENCE
;
1905 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
1906 Net
::SSLeay
::CTX_set_options
($self->{tls_ctx
}->{ctx
}, $tls_ctx_flags);
1909 if ($self->{spiceproxy
}) {
1910 $known_methods = { CONNECT
=> 1 };
1913 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
1915 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
1917 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
1919 if ($self->{conn_count
} >= $self->{max_conn
}) {
1920 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
1921 if ($self->{conn_count
} < $self->{max_conn
}) {
1923 $self->accept_connections();
1927 $self->accept_connections();
1933 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
1934 undef $self->{term_watch
};
1935 $self->wait_end_loop();
1938 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
1939 undef $self->{quit_watch
};
1940 $self->wait_end_loop();
1943 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
1944 PVE
::INotify
::poll
(); # read inotify events
1950 # static helper to add directory including all subdirs
1951 # This can be used to setup $self->{dirs}
1953 my ($result_hash, $alias, $subdir) = @_;
1955 $result_hash->{$alias} = $subdir;
1958 my $dir = $File::Find
::dir
;
1959 if ($dir =~m!^$subdir(.*)$!) {
1960 my $name = "$alias$1/";
1961 $result_hash->{$name} = "$dir/";
1965 find
({wanted
=> $wanted, follow
=> 0, no_chdir
=> 1}, $subdir);
1968 # abstract functions - subclass should overwrite/implement them
1970 sub verify_spice_connect_url
{
1971 my ($self, $connect_str) = @_;
1975 #return ($vmid, $node, $port);
1978 # formatters can call this when the generate a new page
1979 sub generate_csrf_prevention_token
{
1980 my ($username) = @_;
1982 return undef; # do nothing by default
1986 my ($self, $method, $rel_uri, $ticket, $token, $api_token, $peer_host) = @_;
1991 # ticket => $ticket,
1993 # userid => $username,
1995 # isUpload => $isUpload,
1996 # api_token => $api_token,
2001 my ($self, $clientip, $method, $rel_uri, $auth, $params, $format) = @_;
2003 # please do not raise exceptions here (always return a result).
2006 status
=> HTTP_NOT_IMPLEMENTED
,
2007 message
=> "Method '$method $rel_uri' not implemented",
2010 # this should return the following properties, which
2011 # are then passed to the Formatter
2013 # status: HTTP status code
2014 # message: Error message
2015 # errors: more detailed error hash (per parameter)
2016 # info: reference to JSON schema definition - useful to format output
2019 # total: additional info passed to output
2020 # changes: additional info passed to output
2022 # if you want to proxy the request to another node return this
2023 # { proxy => $remip, proxynode => $node, proxy_params => $params };
2025 # to pass the request to the local priviledged daemon use:
2026 # { proxy => 'localhost' , proxy_params => $params };
2028 # to download aspecific file use:
2029 # { download => "/path/to/file" };
2032 sub check_cert_fingerprint
{
2033 my ($self, $cert) = @_;
2038 sub initialize_cert_cache
{
2039 my ($self, $node) = @_;
2044 sub remote_node_ip
{
2045 my ($self, $node) = @_;