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
467 if ($self->{trusted_env}) {
468 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy
not allowed
");
472 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
474 $self->proxy_request($reqstate, $clientip, $res->{proxy}, $method,
475 $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params});
480 PVE::REST::prepare_response_data($format, $res);
481 my ($raw, $ct, $nocomp) = PVE::REST::format_response_data($format, $res, $path);
483 my $resp = HTTP::Response->new($res->{status}, $res->{message});
484 $resp->header("Content-Type
" => $ct);
485 $resp->content($raw);
486 $self->response($reqstate, $resp, $nocomp);
489 $self->error($reqstate, 501, $err);
493 sub handle_spice_proxy_request {
494 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
498 my $rpcenv = $self->{rpcenv};
499 $rpcenv->init_request();
503 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
504 $remip = PVE::Cluster::remote_node_ip($node);
505 die "unable to get remote IP address
for node
'$node'\n" if !$remip;
506 print "REMOTE CONNECT
$vmid, $remip, $connect_str\n" if $self->{debug};
508 print "$$: CONNECT
$vmid, $node, $spiceport\n" if $self->{debug};
511 $reqstate->{hdl}->timeout(0);
512 $reqstate->{hdl}->wbuf_max(64*10*1024);
514 my $remhost = $remip ? $remip : "127.0.0.1";
515 my $remport = $remip ? 3128 : $spiceport;
517 tcp_connect $remhost, $remport, sub {
519 or die "connect to
'$remhost:$remport' failed
: $!";
521 print "$$: CONNECTed to
'$remhost:$remport'\n" if $self->{debug};
522 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
525 wbuf_max => 64*10*1024,
530 $self->log_aborted_request($reqstate);
531 $self->client_do_disconnect($reqstate);
533 if (my $err = $@) { syslog('err', $err); }
536 my ($hdl, $fatal, $message) = @_;
538 $self->log_aborted_request($reqstate, $message);
539 $self->client_do_disconnect($reqstate);
541 if (my $err = $@) { syslog('err', "$err"); }
545 my $proxyhdlreader = sub {
548 my $len = length($hdl->{rbuf});
549 my $data = substr($hdl->{rbuf}, 0, $len, '');
551 #print "READ1
$len\n";
552 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
555 my $hdlreader = sub {
558 my $len = length($hdl->{rbuf});
559 my $data = substr($hdl->{rbuf}, 0, $len, '');
561 #print "READ0
$len\n";
562 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
565 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
567 my $startproxy = sub {
568 $reqstate->{proxyhdl}->timeout(0);
569 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
570 $reqstate->{hdl}->on_read($hdlreader);
572 # todo: use stop_read/start_read if write buffer grows to much
574 my $res = "$proto 200 OK
\015\012"; # hope this is the right answer?
575 $reqstate->{hdl}->push_write($res);
578 $reqstate->{log}->{code} = 200;
579 $self->log_request($reqstate);
583 my $header = "CONNECT
${connect_str
} $proto\015\012" .
584 "Host
: ${connect_str
}\015\012" .
585 "Proxy-Connection
: keep-alive
\015\012" .
586 "User-Agent
: spiceproxy
\015\012" .
588 $reqstate->{proxyhdl}->push_write($header);
589 $reqstate->{proxyhdl}->push_read(line => sub {
590 my ($hdl, $line) = @_;
592 if ($line =~ m!^$proto 200 OK$!) {
595 $reqstate->{hdl}->push_write($line);
596 $self->client_do_disconnect($reqstate);
606 $self->log_aborted_request($reqstate, $err);
607 $self->client_do_disconnect($reqstate);
612 my ($self, $reqstate, $auth) = @_;
615 my $r = $reqstate->{request};
616 my $method = $r->method();
617 my $path = $r->uri->path();
619 # disable timeout on handle (we already have all data we need)
620 # we re-enable timeout in response()
621 $reqstate->{hdl}->timeout(0);
623 if ($path =~ m!$baseuri!) {
624 $self->handle_api2_request($reqstate, $auth);
628 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
629 if (ref($handler) eq 'CODE') {
630 my $params = decode_urlencoded($r->url->query());
631 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
632 $self->response($reqstate, $resp);
633 } elsif (ref($handler) eq 'HASH') {
634 if (my $filename = $handler->{file}) {
635 my $fh = IO::File->new($filename) ||
636 die "unable to
open file
'$filename' - $!\n";
637 send_file_start($self, $reqstate, $filename);
639 die "internal error
- no handler
";
642 die "internal error
- no handler
";
647 if ($self->{dirs} && ($method eq 'GET')) {
648 # we only allow simple names
649 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
650 my ($subdir, $file) = ($1, $2);
651 if (my $dir = $self->{dirs}->{$subdir}) {
652 my $filename = "$dir$file";
653 my $fh = IO::File->new($filename) ||
654 die "unable to
open file
'$filename' - $!\n";
655 send_file_start($self, $reqstate, $filename);
661 die "no such file
'$path'";
664 $self->error($reqstate, 501, $err);
668 sub file_upload_multipart {
669 my ($self, $reqstate, $auth, $rstate) = @_;
672 my $boundary = $rstate->{boundary};
673 my $hdl = $reqstate->{hdl};
675 my $startlen = length($hdl->{rbuf});
677 if ($rstate->{phase} == 0) { # skip everything until start
678 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
679 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
681 my ($ct, $disp, $name, $filename);
682 foreach my $line (split(/\015?\012/, $header)) {
683 # assume we have single line headers
684 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
685 $ct = parse_content_type($1);
686 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
687 ($disp, $name, $filename) = parse_content_disposition($1);
691 if (!($disp && $disp eq 'form-data' && $name)) {
692 syslog('err', "wrong content disposition
in multipart
- abort upload
");
693 $rstate->{phase} = -1;
696 $rstate->{fieldname} = $name;
699 if ($name eq 'filename') {
700 # found file upload data
701 $rstate->{phase} = 1;
702 $rstate->{filename} = $filename;
704 syslog('err', "wrong field name
for file upload
- abort upload
");
705 $rstate->{phase} = -1;
708 # found form data for field $name
709 $rstate->{phase} = 2;
713 my $len = length($hdl->{rbuf});
714 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
715 if $len > $rstate->{maxheader}; # skip garbage
717 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
718 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
719 my ($rest, $eof) = ($1, $3);
720 my $len = length($rest);
721 die "write to temporary file failed
- $!"
722 if syswrite($rstate->{outfh}, $rest) != $len;
723 $rstate->{ctx}->add($rest);
724 $rstate->{params}->{filename} = $rstate->{filename};
725 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
726 $rstate->{bytes} += $len;
727 $rstate->{phase} = $eof ? 100 : 0;
729 my $len = length($hdl->{rbuf});
730 my $wlen = $len - $rstate->{boundlen};
732 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
733 die "write to temporary file failed
- $!"
734 if syswrite($rstate->{outfh}, $data) != $wlen;
735 $rstate->{bytes} += $wlen;
736 $rstate->{ctx}->add($data);
739 } elsif ($rstate->{phase} == 2) { # inside normal field
741 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
742 my ($rest, $eof) = ($1, $3);
743 my $len = length($rest);
744 $rstate->{post_size} += $len;
745 if ($rstate->{post_size} < $limit_max_post) {
746 $rstate->{params}->{$rstate->{fieldname}} = $rest;
747 $rstate->{phase} = $eof ? 100 : 0;
749 syslog('err', "form data to large
- abort upload
");
750 $rstate->{phase} = -1; # skip
754 my $len = length($hdl->{rbuf});
755 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
758 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
760 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
761 $rstate->{done} = 1; # make sure we dont get called twice
762 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
763 die "upload failed
\n";
765 my $elapsed = tv_interval($rstate->{starttime});
767 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
768 syslog('info', "multipart upload complete
" .
769 "(size
: %d time: %ds rate
: %.2fMiB
/s md5sum
: $rstate->{md5sum
})",
770 $rstate->{bytes}, $elapsed, $rate);
771 $self->handle_api2_request($reqstate, $auth, $rstate);
777 $self->error($reqstate, 501, $err);
781 sub parse_content_type {
784 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
786 foreach my $v (@params) {
787 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
788 return wantarray ? ($ct, $1) : $ct;
792 return wantarray ? ($ct) : $ct;
795 sub parse_content_disposition {
798 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
802 foreach my $v (@params) {
803 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
805 $name =~ s/^"(.*)"$/$1/;
806 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
808 $filename =~ s/^"(.*)"$/$1/;
812 return wantarray ? ($disp, $name, $filename) : $disp;
815 my $tmpfile_seq_no = 0;
817 sub get_upload_filename {
818 # choose unpredictable tmpfile name
821 return "/var/tmp
/pveupload-
" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
824 sub unshift_read_header {
825 my ($self, $reqstate, $state) = @_;
827 $state = { size => 0, count => 0 } if !$state;
829 $reqstate->{hdl}->unshift_read(line => sub {
830 my ($hdl, $line) = @_;
833 # print "$$: got header
: $line\n" if $self->{debug};
835 die "to many http header lines
\n" if ++$state->{count} >= $limit_max_headers;
836 die "http header too large
\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
838 my $r = $reqstate->{request};
841 my $path = $r->uri->path();
842 my $method = $r->method();
844 $r->push_header($state->{key}, $state->{val})
847 if (!$known_methods->{$method}) {
848 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available
");
849 $self->response($reqstate, $resp);
853 my $conn = $r->header('Connection');
854 my $accept_enc = $r->header('Accept-Encoding');
855 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
858 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
860 if ($reqstate->{proto}->{ver} < 1001) {
861 $reqstate->{keep_alive} = 0;
865 my $te = $r->header('Transfer-Encoding');
866 if ($te && lc($te) eq 'chunked') {
867 # Handle chunked transfer encoding
868 $self->error($reqstate, 501, "chunked transfer encoding
not supported
");
871 $self->error($reqstate, 501, "Unknown transfer encoding
'$te'");
875 my $pveclientip = $r->header('PVEClientIP');
877 # fixme: how can we make PVEClientIP header trusted?
878 if ($self->{trusted_env} && $pveclientip) {
879 $reqstate->{peer_host} = $pveclientip;
881 $r->header('PVEClientIP', $reqstate->{peer_host});
884 my $len = $r->header('Content-Length');
886 # header processing complete - authenticate now
889 if ($self->{spiceproxy}) {
890 my $connect_str = $r->header('Host');
891 my ($vmid, $node, $port) = PVE::AccessControl::verify_spice_connect_url($connect_str);
892 if (!($vmid && $node && $port)) {
893 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket
");
896 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
898 } elsif ($path =~ m!$baseuri!) {
899 my $token = $r->header('CSRFPreventionToken');
900 my $cookie = $r->header('Cookie');
901 my $ticket = PVE::REST::extract_auth_cookie($cookie);
903 my ($rel_uri, $format) = split_abs_uri($path);
905 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri
");
910 $auth = PVE::REST::auth_handler($self->{rpcenv}, $reqstate->{peer_host}, $method,
911 $rel_uri, $ticket, $token);
914 $self->error($reqstate, HTTP_UNAUTHORIZED, $err);
919 $reqstate->{log}->{userid} = $auth->{userid};
923 if (!($method eq 'PUT' || $method eq 'POST')) {
924 $self->error($reqstate, 501, "Unexpected content
for method '$method'");
928 my $ctype = $r->header('Content-Type');
929 my ($ct, $boundary) = parse_content_type($ctype) if $ctype;
931 if ($auth->{isUpload} && !$self->{trusted_env}) {
932 die "upload
'Content-Type '$ctype' not implemented\n"
933 if !($boundary && $ct && ($ct eq 'multipart
/form-data
'));
935 die "upload without content length header not supported" if !$len;
937 die "upload without content length header not supported" if !$len;
939 print "start upload $path $ct $boundary\n" if $self->{debug};
941 my $tmpfilename = get_upload_filename();
942 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
943 die "unable to create temporary upload file '$tmpfilename'";
945 $reqstate->{keep_alive} = 0;
947 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
951 boundary => $boundary,
952 ctx => Digest::MD5->new,
953 boundlen => $boundlen,
954 maxheader => 2048 + $boundlen, # should be large enough
955 params => decode_urlencoded($r->url->query()),
959 starttime => [gettimeofday],
962 $reqstate->{tmpfilename} = $tmpfilename;
963 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $state); });
967 if ($len > $limit_max_post) {
968 $self->error($reqstate, 501, "for data too large");
972 if (!$ct || $ct eq 'application
/x-www-form-urlencoded
') {
973 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
974 my ($hdl, $data) = @_;
976 $self->handle_request($reqstate, $auth);
979 $self->error($reqstate, 506, "upload 'Content-Type
'$ctype' not implemented
");
982 $self->handle_request($reqstate, $auth);
984 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
985 $r->push_header($state->{key}, $state->{val}) if $state->{key};
986 ($state->{key}, $state->{val}) = ($1, $2);
987 $self->unshift_read_header($reqstate, $state);
988 } elsif ($line =~ /^\s+(.*)/) {
989 $state->{val} .= " $1";
990 $self->unshift_read_header($reqstate, $state);
992 $self->error($reqstate, 506, "unable to parse request header
");
999 sub push_request_header {
1000 my ($self, $reqstate) = @_;
1003 $reqstate->{hdl}->push_read(line => sub {
1004 my ($hdl, $line) = @_;
1007 # print "got request header
: $line\n" if $self->{debug};
1009 $reqstate->{keep_alive}--;
1011 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1012 my ($method, $uri, $maj, $min) = ($1, $2, $3, $4);
1015 $self->error($reqstate, 506, "http protocol version
$maj.$min not supported
");
1019 $self->{request_count}++; # only count valid request headers
1020 if ($self->{request_count} >= $self->{max_requests}) {
1021 $self->{end_loop} = 1;
1023 $reqstate->{log} = { requestline => $line };
1024 $reqstate->{proto}->{str} = "HTTP
/$maj.$min";
1025 $reqstate->{proto}->{maj} = $maj;
1026 $reqstate->{proto}->{min} = $min;
1027 $reqstate->{proto}->{ver} = $maj*1000+$min;
1028 $reqstate->{request} = HTTP::Request->new($method, $uri);
1030 $self->unshift_read_header($reqstate);
1031 } elsif ($line eq '') {
1032 # ignore empty lines before requests (browser bugs?)
1033 $self->push_request_header($reqstate);
1035 $self->error($reqstate, 400, 'bad request');
1049 return if $self->{end_loop};
1051 # we need to m make sure that only one process calls accept
1052 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1053 next if $! == EINTR;
1054 die "could
not get
lock on file
'$self->{lockfile}' - $!\n";
1060 while (!$self->{end_loop} &&
1061 !defined($clientfh = $self->{socket}->accept()) &&
1064 if ($self->{end_loop}) {
1067 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1068 if (!defined($clientfh)) {
1069 $errmsg = "failed to
accept connection
: $!\n";
1075 flock($self->{lockfh}, Fcntl::LOCK_UN());
1077 if (!defined($clientfh)) {
1079 die $errmsg if $errmsg;
1082 fh_nonblocking $clientfh, 1;
1084 $self->{conn_count}++;
1092 $self->{end_loop} = 1;
1094 undef $self->{socket_watch};
1096 if ($self->{conn_count} <= 0) {
1097 $self->{end_cond}->send(1);
1101 # else we need to wait until all open connections gets closed
1102 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1104 # todo: test for active connections instead (we can abort idle connections)
1105 if ($self->{conn_count} <= 0) {
1107 $self->{end_cond}->send(1);
1115 sub check_host_access {
1116 my ($self, $clientip) = @_;
1118 my $cip = Net::IP->new($clientip);
1120 my $match_allow = 0;
1123 if ($self->{allow_from}) {
1124 foreach my $t (@{$self->{allow_from}}) {
1125 if ($t->overlaps($cip)) {
1132 if ($self->{deny_from}) {
1133 foreach my $t (@{$self->{deny_from}}) {
1134 if ($t->overlaps($cip)) {
1141 if ($match_allow == $match_deny) {
1142 # match both allow and deny, or no match
1143 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1146 return $match_allow;
1149 sub accept_connections {
1154 while (my $clientfh = $self->accept()) {
1156 my $reqstate = { keep_alive => $self->{keep_alive} };
1158 # stop keep-alive when there are many open connections
1159 if ($self->{conn_count} >= $self->{max_conn_soft_limit}) {
1160 $reqstate->{keep_alive} = 0;
1163 if (my $sin = getpeername($clientfh)) {
1164 my ($pport, $phost) = Socket::unpack_sockaddr_in($sin);
1165 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntoa($phost));
1168 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1169 print "$$: ABORT request from
$reqstate->{peer_host
} - access denied
\n" if $self->{debug};
1170 $reqstate->{log}->{code} = 403;
1171 $self->log_request($reqstate);
1175 $reqstate->{hdl} = AnyEvent::Handle->new(
1177 rbuf_max => 64*1024,
1178 timeout => $self->{timeout},
1179 linger => 0, # avoid problems with ssh - really needed ?
1183 $self->log_aborted_request($reqstate);
1184 $self->client_do_disconnect($reqstate);
1186 if (my $err = $@) { syslog('err', $err); }
1189 my ($hdl, $fatal, $message) = @_;
1191 $self->log_aborted_request($reqstate, $message);
1192 $self->client_do_disconnect($reqstate);
1194 if (my $err = $@) { syslog('err', "$err"); }
1196 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1198 print "$$: ACCEPT FH
" . $clientfh->fileno() . " CONN
$self->{conn_count
}\n" if $self->{debug};
1200 $self->push_request_header($reqstate);
1205 syslog('err', $err);
1206 $self->{end_loop} = 1;
1209 $self->wait_end_loop() if $self->{end_loop};
1212 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1213 # because we write from multiple processes, and that would arbitrarily mix output
1215 sub open_access_log {
1216 my ($self, $filename) = @_;
1218 my $old_mask = umask(0137);;
1219 my $logfh = IO::File->new($filename, ">>") ||
1220 die "unable to
open log file
'$filename' - $!\n";
1223 $logfh->autoflush(1);
1225 $self->{logfh} = $logfh;
1229 my ($self, $data) = @_;
1231 return if !defined($self->{logfh}) || !$data;
1233 my $res = $self->{logfh}->print($data);
1236 delete $self->{logfh};
1237 syslog('err', "error writing access
log");
1238 $self->{end_loop} = 1; # terminate asap
1242 sub atfork_handler {
1246 # something else do to ?
1247 close($self->{socket});
1253 my ($this, %args) = @_;
1255 my $class = ref($this) || $this;
1257 foreach my $req (qw(socket lockfh lockfile)) {
1258 die "misssing required argument '$req'" if !defined($args{$req});
1261 my $self = bless { %args }, $class;
1264 PVE
::INotify
::inotify_init
();
1266 $self->{rpcenv
} = PVE
::RPCEnvironment-
>init(
1267 $self->{trusted_env
} ?
'priv' : 'pub', atfork
=> sub { $self-> atfork_handler
() });
1269 fh_nonblocking
($self->{socket}, 1);
1271 $self->{end_loop
} = 0;
1272 $self->{conn_count
} = 0;
1273 $self->{request_count
} = 0;
1274 $self->{timeout
} = 5 if !$self->{timeout
};
1275 $self->{keep_alive
} = 0 if !defined($self->{keep_alive
});
1276 $self->{max_conn
} = 800 if !$self->{max_conn
};
1277 $self->{max_requests
} = 8000 if !$self->{max_requests
};
1279 $self->{policy
} = 'allow' if !$self->{policy
};
1281 $self->{end_cond
} = AnyEvent-
>condvar;
1284 $self->{tls_ctx
} = AnyEvent
::TLS-
>new(%{$self->{ssl
}});
1287 if ($self->{spiceproxy
}) {
1288 $known_methods = { CONNECT
=> 1 };
1291 $self->open_access_log($self->{logfile
}) if $self->{logfile
};
1293 $self->{max_conn_soft_limit
} = $self->{max_conn
} > 100 ?
$self->{max_conn
} - 20 : $self->{max_conn
};
1295 $self->{socket_watch
} = AnyEvent-
>io(fh
=> $self->{socket}, poll
=> 'r', cb
=> sub {
1297 if ($self->{conn_count
} >= $self->{max_conn
}) {
1298 my $w; $w = AnyEvent-
>timer (after
=> 1, interval
=> 1, cb
=> sub {
1299 if ($self->{conn_count
} < $self->{max_conn
}) {
1301 $self->accept_connections();
1305 $self->accept_connections();
1311 $self->{term_watch
} = AnyEvent-
>signal(signal
=> "TERM", cb
=> sub {
1312 undef $self->{term_watch
};
1313 $self->wait_end_loop();
1316 $self->{quit_watch
} = AnyEvent-
>signal(signal
=> "QUIT", cb
=> sub {
1317 undef $self->{quit_watch
};
1318 $self->wait_end_loop();
1321 $self->{inotify_poll
} = AnyEvent-
>timer(after
=> 5, interval
=> 5, cb
=> sub {
1322 PVE
::INotify
::poll
(); # read inotify events
1331 $self->{end_cond
}->recv;