1 package PVE
::HTTPServer
;
5 use Time
::HiRes
qw(usleep ualarm gettimeofday tv_interval);
6 use Socket
qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
7 use POSIX
qw(strftime EINTR EAGAIN);
12 # use AnyEvent::Strict; # only use this for debugging
13 use AnyEvent
::Util
qw(guard fh_nonblocking WSAEWOULDBLOCK WSAEINPROGRESS);
23 use PVE
::RPCEnvironment
;
28 use HTTP
::Status
qw(:constants);
33 my $limit_max_headers = 30;
34 my $limit_max_header_size = 8*1024;
35 my $limit_max_post = 16*1024;
45 my $baseuri = "/api2";
50 my ($format, $rel_uri) = $abs_uri =~ m/^\Q$baseuri\E\/+(html
|text
|json
|extjs
|png
|htmljs
|spiceconfig
)(\
/.*)?$/;
51 $rel_uri = '/' if !$rel_uri;
53 return wantarray ?
($rel_uri, $format) : $rel_uri;
57 my ($self, $reqstate) = @_;
59 my $loginfo = $reqstate->{log};
61 # like apache2 common log format
62 # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
64 return if $loginfo->{written
}; # avoid duplicate logs
65 $loginfo->{written
} = 1;
67 my $peerip = $reqstate->{peer_host
} || '-';
68 my $userid = $loginfo->{userid
} || '-';
69 my $content_length = defined($loginfo->{content_length
}) ?
$loginfo->{content_length
} : '-';
70 my $code = $loginfo->{code
} || 500;
71 my $requestline = $loginfo->{requestline
} || '-';
72 my $timestr = strftime
("%d/%b/%Y:%H:%M:%S %z", localtime());
74 my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n";
76 $self->write_log($msg);
79 sub log_aborted_request {
80 my ($self, $reqstate, $error) = @_;
82 my $r = $reqstate->{request};
83 return if !$r; # no active request
86 syslog("err
", "problem with client
$reqstate->{peer_host
}; $error");
89 $self->log_request($reqstate);
92 sub cleanup_reqstate {
95 delete $reqstate->{log};
96 delete $reqstate->{request};
97 delete $reqstate->{proto};
98 delete $reqstate->{accept_gzip};
100 if ($reqstate->{tmpfilename}) {
101 unlink $reqstate->{tmpfilename};
102 delete $reqstate->{tmpfilename};
106 sub client_do_disconnect {
107 my ($self, $reqstate) = @_;
109 cleanup_reqstate($reqstate);
111 my $shutdown_hdl = sub {
114 shutdown($hdl->{fh}, 1);
116 $hdl->on_drain(undef);
117 $hdl->on_read(undef);
121 if (my $proxyhdl = delete $reqstate->{proxyhdl}) {
122 &$shutdown_hdl($proxyhdl);
125 my $hdl = delete $reqstate->{hdl};
128 syslog('err', "detected empty handle
");
132 print "close connection
$hdl\n" if $self->{debug};
134 &$shutdown_hdl($hdl);
136 $self->{conn_count}--;
138 print "$$: CLOSE FH
" . $hdl->{fh}->fileno() . " CONN
$self->{conn_count
}\n" if $self->{debug};
141 sub finish_response {
142 my ($self, $reqstate) = @_;
144 my $hdl = $reqstate->{hdl};
146 cleanup_reqstate($reqstate);
148 if (!$self->{end_loop} && $reqstate->{keep_alive} > 0) {
149 # print "KEEPALIVE
$reqstate->{keep_alive
}\n" if $self->{debug};
151 eval { $self->push_request_header($reqstate); };
155 $hdl->on_drain (sub {
157 $self->client_do_disconnect($reqstate);
165 my ($self, $reqstate, $resp, $mtime, $nocomp) = @_;
167 #print "$$: send response
: " . Dumper($resp);
170 $reqstate->{hdl}->timeout_reset();
171 $reqstate->{hdl}->timeout($self->{timeout});
173 $nocomp = 1 if !$reqstate->{accept_gzip};
175 my $code = $resp->code;
176 my $msg = $resp->message || HTTP::Status::status_message($code);
177 ($msg) = $msg =~m/^(.*)$/m;
178 my $content = $resp->content;
180 if ($code =~ /^(1\d\d|[23]04)$/) {
181 # make sure content we have no content
185 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
187 $reqstate->{log}->{code} = $code;
189 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
190 my $res = "$proto $code $msg\015\012";
193 my $date = HTTP::Date::time2str($ctime);
194 $resp->header('Date' => $date);
196 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
198 $resp->header('Expires' => $date);
199 $resp->header('Cache-Control' => "max-age
=0");
200 $resp->header("Pragma
", "no-cache
");
203 $resp->header('Server' => "pve-api-daemon
/3.0");
208 $content_length = length($content);
210 if (!$nocomp && ($content_length > 1024)) {
211 my $comp = Compress::Zlib::memGzip($content);
212 $resp->header('Content-Encoding', 'gzip');
214 $content_length = length($content);
216 $resp->header("Content-Length
" => $content_length);
217 $reqstate->{log}->{content_length} = $content_length;
220 $resp->remove_header("Content-Length
");
223 if ($reqstate->{keep_alive} > 0) {
224 $resp->push_header('Connection' => 'Keep-Alive');
226 $resp->header('Connection' => 'close');
229 $res .= $resp->headers_as_string("\015\012");
230 #print "SEND
(without content
) $res\n" if $self->{debug};
233 $res .= $content if $content;
235 $self->log_request($reqstate, $reqstate->{request});
237 $reqstate->{hdl}->push_write($res);
238 $self->finish_response($reqstate);
242 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
245 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
246 $self->response($reqstate, $resp);
251 sub send_file_start {
252 my ($self, $reqstate, $filename) = @_;
255 # print "SEND FILE
$filename\n";
256 # Note: aio_load() this is not really async unless we use IO::AIO!
259 my $r = $reqstate->{request};
261 my $fh = IO::File->new($filename, '<') ||
263 my $stat = File::stat::stat($fh) ||
266 my $mtime = $stat->mtime;
268 if (my $ifmod = $r->header('if-modified-since')) {
269 my $iftime = HTTP::Date::str2time($ifmod);
270 if ($mtime <= $iftime) {
271 my $resp = HTTP::Response->new(304, "NOT MODIFIED
");
272 $self->response($reqstate, $resp, $mtime);
278 my $len = sysread($fh, $data, $stat->size);
279 die "got short file
\n" if !defined($len) || $len != $stat->size;
283 if ($filename =~ m/\.css$/) {
285 } elsif ($filename =~ m/\.js$/) {
286 $ct = 'application/javascript';
287 } elsif ($filename =~ m/\.png$/) {
290 } elsif ($filename =~ m/\.gif$/) {
293 } elsif ($filename =~ m/\.jar$/) {
294 $ct = 'application/java-archive';
297 die "unable to detect content type
";
300 my $header = HTTP::Headers->new(Content_Type => $ct);
301 my $resp = HTTP::Response->new(200, "OK
", $header, $data);
302 $self->response($reqstate, $resp, $mtime, $nocomp);
305 $self->error($reqstate, 501, $err);
313 my ($self, $reqstate, $clientip, $host, $method, $uri, $ticket, $token, $params) = @_;
318 if ($host eq 'localhost') {
319 $target = "http
://$host:85$uri";
320 # keep alive for localhost is not worth (connection setup is about 0.2ms)
323 $target = "https
://$host:8006$uri";
327 PVEDisableProxy => 'true',
328 PVEClientIP => $clientip,
331 my $cookie_name = 'PVEAuthCookie';
333 $headers->{'cookie'} = PVE::REST::create_auth_cookie($ticket) if $ticket;
334 $headers->{'CSRFPreventionToken'} = $token if $token;
335 $headers->{'Accept-Encoding'} = 'gzip' if $reqstate->{accept_gzip};
339 if ($method eq 'POST' || $method eq 'PUT') {
340 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
341 # use URI object to format application/x-www-form-urlencoded content.
342 my $url = URI->new('http:');
343 $url->query_form(%$params);
344 $content = $url->query;
345 if (defined($content)) {
346 $headers->{'Content-Length'} = length($content);
350 my $w; $w = http_request(
355 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
356 keepalive => $keep_alive,
358 tls_ctx => $self->{tls_ctx},
360 my ($body, $hdr) = @_;
364 if (!$reqstate->{hdl}) {
365 warn "proxy detected vanished client connection
\n";
370 my $code = delete $hdr->{Status};
371 my $msg = delete $hdr->{Reason};
373 delete $hdr->{HTTPVersion};
374 my $header = HTTP::Headers->new(%$hdr);
375 my $resp = HTTP::Response->new($code, $msg, $header, $body);
376 # Note: disable compression, because body is already compressed
377 $self->response($reqstate, $resp, undef, 1);
385 # return arrays as \0 separated strings (like CGI.pm)
386 sub decode_urlencoded {
391 return $res if !$data;
393 foreach my $kv (split(/[\&\;]/, $data)) {
394 my ($k, $v) = split(/=/, $kv);
396 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
398 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
400 if (defined(my $old = $res->{$k})) {
401 $res->{$k} = "$old\0$v";
410 my ($r, $method) = @_;
414 if ($method eq 'PUT' || $method eq 'POST') {
415 $params = decode_urlencoded($r->content);
418 my $query_params = decode_urlencoded($r->url->query());
420 foreach my $k (keys %{$query_params}) {
421 $params->{$k} = $query_params->{$k};
424 return PVE::Tools::decode_utf8_parameters($params);
427 sub handle_api2_request {
428 my ($self, $reqstate, $auth, $upload_state) = @_;
431 my $r = $reqstate->{request};
432 my $method = $r->method();
433 my $path = $r->uri->path();
435 my ($rel_uri, $format) = split_abs_uri($path);
437 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
441 #print Dumper($upload_state) if $upload_state;
443 my $rpcenv = $self->{rpcenv};
448 $params = $upload_state->{params};
450 $params = extract_params($r, $method);
453 delete $params->{_dc}; # remove disable cache parameter
455 my $clientip = $reqstate->{peer_host};
457 $rpcenv->init_request();
459 my $res = PVE::REST::rest_handler($rpcenv, $clientip, $method, $rel_uri, $auth, $params);
461 AnyEvent->now_update(); # in case somebody called sleep()
463 $rpcenv->set_user(undef); # clear after request
465 if (my $host = $res->{proxy}) {
467 if ($self->{trusted_env}) {
468 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
472 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
473 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
477 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
479 $self->proxy_request($reqstate, $clientip, $host, $method,
480 $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params});
485 PVE::REST::prepare_response_data($format, $res);
486 my ($raw, $ct, $nocomp) = PVE::REST::format_response_data($format, $res, $path);
488 my $resp = HTTP::Response->new($res->{status}, $res->{message});
489 $resp->header("Content-Type
" => $ct);
490 $resp->content($raw);
491 $self->response($reqstate, $resp, $nocomp);
494 $self->error($reqstate, 501, $err);
498 sub handle_spice_proxy_request {
499 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
503 die "Port
$spiceport is not allowed
" if ($spiceport < 61000 || $spiceport > 61099);
505 my $rpcenv = $self->{rpcenv};
506 $rpcenv->init_request();
508 my $clientip = $reqstate->{peer_host};
509 my $r = $reqstate->{request};
513 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
514 $remip = PVE::Cluster::remote_node_ip($node);
515 die "unable to get remote IP address
for node
'$node'\n" if !$remip;
516 print "REMOTE CONNECT
$vmid, $remip, $connect_str\n" if $self->{debug};
518 print "$$: CONNECT
$vmid, $node, $spiceport\n" if $self->{debug};
521 if ($r->header('PVEDisableProxy')) {
522 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
loop detected
");
526 $reqstate->{hdl}->timeout(0);
527 $reqstate->{hdl}->wbuf_max(64*10*1024);
529 my $remhost = $remip ? $remip : "127.0.0.1";
530 my $remport = $remip ? 3128 : $spiceport;
532 tcp_connect $remhost, $remport, sub {
534 or die "connect to
'$remhost:$remport' failed
: $!";
536 print "$$: CONNECTed to
'$remhost:$remport'\n" if $self->{debug};
537 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
540 wbuf_max => 64*10*1024,
545 $self->log_aborted_request($reqstate);
546 $self->client_do_disconnect($reqstate);
548 if (my $err = $@) { syslog('err', $err); }
551 my ($hdl, $fatal, $message) = @_;
553 $self->log_aborted_request($reqstate, $message);
554 $self->client_do_disconnect($reqstate);
556 if (my $err = $@) { syslog('err', "$err"); }
560 my $proxyhdlreader = sub {
563 my $len = length($hdl->{rbuf});
564 my $data = substr($hdl->{rbuf}, 0, $len, '');
566 #print "READ1
$len\n";
567 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
570 my $hdlreader = sub {
573 my $len = length($hdl->{rbuf});
574 my $data = substr($hdl->{rbuf}, 0, $len, '');
576 #print "READ0
$len\n";
577 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
580 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
582 my $startproxy = sub {
583 $reqstate->{proxyhdl}->timeout(0);
584 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
585 $reqstate->{hdl}->on_read($hdlreader);
587 # todo: use stop_read/start_read if write buffer grows to much
589 my $res = "$proto 200 OK
\015\012"; # hope this is the right answer?
590 $reqstate->{hdl}->push_write($res);
593 $reqstate->{log}->{code} = 200;
594 $self->log_request($reqstate);
598 my $header = "CONNECT
${connect_str
} $proto\015\012" .
599 "Host
: ${connect_str
}\015\012" .
600 "Proxy-Connection
: keep-alive
\015\012" .
601 "User-Agent
: spiceproxy
\015\012" .
602 "PVEDisableProxy
: true
\015\012" .
603 "PVEClientIP
: $clientip\015\012" .
606 $reqstate->{proxyhdl}->push_write($header);
607 $reqstate->{proxyhdl}->push_read(line => sub {
608 my ($hdl, $line) = @_;
610 if ($line =~ m!^$proto 200 OK$!) {
613 $reqstate->{hdl}->push_write($line);
614 $self->client_do_disconnect($reqstate);
625 $self->log_aborted_request($reqstate, $err);
626 $self->client_do_disconnect($reqstate);
631 my ($self, $reqstate, $auth) = @_;
634 my $r = $reqstate->{request};
635 my $method = $r->method();
636 my $path = $r->uri->path();
638 # disable timeout on handle (we already have all data we need)
639 # we re-enable timeout in response()
640 $reqstate->{hdl}->timeout(0);
642 if ($path =~ m!$baseuri!) {
643 $self->handle_api2_request($reqstate, $auth);
647 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
648 if (ref($handler) eq 'CODE') {
649 my $params = decode_urlencoded($r->url->query());
650 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
651 $self->response($reqstate, $resp);
652 } elsif (ref($handler) eq 'HASH') {
653 if (my $filename = $handler->{file}) {
654 my $fh = IO::File->new($filename) ||
655 die "unable to
open file
'$filename' - $!\n";
656 send_file_start($self, $reqstate, $filename);
658 die "internal error
- no handler
";
661 die "internal error
- no handler
";
666 if ($self->{dirs} && ($method eq 'GET')) {
667 # we only allow simple names
668 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
669 my ($subdir, $file) = ($1, $2);
670 if (my $dir = $self->{dirs}->{$subdir}) {
671 my $filename = "$dir$file";
672 my $fh = IO::File->new($filename) ||
673 die "unable to
open file
'$filename' - $!\n";
674 send_file_start($self, $reqstate, $filename);
680 die "no such file
'$path'";
683 $self->error($reqstate, 501, $err);
687 sub file_upload_multipart {
688 my ($self, $reqstate, $auth, $rstate) = @_;
691 my $boundary = $rstate->{boundary};
692 my $hdl = $reqstate->{hdl};
694 my $startlen = length($hdl->{rbuf});
696 if ($rstate->{phase} == 0) { # skip everything until start
697 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
698 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
700 my ($ct, $disp, $name, $filename);
701 foreach my $line (split(/\015?\012/, $header)) {
702 # assume we have single line headers
703 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
704 $ct = parse_content_type($1);
705 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
706 ($disp, $name, $filename) = parse_content_disposition($1);
710 if (!($disp && $disp eq 'form-data' && $name)) {
711 syslog('err', "wrong content disposition
in multipart
- abort upload
");
712 $rstate->{phase} = -1;
715 $rstate->{fieldname} = $name;
718 if ($name eq 'filename') {
719 # found file upload data
720 $rstate->{phase} = 1;
721 $rstate->{filename} = $filename;
723 syslog('err', "wrong field name
for file upload
- abort upload
");
724 $rstate->{phase} = -1;
727 # found form data for field $name
728 $rstate->{phase} = 2;
732 my $len = length($hdl->{rbuf});
733 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
734 if $len > $rstate->{maxheader}; # skip garbage
736 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
737 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
738 my ($rest, $eof) = ($1, $3);
739 my $len = length($rest);
740 die "write to temporary file failed
- $!"
741 if syswrite($rstate->{outfh}, $rest) != $len;
742 $rstate->{ctx}->add($rest);
743 $rstate->{params}->{filename} = $rstate->{filename};
744 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
745 $rstate->{bytes} += $len;
746 $rstate->{phase} = $eof ? 100 : 0;
748 my $len = length($hdl->{rbuf});
749 my $wlen = $len - $rstate->{boundlen};
751 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
752 die "write to temporary file failed
- $!"
753 if syswrite($rstate->{outfh}, $data) != $wlen;
754 $rstate->{bytes} += $wlen;
755 $rstate->{ctx}->add($data);
758 } elsif ($rstate->{phase} == 2) { # inside normal field
760 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
761 my ($rest, $eof) = ($1, $3);
762 my $len = length($rest);
763 $rstate->{post_size} += $len;
764 if ($rstate->{post_size} < $limit_max_post) {
765 $rstate->{params}->{$rstate->{fieldname}} = $rest;
766 $rstate->{phase} = $eof ? 100 : 0;
768 syslog('err', "form data to large
- abort upload
");
769 $rstate->{phase} = -1; # skip
773 my $len = length($hdl->{rbuf});
774 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
777 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
779 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
780 $rstate->{done} = 1; # make sure we dont get called twice
781 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
782 die "upload failed
\n";
784 my $elapsed = tv_interval($rstate->{starttime});
786 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
787 syslog('info', "multipart upload complete
" .
788 "(size
: %d time: %ds rate
: %.2fMiB
/s md5sum
: $rstate->{md5sum
})",
789 $rstate->{bytes}, $elapsed, $rate);
790 $self->handle_api2_request($reqstate, $auth, $rstate);
796 $self->error($reqstate, 501, $err);
800 sub parse_content_type {
803 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
805 foreach my $v (@params) {
806 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
807 return wantarray ? ($ct, $1) : $ct;
811 return wantarray ? ($ct) : $ct;
814 sub parse_content_disposition {
817 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
821 foreach my $v (@params) {
822 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
824 $name =~ s/^"(.*)"$/$1/;
825 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
827 $filename =~ s/^"(.*)"$/$1/;
831 return wantarray ? ($disp, $name, $filename) : $disp;
834 my $tmpfile_seq_no = 0;
836 sub get_upload_filename {
837 # choose unpredictable tmpfile name
840 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
843 sub unshift_read_header {
844 my ($self, $reqstate, $state) = @_;
846 $state = { size => 0, count => 0 } if !$state;
848 $reqstate->{hdl}->unshift_read(line => sub {
849 my ($hdl, $line) = @_;
852 # print "$$: got header
: $line\n" if $self->{debug};
854 die "to many http header lines
\n" if ++$state->{count} >= $limit_max_headers;
855 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
857 my $r = $reqstate->{request};
860 my $path = $r->uri->path();
861 my $method = $r->method();
863 $r->push_header($state->{key}, $state->{val})
866 if (!$known_methods->{$method}) {
867 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
868 $self->response($reqstate, $resp);
872 my $conn = $r->header('Connection');
873 my $accept_enc = $r->header('Accept-Encoding');
874 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
877 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
879 if ($reqstate->{proto}->{ver} < 1001) {
880 $reqstate->{keep_alive} = 0;
884 my $te = $r->header('Transfer-Encoding');
885 if ($te && lc($te) eq 'chunked') {
886 # Handle chunked transfer encoding
887 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
890 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
894 my $pveclientip = $r->header('PVEClientIP');
896 # fixme: how can we make PVEClientIP header trusted?
897 if ($self->{trusted_env} && $pveclientip) {
898 $reqstate->{peer_host} = $pveclientip;
900 $r->header('PVEClientIP', $reqstate->{peer_host});
903 my $len = $r->header('Content-Length');
905 # header processing complete - authenticate now
908 if ($self->{spiceproxy}) {
909 my $connect_str = $r->header('Host');
910 my ($vmid, $node, $port) = PVE::AccessControl::verify_spice_connect_url($connect_str);
911 if (!($vmid && $node && $port)) {
912 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket
");
915 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
917 } elsif ($path =~ m!$baseuri!) {
918 my $token = $r->header('CSRFPreventionToken');
919 my $cookie = $r->header('Cookie');
920 my $ticket = PVE::REST::extract_auth_cookie($cookie);
922 my ($rel_uri, $format) = split_abs_uri($path);
924 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
929 $auth = PVE::REST::auth_handler($self->{rpcenv}, $reqstate->{peer_host}, $method,
930 $rel_uri, $ticket, $token);
933 $self->error($reqstate, HTTP_UNAUTHORIZED, $err);
938 $reqstate->{log}->{userid} = $auth->{userid};
942 if (!($method eq 'PUT' || $method eq 'POST')) {
943 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
947 my $ctype = $r->header('Content-Type');
948 my ($ct, $boundary) = parse_content_type($ctype) if $ctype;
950 if ($auth->{isUpload} && !$self->{trusted_env}) {
951 die "upload
'Content-Type '$ctype' not implemented\n"
952 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
954 die "upload without content length header not supported" if !$len;
956 die "upload without content length header not supported" if !$len;
958 print "start upload $path $ct $boundary\n" if $self->{debug};
960 my $tmpfilename = get_upload_filename();
961 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
962 die "unable to create temporary upload file '$tmpfilename'";
964 $reqstate->{keep_alive} = 0;
966 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
970 boundary => $boundary,
971 ctx => Digest::MD5->new,
972 boundlen => $boundlen,
973 maxheader => 2048 + $boundlen, # should be large enough
974 params => decode_urlencoded($r->url->query()),
978 starttime => [gettimeofday],
981 $reqstate->{tmpfilename} = $tmpfilename;
982 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $state); });
986 if ($len > $limit_max_post) {
987 $self->error($reqstate, 501, "for data too large");
991 if (!$ct || $ct eq 'application
/x-www-form-urlencoded
') {
992 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
993 my ($hdl, $data) = @_;
995 $self->handle_request($reqstate, $auth);
998 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
1001 $self->handle_request($reqstate, $auth);
1003 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1004 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1005 ($state->{key}, $state->{val}) = ($1, $2);
1006 $self->unshift_read_header($reqstate, $state);
1007 } elsif ($line =~ /^\s+(.*)/) {
1008 $state->{val} .= " $1";
1009 $self->unshift_read_header($reqstate, $state);
1011 $self->error($reqstate, 506, "unable to parse request header
");
1018 sub push_request_header {
1019 my ($self, $reqstate) = @_;
1022 $reqstate->{hdl}->push_read(line => sub {
1023 my ($hdl, $line) = @_;
1026 # print "got request header
: $line\n" if $self->{debug};
1028 $reqstate->{keep_alive}--;
1030 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1031 my ($method, $uri, $maj, $min) = ($1, $2, $3, $4);
1034 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
1038 $self->{request_count}++; # only count valid request headers
1039 if ($self->{request_count} >= $self->{max_requests}) {
1040 $self->{end_loop} = 1;
1042 $reqstate->{log} = { requestline => $line };
1043 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
1044 $reqstate->{proto}->{maj} = $maj;
1045 $reqstate->{proto}->{min} = $min;
1046 $reqstate->{proto}->{ver} = $maj*1000+$min;
1047 $reqstate->{request} = HTTP::Request->new($method, $uri);
1049 $self->unshift_read_header($reqstate);
1050 } elsif ($line eq '') {
1051 # ignore empty lines before requests (browser bugs?)
1052 $self->push_request_header($reqstate);
1054 $self->error($reqstate, 400, 'bad request');
1068 return if $self->{end_loop};
1070 # we need to m make sure that only one process calls accept
1071 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1072 next if $! == EINTR;
1073 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
1079 while (!$self->{end_loop} &&
1080 !defined($clientfh = $self->{socket}->accept()) &&
1083 if ($self->{end_loop}) {
1086 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1087 if (!defined($clientfh)) {
1088 $errmsg = "failed to
accept connection
: $!\n";
1094 flock($self->{lockfh}, Fcntl::LOCK_UN());
1096 if (!defined($clientfh)) {
1098 die $errmsg if $errmsg;
1101 fh_nonblocking $clientfh, 1;
1103 $self->{conn_count}++;
1111 $self->{end_loop} = 1;
1113 undef $self->{socket_watch};
1115 if ($self->{conn_count} <= 0) {
1116 $self->{end_cond}->send(1);
1120 # else we need to wait until all open connections gets closed
1121 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1123 # todo: test for active connections instead (we can abort idle connections)
1124 if ($self->{conn_count} <= 0) {
1126 $self->{end_cond}->send(1);
1134 sub check_host_access {
1135 my ($self, $clientip) = @_;
1137 my $cip = Net::IP->new($clientip);
1139 my $match_allow = 0;
1142 if ($self->{allow_from}) {
1143 foreach my $t (@{$self->{allow_from}}) {
1144 if ($t->overlaps($cip)) {
1151 if ($self->{deny_from}) {
1152 foreach my $t (@{$self->{deny_from}}) {
1153 if ($t->overlaps($cip)) {
1160 if ($match_allow == $match_deny) {
1161 # match both allow and deny, or no match
1162 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1165 return $match_allow;
1168 sub accept_connections {
1173 while (my $clientfh = $self->accept()) {
1175 my $reqstate = { keep_alive => $self->{keep_alive} };
1177 # stop keep-alive when there are many open connections
1178 if ($self->{conn_count} >= $self->{max_conn_soft_limit}) {
1179 $reqstate->{keep_alive} = 0;
1182 if (my $sin = getpeername($clientfh)) {
1183 my ($pport, $phost) = Socket::unpack_sockaddr_in($sin);
1184 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntoa($phost));
1187 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1188 print "$$: ABORT request from
$reqstate->{peer_host
} - access denied
\n" if $self->{debug};
1189 $reqstate->{log}->{code} = 403;
1190 $self->log_request($reqstate);
1194 $reqstate->{hdl} = AnyEvent::Handle->new(
1196 rbuf_max => 64*1024,
1197 timeout => $self->{timeout},
1198 linger => 0, # avoid problems with ssh - really needed ?
1202 $self->log_aborted_request($reqstate);
1203 $self->client_do_disconnect($reqstate);
1205 if (my $err = $@) { syslog('err', $err); }
1208 my ($hdl, $fatal, $message) = @_;
1210 $self->log_aborted_request($reqstate, $message);
1211 $self->client_do_disconnect($reqstate);
1213 if (my $err = $@) { syslog('err', "$err"); }
1215 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1217 print "$$: ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}\n" if $self->{debug};
1219 $self->push_request_header($reqstate);
1224 syslog('err', $err);
1225 $self->{end_loop} = 1;
1228 $self->wait_end_loop() if $self->{end_loop};
1231 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1232 # because we write from multiple processes, and that would arbitrarily mix output
1234 sub open_access_log {
1235 my ($self, $filename) = @_;
1237 my $old_mask = umask(0137);;
1238 my $logfh = IO::File->new($filename, ">>") ||
1239 die "unable to
open log file
'$filename' - $!\n";
1242 $logfh->autoflush(1);
1244 $self->{logfh} = $logfh;
1248 my ($self, $data) = @_;
1250 return if !defined($self->{logfh}) || !$data;
1252 my $res = $self->{logfh}->print($data);
1255 delete $self->{logfh};
1256 syslog('err', "error writing access
log");
1257 $self->{end_loop} = 1; # terminate asap
1261 sub atfork_handler {
1265 # something else do to ?
1266 close($self->{socket});
1272 my ($this, %args) = @_;
1274 my $class = ref($this) || $this;
1276 foreach my $req (qw(socket lockfh lockfile)) {
1277 die "misssing required argument '$req'" if !defined($args{$req});
1280 my $self = bless { %args }, $class;
1283 PVE
::INotify
::inotify_init
();
1285 $self->{rpcenv
} = PVE
::RPCEnvironment-
>init(
1286 $self->{trusted_env
} ?
'priv' : 'pub', atfork
=> sub { $self-> atfork_handler
() });
1288 fh_nonblocking
($self->{socket}, 1);
1290 $self->{end_loop
} = 0;
1291 $self->{conn_count
} = 0;
1292 $self->{request_count
} = 0;
1293 $self->{timeout
} = 5 if !$self->{timeout
};
1294 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1295 $self->{max_conn
} = 800 if !$self->{max_conn
};
1296 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1298 $self->{policy
} = 'allow' if !$self->{policy
};
1300 $self->{end_cond
} = AnyEvent-
>condvar;
1303 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
1306 if ($self->{spiceproxy
}) {
1307 $known_methods = { CONNECT
=> 1 };
1310 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
1312 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
1314 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
1316 if ($self->{conn_count
} >= $self->{max_conn
}) {
1317 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
1318 if ($self->{conn_count
} < $self->{max_conn
}) {
1320 $self->accept_connections();
1324 $self->accept_connections();
1330 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
1331 undef $self->{term_watch
};
1332 $self->wait_end_loop();
1335 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
1336 undef $self->{quit_watch
};
1337 $self->wait_end_loop();
1340 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
1341 PVE
::INotify
::poll
(); # read inotify events
1350 $self->{end_cond
}->recv;