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();
16 # use AnyEvent::Strict; # only use this for debugging
18 use AnyEvent
::Util
qw(guard fh_nonblocking WSAEWOULDBLOCK WSAEINPROGRESS);
31 use POSIX
qw(strftime EINTR EAGAIN);
32 use Socket
qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
33 use Time
::HiRes
qw(usleep ualarm gettimeofday tv_interval);
35 #use Data::Dumper; # FIXME: remove, just use: print to_json([$var], {pretty => 1}) ."\n";
40 use HTTP
::Status
qw(:constants);
48 use PVE
::Tools
qw(trim);
50 use PVE
::APIServer
::Formatter
;
51 use PVE
::APIServer
::Utils
;
53 my $limit_max_headers = 64;
54 my $limit_max_header_size = 8*1024;
55 my $limit_max_post = 64*1024;
64 my $split_abs_uri = sub {
65 my ($abs_uri, $base_uri) = @_;
67 my ($format, $rel_uri) = $abs_uri =~ m/^\Q$base_uri\E\/+([a-z
][a-z0-9
]+)(\
/.*)?$/;
68 $rel_uri = '/' if !$rel_uri;
70 return wantarray ?
($rel_uri, $format) : $rel_uri;
74 my ($self, $message) = @_;
76 return if !$self->{debug
};
78 my ($pkg, $pkgfile, $line, $sub) = caller(1);
79 $sub =~ s/^(?:.+::)+//;
80 print "worker[$$]: $pkg +$line: $sub: $message\n";
84 my ($self, $reqstate) = @_;
86 my $loginfo = $reqstate->{log};
88 # like apache2 common log format
89 # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
91 return if $loginfo->{written
}; # avoid duplicate logs
92 $loginfo->{written
} = 1;
94 my $peerip = $reqstate->{peer_host
} || '-';
95 my $userid = $loginfo->{userid
} || '-';
96 my $content_length = defined($loginfo->{content_length
}) ?
$loginfo->{content_length
} : '-';
97 my $code = $loginfo->{code
} || 500;
98 my $requestline = $loginfo->{requestline
} || '-';
99 my $timestr = strftime
("%d/%m/%Y:%H:%M:%S %z", localtime());
101 my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n";
103 $self->write_log($msg);
106 sub log_aborted_request {
107 my ($self, $reqstate, $error) = @_;
109 my $r = $reqstate->{request};
110 return if !$r; # no active request
113 syslog("err
", "problem with client
$reqstate->{peer_host
}; $error");
116 $self->log_request($reqstate);
119 sub cleanup_reqstate {
120 my ($reqstate, $deletetmpfile) = @_;
122 delete $reqstate->{log};
123 delete $reqstate->{request};
124 delete $reqstate->{proto};
125 delete $reqstate->{accept_gzip};
126 delete $reqstate->{accept_deflate};
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} && !$reqstate->{accept_deflate};
294 my $code = $resp->code;
295 my $msg = $resp->message || HTTP::Status::status_message($code);
296 my $content = $resp->content;
298 # multiline mode only checks \n for $, so explicitly check for any \n or \r afterwards
299 ($msg) = $msg =~ m/^(.*)$/m;
300 if ($msg =~ /[\r\n]/) {
301 $code = 400; # bad request from user
302 $msg = HTTP::Status::status_message($code);
306 if ($code =~ /^(1\d\d|[23]04)$/) {
307 # make sure informational, no content and not modified response send no content
311 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
313 $reqstate->{log}->{code} = $code;
315 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
316 my $res = "$proto $code $msg\015\012";
319 my $date = HTTP::Date::time2str($ctime);
320 $resp->header('Date' => $date);
322 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
324 $resp->header('Expires' => $date);
325 $resp->header('Cache-Control' => "max-age
=0");
326 $resp->header("Pragma
", "no-cache
");
329 $resp->header('Server' => "pve-api-daemon
/3.0");
332 if ($content && !$stream_fh) {
334 $content_length = length($content);
336 if (!$nocomp && ($content_length > 1024)) {
337 if ($reqstate->{accept_gzip}) {
338 my $comp = Compress::Zlib::memGzip($content);
339 $resp->header('Content-Encoding', 'gzip');
341 } elsif ($reqstate->{accept_deflate}) {
342 my $comp = Compress::Zlib::compress($content);
343 $resp->header('Content-Encoding', 'deflate');
347 $content_length = length($content);
348 $resp->header("Content-Length
" => $content_length);
349 $reqstate->{log}->{content_length} = $content_length;
352 $resp->remove_header("Content-Length
");
355 if ($reqstate->{keep_alive} > 0) {
356 $resp->push_header('Connection' => 'Keep-Alive');
358 $resp->header('Connection' => 'close');
361 $res .= $resp->headers_as_string("\015\012");
362 #print "SEND
(without content
) $res\n" if $self->{debug};
365 $res .= $content if $content && !$stream_fh;
367 $self->log_request($reqstate, $reqstate->{request});
370 # write headers and preamble...
371 $reqstate->{hdl}->push_write($res);
372 # ...then stream data via an AnyEvent::Handle
373 $self->response_stream($reqstate, $stream_fh);
374 } elsif ($delay && $delay > 0) {
375 my $w; $w = AnyEvent->timer(after => $delay, cb => sub {
376 undef $w; # delete reference
377 return if !$reqstate->{hdl}; # already disconnected
378 $reqstate->{hdl}->push_write($res);
379 $self->finish_response($reqstate);
382 $reqstate->{hdl}->push_write($res);
383 $self->finish_response($reqstate);
388 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
391 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
392 $self->response($reqstate, $resp);
397 my $file_extension_info = {
398 css => { ct => 'text/css' },
399 html => { ct => 'text/html' },
400 js => { ct => 'application/javascript' },
401 json => { ct => 'application/json' },
402 map => { ct => 'application/json' },
403 png => { ct => 'image/png' , nocomp => 1 },
404 ico => { ct => 'image/x-icon', nocomp => 1},
405 gif => { ct => 'image/gif', nocomp => 1},
406 svg => { ct => 'image/svg+xml' },
407 jar => { ct => 'application/java-archive', nocomp => 1},
408 woff => { ct => 'application/font-woff', nocomp => 1},
409 woff2 => { ct => 'application/font-woff2', nocomp => 1},
410 ttf => { ct => 'application/font-snft', nocomp => 1},
411 pdf => { ct => 'application/pdf', nocomp => 1},
412 epub => { ct => 'application/epub+zip', nocomp => 1},
413 mp3 => { ct => 'audio/mpeg', nocomp => 1},
414 oga => { ct => 'audio/ogg', nocomp => 1},
415 tgz => { ct => 'application/x-compressed-tar', nocomp => 1},
418 sub send_file_start {
419 my ($self, $reqstate, $download) = @_;
422 # print "SEND FILE
$filename\n";
423 # Note: aio_load() this is not really async unless we use IO::AIO!
426 my $r = $reqstate->{request};
432 if (ref($download) eq 'HASH') {
433 $mime = $download->{'content-type'};
434 my $encoding = $download->{'content-encoding'};
435 my $disposition = $download->{'content-disposition'};
437 if ($download->{path} && $download->{stream} &&
438 $reqstate->{request}->header('PVEDisableProxy'))
440 # avoid double stream from a file, let the proxy handle it
441 die "internal error
: file proxy streaming only available
for pvedaemon
\n"
442 if !$self->{trusted_env};
443 my $header = HTTP::Headers->new(
444 pvestreamfile => $download->{path},
445 Content_Type => $mime,
447 $header->header('Content-Encoding' => $encoding) if defined($encoding);
448 $header->header('Content-Disposition' => $disposition) if defined($disposition);
449 # we need some data so Content-Length gets set correctly and
450 # the proxy doesn't wait for more data - place a canary
451 my $resp = HTTP::Response->new(200, "OK
", $header, "error canary
");
452 $self->response($reqstate, $resp);
456 if (!($fh = $download->{fh})) {
457 my $path = $download->{path};
458 die "internal error
: {download
} returned but neither fh
not path
given\n"
460 sysopen($fh, "$path", O_NONBLOCK | O_RDONLY)
461 or die "open stream path
'$path' for reading failed
: $!\n";
464 if ($download->{stream}) {
465 my $header = HTTP::Headers->new(Content_Type => $mime);
466 $header->header('Content-Encoding' => $encoding) if defined($encoding);
467 $header->header('Content-Disposition' => $disposition) if defined($disposition);
468 my $resp = HTTP::Response->new(200, "OK
", $header);
469 $self->response($reqstate, $resp, undef, 1, 0, $fh);
473 my $filename = $download;
474 $fh = IO::File->new($filename, '<') ||
475 die "unable to
open file
'$filename' - $!\n";
477 my ($ext) = $filename =~ m/\.([^.]*)$/;
478 my $ext_info = $file_extension_info->{$ext};
480 die "unable to detect content type
" if !$ext_info;
481 $mime = $ext_info->{ct};
482 $nocomp = $ext_info->{nocomp};
485 my $stat = File::stat::stat($fh) ||
488 my $mtime = $stat->mtime;
490 if (my $ifmod = $r->header('if-modified-since')) {
491 my $iftime = HTTP::Date::str2time($ifmod);
492 if ($mtime <= $iftime) {
493 my $resp = HTTP::Response->new(304, "NOT MODIFIED
");
494 $self->response($reqstate, $resp, $mtime);
500 my $len = sysread($fh, $data, $stat->size);
501 die "got short file
\n" if !defined($len) || $len != $stat->size;
503 my $header = HTTP::Headers->new(Content_Type => $mime);
504 my $resp = HTTP::Response->new(200, "OK
", $header, $data);
505 $self->response($reqstate, $resp, $mtime, $nocomp);
508 $self->error($reqstate, 501, $err);
515 sub websocket_proxy {
516 my ($self, $reqstate, $wsaccept, $wsproto, $param) = @_;
522 my $max_payload_size = 128*1024;
524 if ($param->{port}) {
525 $remhost = 'localhost';
526 $remport = $param->{port};
527 } elsif ($param->{socket}) {
529 $remport = $param->{socket};
531 die "websocket_proxy
: missing port
or socket\n";
535 my ($data, $opcode) = @_;
540 $string = $opcode ? $opcode : "\x82"; # binary frame
543 my $payload_len = length($payload);
544 if ($payload_len <= 125) {
545 $string .= pack 'C', $payload_len;
546 } elsif ($payload_len <= 0xffff) {
547 $string .= pack 'C', 126;
548 $string .= pack 'n', $payload_len;
550 $string .= pack 'C', 127;
551 $string .= pack 'Q>', $payload_len;
557 tcp_connect $remhost, $remport, sub {
559 or die "connect to
'$remhost:$remport' failed
: $!";
561 $self->dprint("CONNECTed to
'$remhost:$remport'");
563 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
565 rbuf_max => $max_payload_size,
566 wbuf_max => $max_payload_size*5,
571 $self->log_aborted_request($reqstate);
572 $self->client_do_disconnect($reqstate);
574 if (my $err = $@) { syslog('err', $err); }
577 my ($hdl, $fatal, $message) = @_;
579 $self->log_aborted_request($reqstate, $message);
580 $self->client_do_disconnect($reqstate);
582 if (my $err = $@) { syslog('err', "$err"); }
585 my $proxyhdlreader = sub {
588 my $len = length($hdl->{rbuf});
589 my $data = substr($hdl->{rbuf}, 0, $len > $max_payload_size ? $max_payload_size : $len, '');
591 my $string = $encode->(\$data);
593 $reqstate->{hdl}->push_write($string) if $reqstate->{hdl};
596 my $hdlreader = sub {
599 while (my $len = length($hdl->{rbuf})) {
602 my $hdr = unpack('C', substr($hdl->{rbuf}, 0, 1));
603 my $opcode = $hdr & 0b00001111;
604 my $fin = $hdr & 0b10000000;
606 die "received fragmented websocket frame
\n" if !$fin;
608 my $rsv = $hdr & 0b01110000;
609 die "received websocket frame with RSV flags
\n" if $rsv;
611 my $payload_len = unpack 'C', substr($hdl->{rbuf}, 1, 1);
613 my $masked = $payload_len & 0b10000000;
614 die "received unmasked websocket frame from client
\n" if !$masked;
617 $payload_len = $payload_len & 0b01111111;
618 if ($payload_len == 126) {
620 $payload_len = unpack('n', substr($hdl->{rbuf}, $offset, 2));
622 } elsif ($payload_len == 127) {
624 $payload_len = unpack('Q>', substr($hdl->{rbuf}, $offset, 8));
628 die "received too large websocket frame
(len
= $payload_len)\n"
629 if ($payload_len > $max_payload_size) || ($payload_len < 0);
631 return if $len < ($offset + 4 + $payload_len);
633 my $data = substr($hdl->{rbuf}, 0, $offset + 4 + $payload_len, ''); # now consume data
635 my $mask = substr($data, $offset, 4);
638 my $payload = substr($data, $offset, $payload_len);
640 # NULL-mask might be used over TLS, skip to increase performance
641 if ($mask ne pack('N', 0)) {
642 # repeat 4 byte mask to payload length + up to 4 byte
643 $mask = $mask x (int($payload_len / 4) + 1);
644 # truncate mask to payload length
645 substr($mask, $payload_len) = "";
650 if ($opcode == 1 || $opcode == 2) {
651 $reqstate->{proxyhdl}->push_write($payload) if $reqstate->{proxyhdl};
652 } elsif ($opcode == 8) {
653 my $statuscode = unpack ("n
", $payload);
654 $self->dprint("websocket received
close. status code
: '$statuscode'");
655 if (my $proxyhdl = $reqstate->{proxyhdl}) {
656 $proxyhdl->{block_disconnect} = 1 if length $proxyhdl->{wbuf};
658 $proxyhdl->push_shutdown();
660 $hdl->push_shutdown();
661 } elsif ($opcode == 9) {
662 # ping received, schedule pong
663 $reqstate->{hdl}->push_write($encode->(\$payload, "\x8A")) if $reqstate->{hdl};
664 } elsif ($opcode == 0xA) {
665 # pong received, continue
667 die "received unhandled websocket opcode
$opcode\n";
672 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.1';
674 $reqstate->{proxyhdl}->timeout(0);
675 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
676 $reqstate->{hdl}->on_read($hdlreader);
678 # todo: use stop_read/start_read if write buffer grows to much
680 # FIXME: remove protocol in PVE/PMG 8.x
682 # for backwards, compatibility, we have to reply with the websocket
683 # subprotocol from the request
684 my $res = "$proto 101 Switching Protocols
\015\012" .
685 "Upgrade
: websocket
\015\012" .
686 "Connection
: upgrade
\015\012" .
687 "Sec-WebSocket-Accept
: $wsaccept\015\012" .
688 ($wsproto ne "" ? "Sec-WebSocket-Protocol
: $wsproto\015\012" : "") .
693 $reqstate->{hdl}->push_write($res);
696 $reqstate->{log}->{code} = 101;
697 $self->log_request($reqstate);
703 $self->log_aborted_request($reqstate, $err);
704 $self->client_do_disconnect($reqstate);
709 my ($self, $reqstate, $clientip, $host, $node, $method, $uri, $auth, $params) = @_;
715 # stringify URI object and verify it starts with a slash
718 $self->error($reqstate, 400, "invalid proxy uri
");
723 if ($host eq 'localhost') {
724 $target = "http
://$host:85$uri";
725 # keep alive for localhost is not worth (connection setup is about 0.2ms)
727 $may_stream_file = 1;
728 } elsif (Net::IP::ip_is_ipv6($host)) {
729 $target = "https
://[$host]:8006$uri";
731 $target = "https
://$host:8006$uri";
735 PVEDisableProxy => 'true',
736 PVEClientIP => $clientip,
739 $headers->{'cookie'} = PVE::APIServer::Formatter::create_auth_cookie($auth->{ticket}, $self->{cookie_name})
741 $headers->{'Authorization'} = PVE::APIServer::Formatter::create_auth_header($auth->{api_token}, $self->{apitoken_name})
742 if $auth->{api_token};
743 $headers->{'CSRFPreventionToken'} = $auth->{token}
745 if ($self->{compression}) {
746 if ($reqstate->{accept_deflate} && $reqstate->{accept_gzip}) {
747 $headers->{'Accept-Encoding'} = 'gzip, deflate';
748 } elsif ($reqstate->{accept_gzip}) {
749 $headers->{'Accept-Encoding'} = 'gzip';
750 } elsif ($reqstate->{accept_deflate}) {
751 $headers->{'Accept-Encoding'} = 'deflate';
755 if (defined(my $host = $reqstate->{request}->header('Host'))) {
756 $headers->{Host} = $host;
761 if ($method eq 'POST' || $method eq 'PUT') {
762 my $request_ct = $reqstate->{request}->header('Content-Type');
763 if (defined($request_ct) && $request_ct =~ 'application/json') {
764 $headers->{'Content-Type'} = 'application/json';
765 $content = encode_json($params);
767 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
768 # use URI object to format application/x-www-form-urlencoded content.
769 my $url = URI->new('http:');
770 $url->query_form(%$params);
771 $content = $url->query;
773 if (defined($content)) {
774 $headers->{'Content-Length'} = length($content);
779 # TLS 1.x only, with certificate pinning
784 ca_path => '/usr/lib/ssl/certs', # to avoid loading the combined CA cert file
786 my (undef, undef, undef, $depth, undef, undef, $cert) = @_;
787 # we don't care about intermediate or root certificates
788 return 1 if $depth != 0;
789 # check server certificate against cache of pinned FPs
790 return $self->check_cert_fingerprint($cert);
794 # load and cache cert fingerprint if first time we proxy to this node
795 $self->initialize_cert_cache($node);
797 my $w; $w = http_request(
802 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
803 keepalive => $keep_alive,
805 tls_ctx => AnyEvent::TLS->new(%{$tls}),
807 my ($body, $hdr) = @_;
811 if (!$reqstate->{hdl}) {
812 warn "proxy detected vanished client connection
\n";
817 my $code = delete $hdr->{Status};
818 my $msg = delete $hdr->{Reason};
819 my $stream = delete $hdr->{pvestreamfile};
821 delete $hdr->{HTTPVersion};
822 my $header = HTTP::Headers->new(%$hdr);
823 if (my $location = $header->header('Location')) {
824 $location =~ s|^http://localhost:85||;
825 $header->header(Location => $location);
828 if (!$may_stream_file) {
829 $self->error($reqstate, 403, 'streaming denied');
832 sysopen(my $fh, "$stream", O_NONBLOCK | O_RDONLY)
833 or die "open stream path
'$stream' for forwarding failed
: $!\n";
834 my $resp = HTTP::Response->new($code, $msg, $header, undef);
835 $self->response($reqstate, $resp, undef, 1, 0, $fh);
837 my $resp = HTTP::Response->new($code, $msg, $header, $body);
838 # Note: disable compression, because body is already compressed
839 $self->response($reqstate, $resp, undef, 1);
848 # return arrays as \0 separated strings (like CGI.pm)
849 # assume data is UTF8 encoded
850 sub decode_urlencoded {
855 return $res if !$data;
857 foreach my $kv (split(/[\&\;]/, $data)) {
858 my ($k, $v) = split(/=/, $kv);
860 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
864 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
866 $v = Encode::decode('utf8', $v);
868 if (defined(my $old = $res->{$k})) {
869 if (ref($old) eq 'ARRAY') {
884 my ($r, $method) = @_;
888 if ($method eq 'PUT' || $method eq 'POST') {
890 if (my $ctype = $r->header('Content-Type')) {
891 $ct = parse_content_type($ctype);
893 if (defined($ct) && $ct eq 'application/json') {
894 $params = decode_json($r->content);
896 $params = decode_urlencoded($r->content);
900 my $query_params = decode_urlencoded($r->url->query());
902 foreach my $k (keys %{$query_params}) {
903 $params->{$k} = $query_params->{$k};
909 sub handle_api2_request {
910 my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
913 my $r = $reqstate->{request};
915 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
917 my $formatter = PVE::APIServer::Formatter::get_formatter($format, $method, $rel_uri);
919 if (!defined($formatter)) {
920 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no formatter
for uri
$rel_uri, $format");
924 #print Dumper($upload_state) if $upload_state;
929 $params = $upload_state->{params};
931 $params = extract_params($r, $method);
934 delete $params->{_dc} if $params; # remove disable cache parameter
936 my $clientip = $reqstate->{peer_host};
938 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
941 Net::SSLeay::ERR_clear_error();
943 AnyEvent->now_update(); # in case somebody called sleep()
945 my $upgrade = $r->header('upgrade');
946 $upgrade = lc($upgrade) if $upgrade;
948 if (my $host = $res->{proxy}) {
950 if ($self->{trusted_env}) {
951 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
955 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
956 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
960 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
962 $self->proxy_request(
963 $reqstate, $clientip, $host, $res->{proxynode}, $method, $r->uri, $auth, $res->{proxy_params});
966 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
967 die "unable to upgrade to protocol
'$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
968 my $wsver = $r->header('sec-websocket-version');
969 die "unsupported websocket-version
'$wsver'\n" if !$wsver || ($wsver ne '13');
970 my $wsproto = $r->header('sec-websocket-protocol') // "";
971 my $wskey = $r->header('sec-websocket-key');
972 die "missing websocket-key
\n" if !$wskey;
973 # Note: Digest::SHA::sha1_base64 has wrong padding
974 my $wsaccept = Digest::SHA::sha1_base64("${wskey
}258EAFA5-E914-47DA-95CA-C5AB0DC85B11
") . "=";
975 if ($res->{status} == HTTP_OK) {
976 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
982 if ($res->{status} == HTTP_UNAUTHORIZED) {
983 # always delay unauthorized calls by 3 seconds
984 $delay = 3 - tv_interval($reqstate->{starttime});
985 $delay = 0 if $delay < 0;
988 my $download = $res->{download};
989 $download //= $res->{data}->{download}
990 if defined($res->{data}) && ref($res->{data}) eq 'HASH';
991 if (defined($download)) {
992 send_file_start($self, $reqstate, $download);
996 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
997 $auth, $self->{formatter_config});
1000 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1003 $resp = HTTP::Response->new($res->{status}, $res->{message});
1004 $resp->header("Content-Type
" => $ct);
1005 $resp->content($raw);
1007 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1010 $self->error($reqstate, 501, $err);
1014 sub handle_spice_proxy_request {
1015 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
1019 my ($minport, $maxport) = PVE::Tools::spice_port_range();
1020 if ($spiceport < $minport || $spiceport > $maxport) {
1021 die "SPICE Port
$spiceport is not in allowed range
($minport, $maxport)\n";
1024 my $clientip = $reqstate->{peer_host};
1025 my $r = $reqstate->{request};
1029 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
1030 $remip = $self->remote_node_ip($node);
1031 $self->dprint("REMOTE CONNECT
$vmid, $remip, $connect_str");
1033 $self->dprint("CONNECT
$vmid, $node, $spiceport");
1036 if ($remip && $r->header('PVEDisableProxy')) {
1037 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
1041 $reqstate->{hdl}->timeout(0);
1042 $reqstate->{hdl}->wbuf_max(64*10*1024);
1044 my $remhost = $remip ? $remip : "localhost
";
1045 my $remport = $remip ? 3128 : $spiceport;
1047 tcp_connect $remhost, $remport, sub {
1049 or die "connect to
'$remhost:$remport' failed
: $!";
1051 $self->dprint("CONNECTed to
'$remhost:$remport'");
1052 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
1054 rbuf_max => 64*1024,
1055 wbuf_max => 64*10*1024,
1060 $self->log_aborted_request($reqstate);
1061 $self->client_do_disconnect($reqstate);
1063 if (my $err = $@) { syslog('err', $err); }
1066 my ($hdl, $fatal, $message) = @_;
1068 $self->log_aborted_request($reqstate, $message);
1069 $self->client_do_disconnect($reqstate);
1071 if (my $err = $@) { syslog('err', "$err"); }
1075 my $proxyhdlreader = sub {
1078 my $len = length($hdl->{rbuf});
1079 my $data = substr($hdl->{rbuf}, 0, $len, '');
1081 #print "READ1
$len\n";
1082 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
1085 my $hdlreader = sub {
1088 my $len = length($hdl->{rbuf});
1089 my $data = substr($hdl->{rbuf}, 0, $len, '');
1091 #print "READ0
$len\n";
1092 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
1095 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
1097 my $startproxy = sub {
1098 $reqstate->{proxyhdl}->timeout(0);
1099 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
1100 $reqstate->{hdl}->on_read($hdlreader);
1102 # todo: use stop_read/start_read if write buffer grows to much
1104 # a response must be followed by an empty line
1105 my $res = "$proto 200 OK
\015\012\015\012";
1106 $reqstate->{hdl}->push_write($res);
1109 $reqstate->{log}->{code} = 200;
1110 $self->log_request($reqstate);
1114 my $header = "CONNECT
${connect_str
} $proto\015\012" .
1115 "Host
: ${connect_str
}\015\012" .
1116 "Proxy-Connection
: keep-alive
\015\012" .
1117 "User-Agent
: spiceproxy
\015\012" .
1118 "PVEDisableProxy
: true
\015\012" .
1119 "PVEClientIP
: $clientip\015\012" .
1122 $reqstate->{proxyhdl}->push_write($header);
1123 $reqstate->{proxyhdl}->push_read(line => sub {
1124 my ($hdl, $line) = @_;
1126 if ($line =~ m!^$proto 200 OK$!) {
1127 # read the empty line after the 200 OK
1128 $reqstate->{proxyhdl}->unshift_read(line => sub{
1132 $reqstate->{hdl}->push_write($line);
1133 $self->client_do_disconnect($reqstate);
1144 $self->log_aborted_request($reqstate, $err);
1145 $self->client_do_disconnect($reqstate);
1149 sub handle_request {
1150 my ($self, $reqstate, $auth, $method, $path) = @_;
1152 my $base_uri = $self->{base_uri};
1155 my $r = $reqstate->{request};
1157 # disable timeout on handle (we already have all data we need)
1158 # we re-enable timeout in response()
1159 $reqstate->{hdl}->timeout(0);
1161 if ($path =~ m/^\Q$base_uri\E/) {
1162 $self->handle_api2_request($reqstate, $auth, $method, $path);
1166 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
1167 if (ref($handler) eq 'CODE') {
1168 my $params = decode_urlencoded($r->url->query());
1169 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
1171 Net::SSLeay::ERR_clear_error();
1172 $self->response($reqstate, $resp);
1173 } elsif (ref($handler) eq 'HASH') {
1174 if (my $filename = $handler->{file}) {
1175 my $fh = IO::File->new($filename) ||
1176 die "unable to
open file
'$filename' - $!\n";
1177 send_file_start($self, $reqstate, $filename);
1179 die "internal error
- no handler
";
1182 die "internal error
- no handler
";
1187 if ($self->{dirs} && ($method eq 'GET')) {
1188 # we only allow simple names
1189 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
1190 my ($subdir, $file) = ($1, $2);
1191 if (my $dir = $self->{dirs}->{$subdir}) {
1192 my $filename = "$dir$file";
1193 my $fh = IO::File->new($filename) ||
1194 die "unable to
open file
'$filename' - $!\n";
1195 send_file_start($self, $reqstate, $filename);
1201 die "no such file
'$path'\n";
1204 $self->error($reqstate, 501, $err);
1208 my sub assert_form_disposition {
1209 die "wrong Content-Disposition
'$_[0]' in multipart
, expected
'form-data'\n" if $_[0] ne 'form-data';
1212 sub file_upload_multipart {
1213 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
1216 my $boundary = $rstate->{boundary};
1217 my $hdl = $reqstate->{hdl};
1218 my $startlen = length($hdl->{rbuf});
1220 my $newline_re = qr/\015?\012/;
1221 my $delim_re = qr/--\Q$boundary\E${newline_re}/;
1222 my $close_delim_re = qr/--\Q$boundary\E--/;
1224 # Phase 0 - preserve boundary, but remove everything before
1225 if ($rstate->{phase} == 0 && $hdl->{rbuf} =~ s/^.*?($delim_re)/$1/s) {
1226 $rstate->{read} += $startlen - length($hdl->{rbuf});
1227 $rstate->{phase} = 1;
1230 my $remove_until_data = sub {
1232 # remove any remaining multipart "headers
" like Content-Type
1233 $hdl->{rbuf} =~ s/^.*?${newline_re}{2}//s;
1236 my $extract_form_disposition = sub {
1238 if ($hdl->{rbuf} =~ s/^${delim_re}.*?Content-Disposition: (.*?); name="$name"(.*?${delim_re})/$2/s) {
1239 assert_form_disposition($1);
1240 $remove_until_data->($hdl);
1241 $hdl->{rbuf} =~ s/^(.*?)(${delim_re})/$2/s;
1242 $rstate->{params}->{$name} = trim($1);
1246 if ($rstate->{phase} == 1) { # Phase 1 - parse payload without file data
1247 $extract_form_disposition->('content');
1248 $extract_form_disposition->('checksum-algorithm');
1249 $extract_form_disposition->('checksum');
1251 if ($hdl->{rbuf} =~ s/^${delim_re}Content-Disposition: (.*?); name="(.*?)"; filename="([^"]+)"//s) {
1252 assert_form_disposition($1);
1253 die "wrong field name
'$2' for file upload
, expected
'filename'" if $2 ne "filename
";
1254 $rstate->{phase} = 2;
1255 $rstate->{params}->{filename} = trim($3);
1256 $remove_until_data->($hdl); # any remaining multipart "headers
" like Content-Type
1260 if ($rstate->{phase} == 2) { # Phase 2 - dump content into file
1261 my ($data, $write_length);
1262 if ($hdl->{rbuf} =~ s/^(.*?)${newline_re}?+${close_delim_re}.*$//s) {
1264 $write_length = length($data);
1265 $rstate->{phase} = 100;
1267 $write_length = length($hdl->{rbuf}) - $rstate->{boundlen};
1268 $data = substr($hdl->{rbuf}, 0, $write_length, '') if $write_length > 0;
1271 if ($write_length > 0) {
1272 syswrite($rstate->{outfh}, $data) == $write_length or die "write to temporary file failed
- $!\n";
1273 $rstate->{bytes} += $write_length;
1277 if ($rstate->{phase} == 100) { # Phase 100 - transfer finished
1278 my $elapsed = tv_interval($rstate->{starttime});
1279 syslog('info', "multipart upload complete
(size
: %dB time: %.3fs rate
: %.2fMiB
/s filename
: %s)",
1280 $rstate->{bytes}, $elapsed, $rstate->{bytes} / ($elapsed * 1024 * 1024),
1281 $rstate->{params}->{filename}
1283 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1286 $rstate->{read} += $startlen - length($hdl->{rbuf});
1288 if ($rstate->{read} + length($hdl->{rbuf}) >= $rstate->{size} && $rstate->{phase} != 100) {
1289 die "upload failed
";
1293 syslog('err', $err);
1294 $self->error($reqstate, 501, $err);
1298 sub parse_content_type {
1301 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
1303 foreach my $v (@params) {
1304 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1305 return wantarray ? ($ct, $1) : $ct;
1309 return wantarray ? ($ct) : $ct;
1312 my $tmpfile_seq_no = 0;
1314 sub get_upload_filename {
1315 # choose unpredictable tmpfile name
1318 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1321 sub unshift_read_header {
1322 my ($self, $reqstate, $state) = @_;
1324 $state = { size => 0, count => 0 } if !$state;
1326 $reqstate->{hdl}->unshift_read(line => sub {
1327 my ($hdl, $line) = @_;
1330 # print "$$: got header
: $line\n" if $self->{debug};
1332 die "too many http header lines
(> $limit_max_headers)\n" if ++$state->{count} >= $limit_max_headers;
1333 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1335 my $r = $reqstate->{request};
1338 $r->push_header($state->{key}, $state->{val})
1341 return if !$self->process_header($reqstate);
1342 return if !$self->ensure_tls_connection($reqstate);
1344 $self->authenticate_and_handle_request($reqstate);
1346 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1347 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1348 ($state->{key}, $state->{val}) = ($1, $2);
1349 $self->unshift_read_header($reqstate, $state);
1350 } elsif ($line =~ /^\s+(.*)/) {
1351 $state->{val} .= " $1";
1352 $self->unshift_read_header($reqstate, $state);
1354 $self->error($reqstate, 506, "unable to parse request header
");
1361 # sends an (error) response and returns 0 in case of errors
1362 sub process_header {
1363 my ($self, $reqstate) = @_;
1365 my $request = $reqstate->{request};
1367 my $path = uri_unescape($request->uri->path());
1368 my $method = $request->method();
1370 if (!$known_methods->{$method}) {
1371 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
1372 $self->response($reqstate, $resp);
1376 my $conn = $request->header('Connection');
1377 my $accept_enc = $request->header('Accept-Encoding');
1378 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1379 $reqstate->{accept_deflate} = ($accept_enc && $accept_enc =~ m/deflate/) ? 1 : 0;
1382 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1384 if ($reqstate->{proto}->{ver} < 1001) {
1385 $reqstate->{keep_alive} = 0;
1389 my $te = $request->header('Transfer-Encoding');
1390 if ($te && lc($te) eq 'chunked') {
1391 # Handle chunked transfer encoding
1392 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
1395 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
1399 my $pveclientip = $request->header('PVEClientIP');
1401 # fixme: how can we make PVEClientIP header trusted?
1402 if ($self->{trusted_env} && $pveclientip) {
1403 $reqstate->{peer_host} = $pveclientip;
1405 $request->header('PVEClientIP', $reqstate->{peer_host});
1408 if (my $rpcenv = $self->{rpcenv}) {
1409 $rpcenv->set_request_host($request->header('Host'));
1415 # sends an (redirect) response, disconnects the client and returns 0 if
1416 # connection is not TLS-protected
1417 sub ensure_tls_connection {
1418 my ($self, $reqstate) = @_;
1420 # Skip if server doesn't use TLS
1421 if (!$self->{tls_ctx}) {
1425 # TLS session exists, so the handshake has succeeded
1426 if ($reqstate->{hdl}->{tls}) {
1430 my $request = $reqstate->{request};
1431 my $method = $request->method();
1433 my $h_host = $reqstate->{request}->header('Host');
1435 die "Header field
'Host' not found
in request
\n"
1438 my $secure_host = "https
://" . ($h_host =~ s/^http(s)?:\/\///r);
1440 my $header = HTTP::Headers->new('Location' => $secure_host . $request->uri());
1442 if ($method eq 'GET' || $method eq 'HEAD') {
1443 $self->error($reqstate, 301, 'Moved Permanently', $header);
1445 $self->error($reqstate, 308, 'Permanent Redirect', $header);
1448 # disconnect the client so they may immediately connect again via HTTPS
1449 $self->client_do_disconnect($reqstate);
1454 sub authenticate_and_handle_request {
1455 my ($self, $reqstate) = @_;
1457 my $request = $reqstate->{request};
1458 my $method = $request->method();
1460 my $path = uri_unescape($request->uri->path());
1461 my $base_uri = $self->{base_uri};
1465 if ($self->{spiceproxy}) {
1466 my $connect_str = $request->header('Host');
1467 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
1469 if (!(defined($vmid) && $node && $port)) {
1470 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket
");
1474 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1477 } elsif ($path =~ m/^\Q$base_uri\E/) {
1478 my $token = $request->header('CSRFPreventionToken');
1479 my $cookie = $request->header('Cookie');
1480 my $auth_header = $request->header('Authorization');
1482 # prefer actual cookie
1483 my $ticket = PVE::APIServer::Formatter::extract_auth_value(
1485 $self->{cookie_name}
1488 # fallback to cookie in 'Authorization' header
1490 $ticket = PVE::APIServer::Formatter::extract_auth_value(
1492 $self->{cookie_name}
1496 # finally, fallback to API token if no ticket has been provided so far
1499 $api_token = PVE::APIServer::Formatter::extract_auth_value(
1501 $self->{apitoken_name}
1505 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1507 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
1512 $auth = $self->auth_handler(
1518 $reqstate->{peer_host}
1523 Net::SSLeay::ERR_clear_error();
1524 # always delay unauthorized calls by 3 seconds
1527 if (ref($err) eq "PVE
::Exception
") {
1529 $err->{code} ||= HTTP_INTERNAL_SERVER_ERROR,
1530 my $resp = HTTP::Response->new($err->{code}, $err->{msg});
1531 $self->response($reqstate, $resp, undef, 0, $delay);
1533 } elsif (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
1534 my ($raw, $ct, $nocomp) =
1535 $formatter->($path, $auth, $self->{formatter_config});
1538 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1542 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required
");
1543 $resp->header("Content-Type
" => $ct);
1544 $resp->content($raw);
1547 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1550 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1551 $self->response($reqstate, $resp, undef, 0, $delay);
1558 $reqstate->{log}->{userid} = $auth->{userid};
1559 my $len = $request->header('Content-Length');
1563 if (!($method eq 'PUT' || $method eq 'POST')) {
1564 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
1568 my $ctype = $request->header('Content-Type');
1569 my ($ct, $boundary) = $ctype ? parse_content_type($ctype) : ();
1571 if ($auth->{isUpload} && !$self->{trusted_env}) {
1572 die "upload
'Content-Type '$ctype' not implemented\n"
1573 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
1575 die "upload without content length header not supported" if !$len;
1577 die "upload without content length header not supported" if !$len;
1579 $self->dprint("start upload $path $ct $boundary");
1581 my $tmpfilename = get_upload_filename();
1582 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1583 die "unable to create temporary upload file '$tmpfilename'";
1585 $reqstate->{keep_alive} = 0;
1587 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1591 boundary => $boundary,
1592 boundlen => $boundlen,
1593 maxheader => 2048 + $boundlen, # should be large enough
1594 params => decode_urlencoded($request->url->query()),
1598 starttime => [gettimeofday],
1602 die "'tmpfilename
' query parameter is not allowed for file uploads\n"
1603 if exists $state->{params}->{tmpfilename};
1605 $reqstate->{tmpfilename} = $tmpfilename;
1606 $reqstate->{hdl}->on_read(sub {
1607 $self->file_upload_multipart($reqstate, $auth, $method, $path, $state);
1613 if ($len > $limit_max_post) {
1614 $self->error($reqstate, 501, "for data too large");
1618 if (!$ct || $ct eq 'application
/x-www-form-urlencoded' || $ct eq 'application/json
') {
1619 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1620 my ($hdl, $data) = @_;
1621 $request->content($data);
1622 $self->handle_request($reqstate, $auth, $method, $path);
1626 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
1630 $self->handle_request($reqstate, $auth, $method, $path);
1634 sub push_request_header {
1635 my ($self, $reqstate) = @_;
1638 $reqstate->{hdl}->push_read(line => sub {
1639 my ($hdl, $line) = @_;
1642 # print "got request header
: $line\n" if $self->{debug};
1644 $reqstate->{keep_alive}--;
1646 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1647 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1650 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
1653 if ($url =~ m|^[^/]*@|) {
1654 # if an '@' comes before the first slash proxy forwarding might consider
1655 # the frist part of the url to be part of an authority...
1656 $self->error($reqstate, 400, "invalid url
");
1660 $self->{request_count}++; # only count valid request headers
1661 if ($self->{request_count} >= $self->{max_requests}) {
1662 $self->{end_loop} = 1;
1664 $reqstate->{log} = { requestline => $line };
1665 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
1666 $reqstate->{proto}->{maj} = $maj;
1667 $reqstate->{proto}->{min} = $min;
1668 $reqstate->{proto}->{ver} = $maj*1000+$min;
1669 $reqstate->{request} = HTTP::Request->new($method, $url);
1670 $reqstate->{starttime} = [gettimeofday];
1672 $self->unshift_read_header($reqstate);
1673 } elsif ($line eq '') {
1674 # ignore empty lines before requests (browser bugs?)
1675 $self->push_request_header($reqstate);
1677 $self->error($reqstate, 400, 'bad request');
1691 return if $self->{end_loop};
1693 # we need to m make sure that only one process calls accept
1694 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1695 next if $! == EINTR;
1696 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
1702 while (!$self->{end_loop} &&
1703 !defined($clientfh = $self->{socket}->accept()) &&
1706 if ($self->{end_loop}) {
1709 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1710 if (!defined($clientfh)) {
1711 $errmsg = "failed to
accept connection
: $!\n";
1717 flock($self->{lockfh}, Fcntl::LOCK_UN());
1719 if (!defined($clientfh)) {
1721 die $errmsg if $errmsg;
1724 fh_nonblocking $clientfh, 1;
1732 $self->{end_loop} = 1;
1734 undef $self->{socket_watch};
1736 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1738 if ($self->{conn_count} <= 0) {
1739 $self->{end_cond}->send(1);
1743 # fork and exit, so that parent starts a new worker
1748 # else we need to wait until all open connections gets closed
1749 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1751 # todo: test for active connections instead (we can abort idle connections)
1752 if ($self->{conn_count} <= 0) {
1754 $self->{end_cond}->send(1);
1762 sub check_host_access {
1763 my ($self, $clientip) = @_;
1765 $clientip = PVE::APIServer::Utils::normalize_v4_in_v6($clientip);
1766 my $cip = Net::IP->new($clientip);
1769 $self->dprint("client IP
not parsable
: $@");
1773 my $match_allow = 0;
1776 if ($self->{allow_from}) {
1777 foreach my $t (@{$self->{allow_from}}) {
1778 if ($t->overlaps($cip)) {
1780 $self->dprint("client IP allowed
: ". $t->print());
1786 if ($self->{deny_from}) {
1787 foreach my $t (@{$self->{deny_from}}) {
1788 if ($t->overlaps($cip)) {
1789 $self->dprint("client IP denied
: ". $t->print());
1796 if ($match_allow == $match_deny) {
1797 # match both allow and deny, or no match
1798 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1801 return $match_allow;
1804 sub accept_connections {
1807 my ($clientfh, $handle_creation);
1810 while ($clientfh = $self->accept()) {
1812 my $reqstate = { keep_alive => $self->{keep_alive} };
1814 # stop keep-alive when there are many open connections
1815 if ($self->{conn_count} + 1 >= $self->{max_conn_soft_limit}) {
1816 $reqstate->{keep_alive} = 0;
1819 if (my $sin = getpeername($clientfh)) {
1820 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1821 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1823 $self->dprint("getpeername failed
: $!");
1828 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1829 $self->dprint("ABORT request from
$reqstate->{peer_host
} - access denied
");
1830 $reqstate->{log}->{code} = 403;
1831 $self->log_request($reqstate);
1836 # Increment conn_count before creating new handle, since creation
1837 # triggers callbacks, which can potentialy decrement (e.g.
1838 # on_error) conn_count before AnyEvent::Handle->new() returns.
1839 $handle_creation = 1;
1840 $self->{conn_count}++;
1841 $reqstate->{hdl} = AnyEvent::Handle->new(
1843 rbuf_max => 64*1024,
1844 timeout => $self->{timeout},
1845 linger => 0, # avoid problems with ssh - really needed ?
1849 $self->log_aborted_request($reqstate);
1850 $self->client_do_disconnect($reqstate);
1852 if (my $err = $@) { syslog('err', $err); }
1855 my ($hdl, $fatal, $message) = @_;
1857 $self->log_aborted_request($reqstate, $message);
1858 $self->client_do_disconnect($reqstate);
1860 if (my $err = $@) { syslog('err', "$err"); }
1863 $handle_creation = 0;
1865 $self->dprint("ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}");
1867 if ($self->{tls_ctx}) {
1868 $self->dprint("Setting TLS to autostart
");
1869 $reqstate->{hdl}->unshift_read(tls_autostart => $self->{tls_ctx}, "accept");
1872 $self->push_request_header($reqstate);
1877 syslog('err', $err);
1878 $self->dprint("connection
accept error
: $err");
1880 if ($handle_creation) {
1881 if ($self->{conn_count} <= 0) {
1882 warn "connection count
<= 0 not decrementing
!\n";
1884 $self->{conn_count}--;
1887 $self->{end_loop} = 1;
1890 $self->wait_end_loop() if $self->{end_loop};
1893 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1894 # because we write from multiple processes, and that would arbitrarily mix output
1896 sub open_access_log {
1897 my ($self, $filename) = @_;
1899 my $old_mask = umask(0137);;
1900 my $logfh = IO::File->new($filename, ">>") ||
1901 die "unable to
open log file
'$filename' - $!\n";
1904 $logfh->autoflush(1);
1906 $self->{logfh} = $logfh;
1910 my ($self, $data) = @_;
1912 return if !defined($self->{logfh}) || !$data;
1914 my $res = $self->{logfh}->print($data);
1917 delete $self->{logfh};
1918 syslog('err', "error writing access
log");
1919 $self->{end_loop} = 1; # terminate asap
1923 sub atfork_handler {
1927 # something else do to ?
1928 close($self->{socket});
1936 $self->{end_cond}->recv;
1940 my ($this, %args) = @_;
1942 my $class = ref($this) || $this;
1944 foreach my $req (qw(socket lockfh lockfile)) {
1945 die "misssing required argument '$req'" if !defined($args{$req});
1948 my $self = bless { %args }, $class;
1950 $self->{cookie_name
} //= 'PVEAuthCookie';
1951 $self->{apitoken_name
} //= 'PVEAPIToken';
1952 $self->{base_uri
} //= "/api2";
1953 $self->{dirs
} //= {};
1954 $self->{title
} //= 'API Inspector';
1955 $self->{compression
} //= 1;
1957 # formatter_config: we pass some configuration values to the Formatter
1958 $self->{formatter_config
} = {};
1959 foreach my $p (qw(apitoken_name cookie_name base_uri title)) {
1960 $self->{formatter_config
}->{$p} = $self->{$p};
1962 $self->{formatter_config
}->{csrfgen_func
} =
1963 $self->can('generate_csrf_prevention_token');
1965 # add default dirs which includes jquery and bootstrap
1966 my $jsbase = '/usr/share/javascript';
1967 add_dirs
($self->{dirs
}, '/js/' => "$jsbase/");
1968 # libjs-bootstrap uses symlinks for this, which we do not want to allow..
1969 my $glyphicons = '/usr/share/fonts/truetype/glyphicons/';
1970 add_dirs
($self->{dirs
}, '/js/bootstrap/fonts/' => "$glyphicons");
1973 PVE
::INotify
::inotify_init
();
1975 fh_nonblocking
($self->{socket}, 1);
1977 $self->{end_loop
} = 0;
1978 $self->{conn_count
} = 0;
1979 $self->{request_count
} = 0;
1980 $self->{timeout
} = 5 if !$self->{timeout
};
1981 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1982 $self->{max_conn
} = 800 if !$self->{max_conn
};
1983 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1985 $self->{policy
} = 'allow' if !$self->{policy
};
1987 $self->{end_cond
} = AnyEvent-
>condvar;
1990 my $ssl_defaults = {
1991 # Note: older versions are considered insecure, for example
1992 # search for "Poodle"-Attack
1996 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',
1997 honor_cipher_order
=> 1,
2000 # workaround until anyevent supports TLS 1.3 ciphersuites directly
2001 my $ciphersuites = delete $self->{ssl
}->{ciphersuites
};
2003 foreach my $k (keys %$ssl_defaults) {
2004 $self->{ssl
}->{$k} //= $ssl_defaults->{$k};
2007 if (!defined($self->{ssl
}->{dh_file
})) {
2008 $self->{ssl
}->{dh
} = 'skip2048';
2011 my $tls_ctx_flags = 0;
2012 $tls_ctx_flags |= &Net
::SSLeay
::OP_NO_COMPRESSION
;
2013 $tls_ctx_flags |= &Net
::SSLeay
::OP_SINGLE_ECDH_USE
;
2014 $tls_ctx_flags |= &Net
::SSLeay
::OP_SINGLE_DH_USE
;
2015 $tls_ctx_flags |= &Net
::SSLeay
::OP_NO_RENEGOTIATION
;
2016 if (delete $self->{ssl
}->{honor_cipher_order
}) {
2017 $tls_ctx_flags |= &Net
::SSLeay
::OP_CIPHER_SERVER_PREFERENCE
;
2019 # workaround until anyevent supports disabling TLS 1.3 directly
2020 if (exists($self->{ssl
}->{tlsv1_3
}) && !$self->{ssl
}->{tlsv1_3
}) {
2021 $tls_ctx_flags |= &Net
::SSLeay
::OP_NO_TLSv1_3
;
2025 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
2026 Net
::SSLeay
::CTX_set_options
($self->{tls_ctx
}->{ctx
}, $tls_ctx_flags);
2027 if (defined($ciphersuites)) {
2028 warn "Failed to set TLS 1.3 ciphersuites '$ciphersuites'\n"
2029 if !Net
::SSLeay
::CTX_set_ciphersuites
($self->{tls_ctx
}->{ctx
}, $ciphersuites);
2032 my $opts = Net
::SSLeay
::CTX_get_options
($self->{tls_ctx
}->{ctx
});
2033 my $min_version = Net
::SSLeay
::TLS1_1_VERSION
();
2034 my $max_version = Net
::SSLeay
::TLS1_3_VERSION
();
2035 if ($opts & &Net
::SSLeay
::OP_NO_TLSv1_1
) {
2036 $min_version = Net
::SSLeay
::TLS1_2_VERSION
();
2038 if ($opts & &Net
::SSLeay
::OP_NO_TLSv1_2
) {
2039 $min_version = Net
::SSLeay
::TLS1_3_VERSION
();
2041 if ($opts & &Net
::SSLeay
::OP_NO_TLSv1_3
) {
2042 die "misconfigured TLS settings - cannot disable all supported TLS versions!\n"
2043 if $min_version && $min_version == Net
::SSLeay
::TLS1_3_VERSION
();
2044 $max_version = Net
::SSLeay
::TLS1_2_VERSION
();
2046 Net
::SSLeay
::CTX_set_min_proto_version
($self->{tls_ctx
}->{ctx
}, $min_version) if $min_version;
2047 Net
::SSLeay
::CTX_set_max_proto_version
($self->{tls_ctx
}->{ctx
}, $max_version);
2050 if ($self->{spiceproxy
}) {
2051 $known_methods = { CONNECT
=> 1 };
2054 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
2056 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
2058 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
2060 if ($self->{conn_count
} >= $self->{max_conn
}) {
2061 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
2062 if ($self->{conn_count
} < $self->{max_conn
}) {
2064 $self->accept_connections();
2068 $self->accept_connections();
2074 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
2075 undef $self->{term_watch
};
2076 $self->wait_end_loop();
2079 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
2080 undef $self->{quit_watch
};
2081 $self->wait_end_loop();
2084 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
2085 PVE
::INotify
::poll
(); # read inotify events
2091 # static helper to add directory including all subdirs
2092 # This can be used to setup $self->{dirs}
2094 my ($result_hash, $alias, $subdir) = @_;
2096 $result_hash->{$alias} = $subdir;
2099 my $dir = $File::Find
::dir
;
2100 if ($dir =~m!^$subdir(.*)$!) {
2101 my $name = "$alias$1/";
2102 $result_hash->{$name} = "$dir/";
2106 find
({wanted
=> $wanted, follow
=> 0, no_chdir
=> 1}, $subdir);
2109 # abstract functions - subclass should overwrite/implement them
2111 sub verify_spice_connect_url
{
2112 my ($self, $connect_str) = @_;
2116 #return ($vmid, $node, $port);
2119 # formatters can call this when the generate a new page
2120 sub generate_csrf_prevention_token
{
2121 my ($username) = @_;
2123 return undef; # do nothing by default
2127 my ($self, $method, $rel_uri, $ticket, $token, $api_token, $peer_host) = @_;
2132 # ticket => $ticket,
2134 # userid => $username,
2136 # isUpload => $isUpload,
2137 # api_token => $api_token,
2142 my ($self, $clientip, $method, $rel_uri, $auth, $params, $format) = @_;
2144 # please do not raise exceptions here (always return a result).
2147 status
=> HTTP_NOT_IMPLEMENTED
,
2148 message
=> "Method '$method $rel_uri' not implemented",
2151 # this should return the following properties, which
2152 # are then passed to the Formatter
2154 # status: HTTP status code
2155 # message: Error message
2156 # errors: more detailed error hash (per parameter)
2157 # info: reference to JSON schema definition - useful to format output
2160 # total: additional info passed to output
2161 # changes: additional info passed to output
2163 # if you want to proxy the request to another node return this
2164 # { proxy => $remip, proxynode => $node, proxy_params => $params };
2166 # to pass the request to the local priviledged daemon use:
2167 # { proxy => 'localhost' , proxy_params => $params };
2169 # to download aspecific file use:
2170 # { download => "/path/to/file" };
2173 sub check_cert_fingerprint
{
2174 my ($self, $cert) = @_;
2179 sub initialize_cert_cache
{
2180 my ($self, $node) = @_;
2185 sub remote_node_ip
{
2186 my ($self, $node) = @_;