]> git.proxmox.com Git - pve-http-server.git/blob - PVE/APIServer/AnyEvent.pm
bump version to 5.1.0
[pve-http-server.git] / PVE / APIServer / AnyEvent.pm
1 package PVE::APIServer::AnyEvent;
2
3 # Note 1: interactions with Crypt::OpenSSL::RSA
4 #
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();
9
10 use strict;
11 use warnings;
12 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
13 use Socket qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
14 use POSIX qw(strftime EINTR EAGAIN);
15 use Fcntl;
16 use IO::File;
17 use File::stat qw();
18 use File::Find;
19 use MIME::Base64;
20 use Digest::MD5;
21 use Digest::SHA;
22 # use AnyEvent::Strict; # only use this for debugging
23 use AnyEvent::Util qw(guard fh_nonblocking WSAEWOULDBLOCK WSAEINPROGRESS);
24 use AnyEvent::Socket;
25 use AnyEvent::Handle;
26 use Net::SSLeay;
27 use AnyEvent::TLS;
28 use AnyEvent::IO;
29 use AnyEvent::HTTP;
30 use Fcntl ();
31 use Compress::Zlib;
32 use Encode;
33 use PVE::SafeSyslog;
34 use PVE::INotify;
35 use PVE::Tools;
36 use PVE::APIServer::Formatter;
37
38 use Net::IP;
39 use URI;
40 use URI::Escape;
41 use HTTP::Status qw(:constants);
42 use HTTP::Date;
43 use HTTP::Headers;
44 use HTTP::Request;
45 use HTTP::Response;
46 use Data::Dumper;
47
48 my $limit_max_headers = 30;
49 my $limit_max_header_size = 8*1024;
50 my $limit_max_post = 64*1024;
51
52 my $known_methods = {
53 GET => 1,
54 POST => 1,
55 PUT => 1,
56 DELETE => 1,
57 };
58
59 my $split_abs_uri = sub {
60 my ($abs_uri, $base_uri) = @_;
61
62 my ($format, $rel_uri) = $abs_uri =~ m/^\Q$base_uri\E\/+([a-z][a-z0-9]+)(\/.*)?$/;
63 $rel_uri = '/' if !$rel_uri;
64
65 return wantarray ? ($rel_uri, $format) : $rel_uri;
66 };
67
68 sub log_request {
69 my ($self, $reqstate) = @_;
70
71 my $loginfo = $reqstate->{log};
72
73 # like apache2 common log format
74 # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
75
76 return if $loginfo->{written}; # avoid duplicate logs
77 $loginfo->{written} = 1;
78
79 my $peerip = $reqstate->{peer_host} || '-';
80 my $userid = $loginfo->{userid} || '-';
81 my $content_length = defined($loginfo->{content_length}) ? $loginfo->{content_length} : '-';
82 my $code = $loginfo->{code} || 500;
83 my $requestline = $loginfo->{requestline} || '-';
84 my $timestr = strftime("%d/%m/%Y:%H:%M:%S %z", localtime());
85
86 my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n";
87
88 $self->write_log($msg);
89 }
90
91 sub log_aborted_request {
92 my ($self, $reqstate, $error) = @_;
93
94 my $r = $reqstate->{request};
95 return if !$r; # no active request
96
97 if ($error) {
98 syslog("err", "problem with client $reqstate->{peer_host}; $error");
99 }
100
101 $self->log_request($reqstate);
102 }
103
104 sub cleanup_reqstate {
105 my ($reqstate) = @_;
106
107 delete $reqstate->{log};
108 delete $reqstate->{request};
109 delete $reqstate->{proto};
110 delete $reqstate->{accept_gzip};
111 delete $reqstate->{starttime};
112
113 if ($reqstate->{tmpfilename}) {
114 unlink $reqstate->{tmpfilename};
115 delete $reqstate->{tmpfilename};
116 }
117 }
118
119 sub client_do_disconnect {
120 my ($self, $reqstate) = @_;
121
122 cleanup_reqstate($reqstate);
123
124 my $shutdown_hdl = sub {
125 my $hdl = shift;
126
127 shutdown($hdl->{fh}, 1);
128 # clear all handlers
129 $hdl->on_drain(undef);
130 $hdl->on_read(undef);
131 $hdl->on_eof(undef);
132 };
133
134 if (my $proxyhdl = delete $reqstate->{proxyhdl}) {
135 &$shutdown_hdl($proxyhdl);
136 }
137
138 my $hdl = delete $reqstate->{hdl};
139
140 if (!$hdl) {
141 syslog('err', "detected empty handle");
142 return;
143 }
144
145 print "close connection $hdl\n" if $self->{debug};
146
147 &$shutdown_hdl($hdl);
148
149 $self->{conn_count}--;
150
151 print "$$: CLOSE FH" . $hdl->{fh}->fileno() . " CONN$self->{conn_count}\n" if $self->{debug};
152 }
153
154 sub finish_response {
155 my ($self, $reqstate) = @_;
156
157 cleanup_reqstate($reqstate);
158
159 my $hdl = $reqstate->{hdl};
160 return if !$hdl; # already disconnected
161
162 if (!$self->{end_loop} && $reqstate->{keep_alive} > 0) {
163 # print "KEEPALIVE $reqstate->{keep_alive}\n" if $self->{debug};
164 $hdl->on_read(sub {
165 eval { $self->push_request_header($reqstate); };
166 warn $@ if $@;
167 });
168 } else {
169 $hdl->on_drain (sub {
170 eval {
171 $self->client_do_disconnect($reqstate);
172 };
173 warn $@ if $@;
174 });
175 }
176 }
177
178 sub response {
179 my ($self, $reqstate, $resp, $mtime, $nocomp, $delay) = @_;
180
181 #print "$$: send response: " . Dumper($resp);
182
183 # activate timeout
184 $reqstate->{hdl}->timeout_reset();
185 $reqstate->{hdl}->timeout($self->{timeout});
186
187 $nocomp = 1 if !$self->{compression};
188 $nocomp = 1 if !$reqstate->{accept_gzip};
189
190 my $code = $resp->code;
191 my $msg = $resp->message || HTTP::Status::status_message($code);
192 ($msg) = $msg =~m/^(.*)$/m;
193 my $content = $resp->content;
194
195 if ($code =~ /^(1\d\d|[23]04)$/) {
196 # make sure content we have no content
197 $content = "";
198 }
199
200 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
201
202 $reqstate->{log}->{code} = $code;
203
204 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
205 my $res = "$proto $code $msg\015\012";
206
207 my $ctime = time();
208 my $date = HTTP::Date::time2str($ctime);
209 $resp->header('Date' => $date);
210 if ($mtime) {
211 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
212 } else {
213 $resp->header('Expires' => $date);
214 $resp->header('Cache-Control' => "max-age=0");
215 $resp->header("Pragma", "no-cache");
216 }
217
218 $resp->header('Server' => "pve-api-daemon/3.0");
219
220 my $content_length;
221 if ($content) {
222
223 $content_length = length($content);
224
225 if (!$nocomp && ($content_length > 1024)) {
226 my $comp = Compress::Zlib::memGzip($content);
227 $resp->header('Content-Encoding', 'gzip');
228 $content = $comp;
229 $content_length = length($content);
230 }
231 $resp->header("Content-Length" => $content_length);
232 $reqstate->{log}->{content_length} = $content_length;
233
234 } else {
235 $resp->remove_header("Content-Length");
236 }
237
238 if ($reqstate->{keep_alive} > 0) {
239 $resp->push_header('Connection' => 'Keep-Alive');
240 } else {
241 $resp->header('Connection' => 'close');
242 }
243
244 $res .= $resp->headers_as_string("\015\012");
245 #print "SEND(without content) $res\n" if $self->{debug};
246
247 $res .= "\015\012";
248 $res .= $content if $content;
249
250 $self->log_request($reqstate, $reqstate->{request});
251
252 if ($delay && $delay > 0) {
253 my $w; $w = AnyEvent->timer(after => $delay, cb => sub {
254 undef $w; # delete reference
255 $reqstate->{hdl}->push_write($res);
256 $self->finish_response($reqstate);
257 });
258 } else {
259 $reqstate->{hdl}->push_write($res);
260 $self->finish_response($reqstate);
261 }
262 }
263
264 sub error {
265 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
266
267 eval {
268 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
269 $self->response($reqstate, $resp);
270 };
271 warn $@ if $@;
272 }
273
274 my $file_extension_info = {
275 css => { ct => 'text/css' },
276 html => { ct => 'text/html' },
277 js => { ct => 'application/javascript' },
278 json => { ct => 'application/json' },
279 map => { ct => 'application/json' },
280 png => { ct => 'image/png' , nocomp => 1 },
281 ico => { ct => 'image/x-icon', nocomp => 1},
282 gif => { ct => 'image/gif', nocomp => 1},
283 svg => { ct => 'image/svg+xml' },
284 jar => { ct => 'application/java-archive', nocomp => 1},
285 woff => { ct => 'application/font-woff', nocomp => 1},
286 woff2 => { ct => 'application/font-woff2', nocomp => 1},
287 ttf => { ct => 'application/font-snft', nocomp => 1},
288 pdf => { ct => 'application/pdf', nocomp => 1},
289 epub => { ct => 'application/epub+zip', nocomp => 1},
290 mp3 => { ct => 'audio/mpeg', nocomp => 1},
291 oga => { ct => 'audio/ogg', nocomp => 1},
292 tgz => { ct => 'application/x-compressed-tar', nocomp => 1},
293 };
294
295 sub send_file_start {
296 my ($self, $reqstate, $download) = @_;
297
298 eval {
299 # print "SEND FILE $filename\n";
300 # Note: aio_load() this is not really async unless we use IO::AIO!
301 eval {
302
303 my $r = $reqstate->{request};
304
305 my $fh;
306 my $nocomp;
307 my $mime;
308
309 if (ref($download) eq 'HASH') {
310 $fh = $download->{fh};
311 $mime = $download->{'content-type'};
312 } else {
313 my $filename = $download;
314 $fh = IO::File->new($filename, '<') ||
315 die "unable to open file '$filename' - $!\n";
316
317 my ($ext) = $filename =~ m/\.([^.]*)$/;
318 my $ext_info = $file_extension_info->{$ext};
319
320 die "unable to detect content type" if !$ext_info;
321 $mime = $ext_info->{ct};
322 $nocomp = $ext_info->{nocomp};
323 }
324
325 my $stat = File::stat::stat($fh) ||
326 die "$!\n";
327
328 my $mtime = $stat->mtime;
329
330 if (my $ifmod = $r->header('if-modified-since')) {
331 my $iftime = HTTP::Date::str2time($ifmod);
332 if ($mtime <= $iftime) {
333 my $resp = HTTP::Response->new(304, "NOT MODIFIED");
334 $self->response($reqstate, $resp, $mtime);
335 return;
336 }
337 }
338
339 my $data;
340 my $len = sysread($fh, $data, $stat->size);
341 die "got short file\n" if !defined($len) || $len != $stat->size;
342
343 my $header = HTTP::Headers->new(Content_Type => $mime);
344 my $resp = HTTP::Response->new(200, "OK", $header, $data);
345 $self->response($reqstate, $resp, $mtime, $nocomp);
346 };
347 if (my $err = $@) {
348 $self->error($reqstate, 501, $err);
349 }
350 };
351
352 warn $@ if $@;
353 }
354
355 sub websocket_proxy {
356 my ($self, $reqstate, $wsaccept, $wsproto, $param) = @_;
357
358 eval {
359 my $remhost;
360 my $remport;
361
362 my $max_payload_size = 128*1024;
363
364 my $binary;
365 if ($wsproto eq 'binary') {
366 $binary = 1;
367 } elsif ($wsproto eq 'base64') {
368 $binary = 0;
369 } else {
370 die "websocket_proxy: unsupported protocol '$wsproto'\n";
371 }
372
373 if ($param->{port}) {
374 $remhost = 'localhost';
375 $remport = $param->{port};
376 } elsif ($param->{socket}) {
377 $remhost = 'unix/';
378 $remport = $param->{socket};
379 } else {
380 die "websocket_proxy: missing port or socket\n";
381 }
382
383 tcp_connect $remhost, $remport, sub {
384 my ($fh) = @_
385 or die "connect to '$remhost:$remport' failed: $!";
386
387 print "$$: CONNECTed to '$remhost:$remport'\n" if $self->{debug};
388
389 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
390 fh => $fh,
391 rbuf_max => $max_payload_size,
392 wbuf_max => $max_payload_size*5,
393 timeout => 5,
394 on_eof => sub {
395 my ($hdl) = @_;
396 eval {
397 $self->log_aborted_request($reqstate);
398 $self->client_do_disconnect($reqstate);
399 };
400 if (my $err = $@) { syslog('err', $err); }
401 },
402 on_error => sub {
403 my ($hdl, $fatal, $message) = @_;
404 eval {
405 $self->log_aborted_request($reqstate, $message);
406 $self->client_do_disconnect($reqstate);
407 };
408 if (my $err = $@) { syslog('err', "$err"); }
409 });
410
411 my $proxyhdlreader = sub {
412 my ($hdl) = @_;
413
414 my $len = length($hdl->{rbuf});
415 my $data = substr($hdl->{rbuf}, 0, $len > $max_payload_size ? $max_payload_size : $len, '');
416
417 my $string;
418 my $payload;
419
420 if ($binary) {
421 $string = "\x82"; # binary frame
422 $payload = $data;
423 } else {
424 $string = "\x81"; # text frame
425 $payload = encode_base64($data, '');
426 }
427
428 my $payload_len = length($payload);
429 if ($payload_len <= 125) {
430 $string .= pack 'C', $payload_len;
431 } elsif ($payload_len <= 0xffff) {
432 $string .= pack 'C', 126;
433 $string .= pack 'n', $payload_len;
434 } else {
435 $string .= pack 'C', 127;
436 $string .= pack 'Q>', $payload_len;
437 }
438 $string .= $payload;
439
440 $reqstate->{hdl}->push_write($string) if $reqstate->{hdl};
441 };
442
443 my $hdlreader = sub {
444 my ($hdl) = @_;
445
446 while (my $len = length($hdl->{rbuf})) {
447 return if $len < 2;
448
449 my $hdr = unpack('C', substr($hdl->{rbuf}, 0, 1));
450 my $opcode = $hdr & 0b00001111;
451 my $fin = $hdr & 0b10000000;
452
453 die "received fragmented websocket frame\n" if !$fin;
454
455 my $rsv = $hdr & 0b01110000;
456 die "received websocket frame with RSV flags\n" if $rsv;
457
458 my $payload_len = unpack 'C', substr($hdl->{rbuf}, 1, 1);
459
460 my $masked = $payload_len & 0b10000000;
461 die "received unmasked websocket frame from client\n" if !$masked;
462
463 my $offset = 2;
464 $payload_len = $payload_len & 0b01111111;
465 if ($payload_len == 126) {
466 return if $len < 4;
467 $payload_len = unpack('n', substr($hdl->{rbuf}, $offset, 2));
468 $offset += 2;
469 } elsif ($payload_len == 127) {
470 return if $len < 10;
471 $payload_len = unpack('Q>', substr($hdl->{rbuf}, $offset, 8));
472 $offset += 8;
473 }
474
475 die "received too large websocket frame (len = $payload_len)\n"
476 if ($payload_len > $max_payload_size) || ($payload_len < 0);
477
478 return if $len < ($offset + 4 + $payload_len);
479
480 my $data = substr($hdl->{rbuf}, 0, $offset + 4 + $payload_len, ''); # now consume data
481
482 my @mask = (unpack('C', substr($data, $offset+0, 1)),
483 unpack('C', substr($data, $offset+1, 1)),
484 unpack('C', substr($data, $offset+2, 1)),
485 unpack('C', substr($data, $offset+3, 1)));
486
487 $offset += 4;
488
489 my $payload = substr($data, $offset, $payload_len);
490
491 for (my $i = 0; $i < $payload_len; $i++) {
492 my $d = unpack('C', substr($payload, $i, 1));
493 my $n = $d ^ $mask[$i % 4];
494 substr($payload, $i, 1, pack('C', $n));
495 }
496
497 $payload = decode_base64($payload) if !$binary;
498
499 if ($opcode == 1 || $opcode == 2) {
500 $reqstate->{proxyhdl}->push_write($payload) if $reqstate->{proxyhdl};
501 } elsif ($opcode == 8) {
502 my $statuscode = unpack ("n", $payload);
503 print "websocket received close. status code: '$statuscode'\n" if $self->{debug};
504 if ($reqstate->{proxyhdl}) {
505 $reqstate->{proxyhdl}->push_shutdown();
506 }
507 $hdl->push_shutdown();
508 } else {
509 die "received unhandled websocket opcode $opcode\n";
510 }
511 }
512 };
513
514 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.1';
515
516 $reqstate->{proxyhdl}->timeout(0);
517 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
518 $reqstate->{hdl}->on_read($hdlreader);
519
520 # todo: use stop_read/start_read if write buffer grows to much
521
522 my $res = "$proto 101 Switching Protocols\015\012" .
523 "Upgrade: websocket\015\012" .
524 "Connection: upgrade\015\012" .
525 "Sec-WebSocket-Accept: $wsaccept\015\012" .
526 "Sec-WebSocket-Protocol: $wsproto\015\012" .
527 "\015\012";
528
529 print $res if $self->{debug};
530
531 $reqstate->{hdl}->push_write($res);
532
533 # log early
534 $reqstate->{log}->{code} = 101;
535 $self->log_request($reqstate);
536 };
537
538 };
539 if (my $err = $@) {
540 warn $err;
541 $self->log_aborted_request($reqstate, $err);
542 $self->client_do_disconnect($reqstate);
543 }
544 }
545
546 sub proxy_request {
547 my ($self, $reqstate, $clientip, $host, $node, $method, $uri, $ticket, $token, $params) = @_;
548
549 eval {
550 my $target;
551 my $keep_alive = 1;
552 if ($host eq 'localhost') {
553 $target = "http://$host:85$uri";
554 # keep alive for localhost is not worth (connection setup is about 0.2ms)
555 $keep_alive = 0;
556 } elsif (Net::IP::ip_is_ipv6($host)) {
557 $target = "https://[$host]:8006$uri";
558 } else {
559 $target = "https://$host:8006$uri";
560 }
561
562 my $headers = {
563 PVEDisableProxy => 'true',
564 PVEClientIP => $clientip,
565 };
566
567 $headers->{'cookie'} = PVE::APIServer::Formatter::create_auth_cookie($ticket, $self->{cookie_name}) if $ticket;
568 $headers->{'CSRFPreventionToken'} = $token if $token;
569 $headers->{'Accept-Encoding'} = 'gzip' if ($reqstate->{accept_gzip} && $self->{compression});
570
571 if (defined(my $host = $reqstate->{request}->header('Host'))) {
572 $headers->{Host} = $host;
573 }
574
575 my $content;
576
577 if ($method eq 'POST' || $method eq 'PUT') {
578 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
579 # use URI object to format application/x-www-form-urlencoded content.
580 my $url = URI->new('http:');
581 $url->query_form(%$params);
582 $content = $url->query;
583 if (defined($content)) {
584 $headers->{'Content-Length'} = length($content);
585 }
586 }
587
588 my $tls = {
589 # TLS 1.x only, with certificate pinning
590 method => 'any',
591 sslv2 => 0,
592 sslv3 => 0,
593 verify => 1,
594 # be compatible with openssl 1.1, fix for debian bug #923615
595 # remove once libanyeven-perl with this fix transitions to buster
596 dh => 'schmorp2048',
597 verify_cb => sub {
598 my (undef, undef, undef, $depth, undef, undef, $cert) = @_;
599 # we don't care about intermediate or root certificates
600 return 1 if $depth != 0;
601 # check server certificate against cache of pinned FPs
602 return $self->check_cert_fingerprint($cert);
603 },
604 };
605
606 # load and cache cert fingerprint if first time we proxy to this node
607 $self->initialize_cert_cache($node);
608
609 my $w; $w = http_request(
610 $method => $target,
611 headers => $headers,
612 timeout => 30,
613 recurse => 0,
614 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
615 keepalive => $keep_alive,
616 body => $content,
617 tls_ctx => AnyEvent::TLS->new(%{$tls}),
618 sub {
619 my ($body, $hdr) = @_;
620
621 undef $w;
622
623 if (!$reqstate->{hdl}) {
624 warn "proxy detected vanished client connection\n";
625 return;
626 }
627
628 eval {
629 my $code = delete $hdr->{Status};
630 my $msg = delete $hdr->{Reason};
631 delete $hdr->{URL};
632 delete $hdr->{HTTPVersion};
633 my $header = HTTP::Headers->new(%$hdr);
634 if (my $location = $header->header('Location')) {
635 $location =~ s|^http://localhost:85||;
636 $header->header(Location => $location);
637 }
638 my $resp = HTTP::Response->new($code, $msg, $header, $body);
639 # Note: disable compression, because body is already compressed
640 $self->response($reqstate, $resp, undef, 1);
641 };
642 warn $@ if $@;
643 });
644 };
645 warn $@ if $@;
646 }
647
648 # return arrays as \0 separated strings (like CGI.pm)
649 # assume data is UTF8 encoded
650 sub decode_urlencoded {
651 my ($data) = @_;
652
653 my $res = {};
654
655 return $res if !$data;
656
657 foreach my $kv (split(/[\&\;]/, $data)) {
658 my ($k, $v) = split(/=/, $kv);
659 $k =~s/\+/ /g;
660 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
661
662 if (defined($v)) {
663 $v =~s/\+/ /g;
664 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
665
666 $v = Encode::decode('utf8', $v);
667
668 if (defined(my $old = $res->{$k})) {
669 $v = "$old\0$v";
670 }
671 }
672
673 $res->{$k} = $v;
674 }
675 return $res;
676 }
677
678 sub extract_params {
679 my ($r, $method) = @_;
680
681 my $params = {};
682
683 if ($method eq 'PUT' || $method eq 'POST') {
684 $params = decode_urlencoded($r->content);
685 }
686
687 my $query_params = decode_urlencoded($r->url->query());
688
689 foreach my $k (keys %{$query_params}) {
690 $params->{$k} = $query_params->{$k};
691 }
692
693 return $params;
694 }
695
696 sub handle_api2_request {
697 my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
698
699 eval {
700 my $r = $reqstate->{request};
701
702 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
703
704 my $formatter = PVE::APIServer::Formatter::get_formatter($format, $method, $rel_uri);
705
706 if (!defined($formatter)) {
707 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no formatter for uri $rel_uri, $format");
708 return;
709 }
710
711 #print Dumper($upload_state) if $upload_state;
712
713 my $params;
714
715 if ($upload_state) {
716 $params = $upload_state->{params};
717 } else {
718 $params = extract_params($r, $method);
719 }
720
721 delete $params->{_dc}; # remove disable cache parameter
722
723 my $clientip = $reqstate->{peer_host};
724
725 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
726
727 # HACK: see Note 1
728 Net::SSLeay::ERR_clear_error();
729
730 AnyEvent->now_update(); # in case somebody called sleep()
731
732 my $upgrade = $r->header('upgrade');
733 $upgrade = lc($upgrade) if $upgrade;
734
735 if (my $host = $res->{proxy}) {
736
737 if ($self->{trusted_env}) {
738 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy not allowed");
739 return;
740 }
741
742 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
743 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy loop detected");
744 return;
745 }
746
747 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
748
749 $self->proxy_request($reqstate, $clientip, $host, $res->{proxynode}, $method,
750 $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params}, $res->{proxynode});
751 return;
752
753 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
754 die "unable to upgrade to protocol '$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
755 my $wsver = $r->header('sec-websocket-version');
756 die "unsupported websocket-version '$wsver'\n" if !$wsver || ($wsver ne '13');
757 my $wsproto_str = $r->header('sec-websocket-protocol');
758 die "missing websocket-protocol header" if !$wsproto_str;
759 my $wsproto;
760 foreach my $p (PVE::Tools::split_list($wsproto_str)) {
761 $wsproto = $p if !$wsproto && $p eq 'base64';
762 $wsproto = $p if $p eq 'binary';
763 }
764 die "unsupported websocket-protocol protocol '$wsproto_str'\n" if !$wsproto;
765 my $wskey = $r->header('sec-websocket-key');
766 die "missing websocket-key\n" if !$wskey;
767 # Note: Digest::SHA::sha1_base64 has wrong padding
768 my $wsaccept = Digest::SHA::sha1_base64("${wskey}258EAFA5-E914-47DA-95CA-C5AB0DC85B11") . "=";
769 if ($res->{status} == HTTP_OK) {
770 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
771 return;
772 }
773 }
774
775 my $delay = 0;
776 if ($res->{status} == HTTP_UNAUTHORIZED) {
777 # always delay unauthorized calls by 3 seconds
778 $delay = 3 - tv_interval($reqstate->{starttime});
779 $delay = 0 if $delay < 0;
780 }
781
782 if (defined(my $download = $res->{download})) {
783 send_file_start($self, $reqstate, $download);
784 return;
785 }
786
787 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
788 $auth, $self->{formatter_config});
789
790 my $resp;
791 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
792 $resp = $raw;
793 } else {
794 $resp = HTTP::Response->new($res->{status}, $res->{message});
795 $resp->header("Content-Type" => $ct);
796 $resp->content($raw);
797 }
798 $self->response($reqstate, $resp, undef, $nocomp, $delay);
799 };
800 if (my $err = $@) {
801 $self->error($reqstate, 501, $err);
802 }
803 }
804
805 sub handle_spice_proxy_request {
806 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
807
808 eval {
809
810 die "Port $spiceport is not allowed" if ($spiceport < 61000 || $spiceport > 61099);
811
812 my $clientip = $reqstate->{peer_host};
813 my $r = $reqstate->{request};
814
815 my $remip;
816
817 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
818 $remip = $self->remote_node_ip($node);
819 print "REMOTE CONNECT $vmid, $remip, $connect_str\n" if $self->{debug};
820 } else {
821 print "$$: CONNECT $vmid, $node, $spiceport\n" if $self->{debug};
822 }
823
824 if ($remip && $r->header('PVEDisableProxy')) {
825 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy loop detected");
826 return;
827 }
828
829 $reqstate->{hdl}->timeout(0);
830 $reqstate->{hdl}->wbuf_max(64*10*1024);
831
832 my $remhost = $remip ? $remip : "localhost";
833 my $remport = $remip ? 3128 : $spiceport;
834
835 tcp_connect $remhost, $remport, sub {
836 my ($fh) = @_
837 or die "connect to '$remhost:$remport' failed: $!";
838
839 print "$$: CONNECTed to '$remhost:$remport'\n" if $self->{debug};
840 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
841 fh => $fh,
842 rbuf_max => 64*1024,
843 wbuf_max => 64*10*1024,
844 timeout => 5,
845 on_eof => sub {
846 my ($hdl) = @_;
847 eval {
848 $self->log_aborted_request($reqstate);
849 $self->client_do_disconnect($reqstate);
850 };
851 if (my $err = $@) { syslog('err', $err); }
852 },
853 on_error => sub {
854 my ($hdl, $fatal, $message) = @_;
855 eval {
856 $self->log_aborted_request($reqstate, $message);
857 $self->client_do_disconnect($reqstate);
858 };
859 if (my $err = $@) { syslog('err', "$err"); }
860 });
861
862
863 my $proxyhdlreader = sub {
864 my ($hdl) = @_;
865
866 my $len = length($hdl->{rbuf});
867 my $data = substr($hdl->{rbuf}, 0, $len, '');
868
869 #print "READ1 $len\n";
870 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
871 };
872
873 my $hdlreader = sub {
874 my ($hdl) = @_;
875
876 my $len = length($hdl->{rbuf});
877 my $data = substr($hdl->{rbuf}, 0, $len, '');
878
879 #print "READ0 $len\n";
880 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
881 };
882
883 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
884
885 my $startproxy = sub {
886 $reqstate->{proxyhdl}->timeout(0);
887 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
888 $reqstate->{hdl}->on_read($hdlreader);
889
890 # todo: use stop_read/start_read if write buffer grows to much
891
892 # a response must be followed by an empty line
893 my $res = "$proto 200 OK\015\012\015\012";
894 $reqstate->{hdl}->push_write($res);
895
896 # log early
897 $reqstate->{log}->{code} = 200;
898 $self->log_request($reqstate);
899 };
900
901 if ($remip) {
902 my $header = "CONNECT ${connect_str} $proto\015\012" .
903 "Host: ${connect_str}\015\012" .
904 "Proxy-Connection: keep-alive\015\012" .
905 "User-Agent: spiceproxy\015\012" .
906 "PVEDisableProxy: true\015\012" .
907 "PVEClientIP: $clientip\015\012" .
908 "\015\012";
909
910 $reqstate->{proxyhdl}->push_write($header);
911 $reqstate->{proxyhdl}->push_read(line => sub {
912 my ($hdl, $line) = @_;
913
914 if ($line =~ m!^$proto 200 OK$!) {
915 # read the empty line after the 200 OK
916 $reqstate->{proxyhdl}->unshift_read(line => sub{
917 &$startproxy();
918 });
919 } else {
920 $reqstate->{hdl}->push_write($line);
921 $self->client_do_disconnect($reqstate);
922 }
923 });
924 } else {
925 &$startproxy();
926 }
927
928 };
929 };
930 if (my $err = $@) {
931 warn $err;
932 $self->log_aborted_request($reqstate, $err);
933 $self->client_do_disconnect($reqstate);
934 }
935 }
936
937 sub handle_request {
938 my ($self, $reqstate, $auth, $method, $path) = @_;
939
940 my $base_uri = $self->{base_uri};
941
942 eval {
943 my $r = $reqstate->{request};
944
945 # disable timeout on handle (we already have all data we need)
946 # we re-enable timeout in response()
947 $reqstate->{hdl}->timeout(0);
948
949 if ($path =~ m/^\Q$base_uri\E/) {
950 $self->handle_api2_request($reqstate, $auth, $method, $path);
951 return;
952 }
953
954 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
955 if (ref($handler) eq 'CODE') {
956 my $params = decode_urlencoded($r->url->query());
957 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
958 # HACK: see Note 1
959 Net::SSLeay::ERR_clear_error();
960 $self->response($reqstate, $resp);
961 } elsif (ref($handler) eq 'HASH') {
962 if (my $filename = $handler->{file}) {
963 my $fh = IO::File->new($filename) ||
964 die "unable to open file '$filename' - $!\n";
965 send_file_start($self, $reqstate, $filename);
966 } else {
967 die "internal error - no handler";
968 }
969 } else {
970 die "internal error - no handler";
971 }
972 return;
973 }
974
975 if ($self->{dirs} && ($method eq 'GET')) {
976 # we only allow simple names
977 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
978 my ($subdir, $file) = ($1, $2);
979 if (my $dir = $self->{dirs}->{$subdir}) {
980 my $filename = "$dir$file";
981 my $fh = IO::File->new($filename) ||
982 die "unable to open file '$filename' - $!\n";
983 send_file_start($self, $reqstate, $filename);
984 return;
985 }
986 }
987 }
988
989 die "no such file '$path'\n";
990 };
991 if (my $err = $@) {
992 $self->error($reqstate, 501, $err);
993 }
994 }
995
996 sub file_upload_multipart {
997 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
998
999 eval {
1000 my $boundary = $rstate->{boundary};
1001 my $hdl = $reqstate->{hdl};
1002
1003 my $startlen = length($hdl->{rbuf});
1004
1005 if ($rstate->{phase} == 0) { # skip everything until start
1006 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
1007 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
1008 my $header = $1;
1009 my ($ct, $disp, $name, $filename);
1010 foreach my $line (split(/\015?\012/, $header)) {
1011 # assume we have single line headers
1012 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
1013 $ct = parse_content_type($1);
1014 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
1015 ($disp, $name, $filename) = parse_content_disposition($1);
1016 }
1017 }
1018
1019 if (!($disp && $disp eq 'form-data' && $name)) {
1020 syslog('err', "wrong content disposition in multipart - abort upload");
1021 $rstate->{phase} = -1;
1022 } else {
1023
1024 $rstate->{fieldname} = $name;
1025
1026 if ($filename) {
1027 if ($name eq 'filename') {
1028 # found file upload data
1029 $rstate->{phase} = 1;
1030 $rstate->{filename} = $filename;
1031 } else {
1032 syslog('err', "wrong field name for file upload - abort upload");
1033 $rstate->{phase} = -1;
1034 }
1035 } else {
1036 # found form data for field $name
1037 $rstate->{phase} = 2;
1038 }
1039 }
1040 } else {
1041 my $len = length($hdl->{rbuf});
1042 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
1043 if $len > $rstate->{maxheader}; # skip garbage
1044 }
1045 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
1046 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1047 my ($rest, $eof) = ($1, $3);
1048 my $len = length($rest);
1049 die "write to temporary file failed - $!"
1050 if syswrite($rstate->{outfh}, $rest) != $len;
1051 $rstate->{ctx}->add($rest);
1052 $rstate->{params}->{filename} = $rstate->{filename};
1053 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
1054 $rstate->{bytes} += $len;
1055 $rstate->{phase} = $eof ? 100 : 0;
1056 } else {
1057 my $len = length($hdl->{rbuf});
1058 my $wlen = $len - $rstate->{boundlen};
1059 if ($wlen > 0) {
1060 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
1061 die "write to temporary file failed - $!"
1062 if syswrite($rstate->{outfh}, $data) != $wlen;
1063 $rstate->{bytes} += $wlen;
1064 $rstate->{ctx}->add($data);
1065 }
1066 }
1067 } elsif ($rstate->{phase} == 2) { # inside normal field
1068
1069 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1070 my ($rest, $eof) = ($1, $3);
1071 my $len = length($rest);
1072 $rstate->{post_size} += $len;
1073 if ($rstate->{post_size} < $limit_max_post) {
1074 $rstate->{params}->{$rstate->{fieldname}} = $rest;
1075 $rstate->{phase} = $eof ? 100 : 0;
1076 } else {
1077 syslog('err', "form data to large - abort upload");
1078 $rstate->{phase} = -1; # skip
1079 }
1080 }
1081 } else { # skip
1082 my $len = length($hdl->{rbuf});
1083 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
1084 }
1085
1086 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
1087
1088 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
1089 $rstate->{done} = 1; # make sure we dont get called twice
1090 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
1091 die "upload failed\n";
1092 } else {
1093 my $elapsed = tv_interval($rstate->{starttime});
1094
1095 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
1096 syslog('info', "multipart upload complete " .
1097 "(size: %d time: %ds rate: %.2fMiB/s md5sum: $rstate->{md5sum})",
1098 $rstate->{bytes}, $elapsed, $rate);
1099 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1100 }
1101 }
1102 };
1103 if (my $err = $@) {
1104 syslog('err', $err);
1105 $self->error($reqstate, 501, $err);
1106 }
1107 }
1108
1109 sub parse_content_type {
1110 my ($ctype) = @_;
1111
1112 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
1113
1114 foreach my $v (@params) {
1115 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1116 return wantarray ? ($ct, $1) : $ct;
1117 }
1118 }
1119
1120 return wantarray ? ($ct) : $ct;
1121 }
1122
1123 sub parse_content_disposition {
1124 my ($line) = @_;
1125
1126 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
1127 my $name;
1128 my $filename;
1129
1130 foreach my $v (@params) {
1131 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
1132 $name = $1;
1133 $name =~ s/^"(.*)"$/$1/;
1134 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
1135 $filename = $1;
1136 $filename =~ s/^"(.*)"$/$1/;
1137 }
1138 }
1139
1140 return wantarray ? ($disp, $name, $filename) : $disp;
1141 }
1142
1143 my $tmpfile_seq_no = 0;
1144
1145 sub get_upload_filename {
1146 # choose unpredictable tmpfile name
1147
1148 $tmpfile_seq_no++;
1149 return "/var/tmp/pveupload-" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1150 }
1151
1152 sub unshift_read_header {
1153 my ($self, $reqstate, $state) = @_;
1154
1155 $state = { size => 0, count => 0 } if !$state;
1156
1157 $reqstate->{hdl}->unshift_read(line => sub {
1158 my ($hdl, $line) = @_;
1159
1160 eval {
1161 # print "$$: got header: $line\n" if $self->{debug};
1162
1163 die "to many http header lines\n" if ++$state->{count} >= $limit_max_headers;
1164 die "http header too large\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1165
1166 my $r = $reqstate->{request};
1167 if ($line eq '') {
1168
1169 my $path = uri_unescape($r->uri->path());
1170 my $method = $r->method();
1171
1172 $r->push_header($state->{key}, $state->{val})
1173 if $state->{key};
1174
1175 if (!$known_methods->{$method}) {
1176 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available");
1177 $self->response($reqstate, $resp);
1178 return;
1179 }
1180
1181 my $conn = $r->header('Connection');
1182 my $accept_enc = $r->header('Accept-Encoding');
1183 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1184
1185 if ($conn) {
1186 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1187 } else {
1188 if ($reqstate->{proto}->{ver} < 1001) {
1189 $reqstate->{keep_alive} = 0;
1190 }
1191 }
1192
1193 my $te = $r->header('Transfer-Encoding');
1194 if ($te && lc($te) eq 'chunked') {
1195 # Handle chunked transfer encoding
1196 $self->error($reqstate, 501, "chunked transfer encoding not supported");
1197 return;
1198 } elsif ($te) {
1199 $self->error($reqstate, 501, "Unknown transfer encoding '$te'");
1200 return;
1201 }
1202
1203 my $pveclientip = $r->header('PVEClientIP');
1204 my $base_uri = $self->{base_uri};
1205
1206 # fixme: how can we make PVEClientIP header trusted?
1207 if ($self->{trusted_env} && $pveclientip) {
1208 $reqstate->{peer_host} = $pveclientip;
1209 } else {
1210 $r->header('PVEClientIP', $reqstate->{peer_host});
1211 }
1212
1213 my $len = $r->header('Content-Length');
1214
1215 my $host_header = $r->header('Host');
1216 if (my $rpcenv = $self->{rpcenv}) {
1217 $rpcenv->set_request_host($host_header);
1218 }
1219
1220 # header processing complete - authenticate now
1221
1222 my $auth = {};
1223 if ($self->{spiceproxy}) {
1224 my $connect_str = $host_header;
1225 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
1226 if (!(defined($vmid) && $node && $port)) {
1227 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket");
1228 return;
1229 }
1230 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1231 return;
1232 } elsif ($path =~ m/^\Q$base_uri\E/) {
1233 my $token = $r->header('CSRFPreventionToken');
1234 my $cookie = $r->header('Cookie');
1235 my $ticket = PVE::APIServer::Formatter::extract_auth_cookie($cookie, $self->{cookie_name});
1236
1237 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1238 if (!$format) {
1239 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri");
1240 return;
1241 }
1242
1243 eval {
1244 $auth = $self->auth_handler($method, $rel_uri, $ticket, $token,
1245 $reqstate->{peer_host});
1246 };
1247 if (my $err = $@) {
1248 # HACK: see Note 1
1249 Net::SSLeay::ERR_clear_error();
1250 # always delay unauthorized calls by 3 seconds
1251 my $delay = 3;
1252
1253 if (ref($err) eq "PVE::Exception") {
1254
1255 $err->{code} ||= HTTP_INTERNAL_SERVER_ERROR,
1256 my $resp = HTTP::Response->new($err->{code}, $err->{msg});
1257 $self->response($reqstate, $resp, undef, 0, $delay);
1258
1259 } elsif (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
1260 my ($raw, $ct, $nocomp) =
1261 $formatter->($path, $auth, $self->{formatter_config});
1262 my $resp;
1263 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1264 $resp = $raw;
1265 } else {
1266 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required");
1267 $resp->header("Content-Type" => $ct);
1268 $resp->content($raw);
1269 }
1270 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1271 } else {
1272 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1273 $self->response($reqstate, $resp, undef, 0, $delay);
1274 }
1275 return;
1276 }
1277 }
1278
1279 $reqstate->{log}->{userid} = $auth->{userid};
1280
1281 if ($len) {
1282
1283 if (!($method eq 'PUT' || $method eq 'POST')) {
1284 $self->error($reqstate, 501, "Unexpected content for method '$method'");
1285 return;
1286 }
1287
1288 my $ctype = $r->header('Content-Type');
1289 my ($ct, $boundary) = parse_content_type($ctype) if $ctype;
1290
1291 if ($auth->{isUpload} && !$self->{trusted_env}) {
1292 die "upload 'Content-Type '$ctype' not implemented\n"
1293 if !($boundary && $ct && ($ct eq 'multipart/form-data'));
1294
1295 die "upload without content length header not supported" if !$len;
1296
1297 die "upload without content length header not supported" if !$len;
1298
1299 print "start upload $path $ct $boundary\n" if $self->{debug};
1300
1301 my $tmpfilename = get_upload_filename();
1302 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1303 die "unable to create temporary upload file '$tmpfilename'";
1304
1305 $reqstate->{keep_alive} = 0;
1306
1307 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1308
1309 my $state = {
1310 size => $len,
1311 boundary => $boundary,
1312 ctx => Digest::MD5->new,
1313 boundlen => $boundlen,
1314 maxheader => 2048 + $boundlen, # should be large enough
1315 params => decode_urlencoded($r->url->query()),
1316 phase => 0,
1317 read => 0,
1318 post_size => 0,
1319 starttime => [gettimeofday],
1320 outfh => $outfh,
1321 };
1322 $reqstate->{tmpfilename} = $tmpfilename;
1323 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $method, $path, $state); });
1324 return;
1325 }
1326
1327 if ($len > $limit_max_post) {
1328 $self->error($reqstate, 501, "for data too large");
1329 return;
1330 }
1331
1332 if (!$ct || $ct eq 'application/x-www-form-urlencoded') {
1333 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1334 my ($hdl, $data) = @_;
1335 $r->content($data);
1336 $self->handle_request($reqstate, $auth, $method, $path);
1337 });
1338 } else {
1339 $self->error($reqstate, 506, "upload 'Content-Type '$ctype' not implemented");
1340 }
1341 } else {
1342 $self->handle_request($reqstate, $auth, $method, $path);
1343 }
1344 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1345 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1346 ($state->{key}, $state->{val}) = ($1, $2);
1347 $self->unshift_read_header($reqstate, $state);
1348 } elsif ($line =~ /^\s+(.*)/) {
1349 $state->{val} .= " $1";
1350 $self->unshift_read_header($reqstate, $state);
1351 } else {
1352 $self->error($reqstate, 506, "unable to parse request header");
1353 }
1354 };
1355 warn $@ if $@;
1356 });
1357 };
1358
1359 sub push_request_header {
1360 my ($self, $reqstate) = @_;
1361
1362 eval {
1363 $reqstate->{hdl}->push_read(line => sub {
1364 my ($hdl, $line) = @_;
1365
1366 eval {
1367 # print "got request header: $line\n" if $self->{debug};
1368
1369 $reqstate->{keep_alive}--;
1370
1371 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1372 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1373
1374 if ($maj != 1) {
1375 $self->error($reqstate, 506, "http protocol version $maj.$min not supported");
1376 return;
1377 }
1378
1379 $self->{request_count}++; # only count valid request headers
1380 if ($self->{request_count} >= $self->{max_requests}) {
1381 $self->{end_loop} = 1;
1382 }
1383 $reqstate->{log} = { requestline => $line };
1384 $reqstate->{proto}->{str} = "HTTP/$maj.$min";
1385 $reqstate->{proto}->{maj} = $maj;
1386 $reqstate->{proto}->{min} = $min;
1387 $reqstate->{proto}->{ver} = $maj*1000+$min;
1388 $reqstate->{request} = HTTP::Request->new($method, $url);
1389 $reqstate->{starttime} = [gettimeofday],
1390
1391 $self->unshift_read_header($reqstate);
1392 } elsif ($line eq '') {
1393 # ignore empty lines before requests (browser bugs?)
1394 $self->push_request_header($reqstate);
1395 } else {
1396 $self->error($reqstate, 400, 'bad request');
1397 }
1398 };
1399 warn $@ if $@;
1400 });
1401 };
1402 warn $@ if $@;
1403 }
1404
1405 sub accept {
1406 my ($self) = @_;
1407
1408 my $clientfh;
1409
1410 return if $self->{end_loop};
1411
1412 # we need to m make sure that only one process calls accept
1413 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1414 next if $! == EINTR;
1415 die "could not get lock on file '$self->{lockfile}' - $!\n";
1416 }
1417
1418 my $again = 0;
1419 my $errmsg;
1420 eval {
1421 while (!$self->{end_loop} &&
1422 !defined($clientfh = $self->{socket}->accept()) &&
1423 ($! == EINTR)) {};
1424
1425 if ($self->{end_loop}) {
1426 $again = 0;
1427 } else {
1428 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1429 if (!defined($clientfh)) {
1430 $errmsg = "failed to accept connection: $!\n";
1431 }
1432 }
1433 };
1434 warn $@ if $@;
1435
1436 flock($self->{lockfh}, Fcntl::LOCK_UN());
1437
1438 if (!defined($clientfh)) {
1439 return if $again;
1440 die $errmsg if $errmsg;
1441 }
1442
1443 fh_nonblocking $clientfh, 1;
1444
1445 $self->{conn_count}++;
1446
1447 return $clientfh;
1448 }
1449
1450 sub wait_end_loop {
1451 my ($self) = @_;
1452
1453 $self->{end_loop} = 1;
1454
1455 undef $self->{socket_watch};
1456
1457 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1458
1459 if ($self->{conn_count} <= 0) {
1460 $self->{end_cond}->send(1);
1461 return;
1462 }
1463
1464 # fork and exit, so that parent starts a new worker
1465 if (fork()) {
1466 exit(0);
1467 }
1468
1469 # else we need to wait until all open connections gets closed
1470 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1471 eval {
1472 # todo: test for active connections instead (we can abort idle connections)
1473 if ($self->{conn_count} <= 0) {
1474 undef $w;
1475 $self->{end_cond}->send(1);
1476 }
1477 };
1478 warn $@ if $@;
1479 });
1480 }
1481
1482
1483 sub check_host_access {
1484 my ($self, $clientip) = @_;
1485
1486 my $cip = Net::IP->new($clientip);
1487
1488 my $match_allow = 0;
1489 my $match_deny = 0;
1490
1491 if ($self->{allow_from}) {
1492 foreach my $t (@{$self->{allow_from}}) {
1493 if ($t->overlaps($cip)) {
1494 $match_allow = 1;
1495 last;
1496 }
1497 }
1498 }
1499
1500 if ($self->{deny_from}) {
1501 foreach my $t (@{$self->{deny_from}}) {
1502 if ($t->overlaps($cip)) {
1503 $match_deny = 1;
1504 last;
1505 }
1506 }
1507 }
1508
1509 if ($match_allow == $match_deny) {
1510 # match both allow and deny, or no match
1511 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1512 }
1513
1514 return $match_allow;
1515 }
1516
1517 sub accept_connections {
1518 my ($self) = @_;
1519
1520 eval {
1521
1522 while (my $clientfh = $self->accept()) {
1523
1524 my $reqstate = { keep_alive => $self->{keep_alive} };
1525
1526 # stop keep-alive when there are many open connections
1527 if ($self->{conn_count} >= $self->{max_conn_soft_limit}) {
1528 $reqstate->{keep_alive} = 0;
1529 }
1530
1531 if (my $sin = getpeername($clientfh)) {
1532 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1533 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1534 }
1535
1536 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1537 print "$$: ABORT request from $reqstate->{peer_host} - access denied\n" if $self->{debug};
1538 $reqstate->{log}->{code} = 403;
1539 $self->log_request($reqstate);
1540 next;
1541 }
1542
1543 $reqstate->{hdl} = AnyEvent::Handle->new(
1544 fh => $clientfh,
1545 rbuf_max => 64*1024,
1546 timeout => $self->{timeout},
1547 linger => 0, # avoid problems with ssh - really needed ?
1548 on_eof => sub {
1549 my ($hdl) = @_;
1550 eval {
1551 $self->log_aborted_request($reqstate);
1552 $self->client_do_disconnect($reqstate);
1553 };
1554 if (my $err = $@) { syslog('err', $err); }
1555 },
1556 on_error => sub {
1557 my ($hdl, $fatal, $message) = @_;
1558 eval {
1559 $self->log_aborted_request($reqstate, $message);
1560 $self->client_do_disconnect($reqstate);
1561 };
1562 if (my $err = $@) { syslog('err', "$err"); }
1563 },
1564 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1565
1566 print "$$: ACCEPT FH" . $clientfh->fileno() . " CONN$self->{conn_count}\n" if $self->{debug};
1567
1568 $self->push_request_header($reqstate);
1569 }
1570 };
1571
1572 if (my $err = $@) {
1573 syslog('err', $err);
1574 $self->{end_loop} = 1;
1575 }
1576
1577 $self->wait_end_loop() if $self->{end_loop};
1578 }
1579
1580 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1581 # because we write from multiple processes, and that would arbitrarily mix output
1582 # of all processes.
1583 sub open_access_log {
1584 my ($self, $filename) = @_;
1585
1586 my $old_mask = umask(0137);;
1587 my $logfh = IO::File->new($filename, ">>") ||
1588 die "unable to open log file '$filename' - $!\n";
1589 umask($old_mask);
1590
1591 $logfh->autoflush(1);
1592
1593 $self->{logfh} = $logfh;
1594 }
1595
1596 sub write_log {
1597 my ($self, $data) = @_;
1598
1599 return if !defined($self->{logfh}) || !$data;
1600
1601 my $res = $self->{logfh}->print($data);
1602
1603 if (!$res) {
1604 delete $self->{logfh};
1605 syslog('err', "error writing access log");
1606 $self->{end_loop} = 1; # terminate asap
1607 }
1608 }
1609
1610 sub atfork_handler {
1611 my ($self) = @_;
1612
1613 eval {
1614 # something else do to ?
1615 close($self->{socket});
1616 };
1617 warn $@ if $@;
1618 }
1619
1620 sub run {
1621 my ($self) = @_;
1622
1623 $self->{end_cond}->recv;
1624 }
1625
1626 sub new {
1627 my ($this, %args) = @_;
1628
1629 my $class = ref($this) || $this;
1630
1631 foreach my $req (qw(socket lockfh lockfile)) {
1632 die "misssing required argument '$req'" if !defined($args{$req});
1633 }
1634
1635 my $self = bless { %args }, $class;
1636
1637 $self->{cookie_name} //= 'PVEAuthCookie';
1638 $self->{base_uri} //= "/api2";
1639 $self->{dirs} //= {};
1640 $self->{title} //= 'API Inspector';
1641 $self->{compression} //= 1;
1642
1643 # formatter_config: we pass some configuration values to the Formatter
1644 $self->{formatter_config} = {};
1645 foreach my $p (qw(cookie_name base_uri title)) {
1646 $self->{formatter_config}->{$p} = $self->{$p};
1647 }
1648 $self->{formatter_config}->{csrfgen_func} =
1649 $self->can('generate_csrf_prevention_token');
1650
1651 # add default dirs which includes jquery and bootstrap
1652 my $jsbase = '/usr/share/javascript';
1653 add_dirs($self->{dirs}, '/js/' => "$jsbase/");
1654 # libjs-bootstrap uses symlinks for this, which we do not want to allow..
1655 my $glyphicons = '/usr/share/fonts/truetype/glyphicons/';
1656 add_dirs($self->{dirs}, '/js/bootstrap/fonts/' => "$glyphicons");
1657
1658 # init inotify
1659 PVE::INotify::inotify_init();
1660
1661 fh_nonblocking($self->{socket}, 1);
1662
1663 $self->{end_loop} = 0;
1664 $self->{conn_count} = 0;
1665 $self->{request_count} = 0;
1666 $self->{timeout} = 5 if !$self->{timeout};
1667 $self->{keep_alive} = 0 if !defined($self->{keep_alive});
1668 $self->{max_conn} = 800 if !$self->{max_conn};
1669 $self->{max_requests} = 8000 if !$self->{max_requests};
1670
1671 $self->{policy} = 'allow' if !$self->{policy};
1672
1673 $self->{end_cond} = AnyEvent->condvar;
1674
1675 if ($self->{ssl}) {
1676 my $ssl_defaults = {
1677 # Note: older versions are considered insecure, for example
1678 # search for "Poodle"-Attack
1679 method => 'any',
1680 sslv2 => 0,
1681 sslv3 => 0,
1682 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',
1683 honor_cipher_order => 1,
1684 };
1685
1686 foreach my $k (keys %$ssl_defaults) {
1687 $self->{ssl}->{$k} //= $ssl_defaults->{$k};
1688 }
1689
1690 if (!defined($self->{ssl}->{dh_file})) {
1691 $self->{ssl}->{dh} = 'skip2048';
1692 }
1693
1694 my $tls_ctx_flags = &Net::SSLeay::OP_NO_COMPRESSION | &Net::SSLeay::OP_SINGLE_ECDH_USE | &Net::SSLeay::OP_SINGLE_DH_USE;
1695 if ( delete $self->{ssl}->{honor_cipher_order} ) {
1696 $tls_ctx_flags |= &Net::SSLeay::OP_CIPHER_SERVER_PREFERENCE;
1697 }
1698
1699 $self->{tls_ctx} = AnyEvent::TLS->new(%{$self->{ssl}});
1700 Net::SSLeay::CTX_set_options($self->{tls_ctx}->{ctx}, $tls_ctx_flags);
1701 }
1702
1703 if ($self->{spiceproxy}) {
1704 $known_methods = { CONNECT => 1 };
1705 }
1706
1707 $self->open_access_log($self->{logfile}) if $self->{logfile};
1708
1709 $self->{max_conn_soft_limit} = $self->{max_conn} > 100 ? $self->{max_conn} - 20 : $self->{max_conn};
1710
1711 $self->{socket_watch} = AnyEvent->io(fh => $self->{socket}, poll => 'r', cb => sub {
1712 eval {
1713 if ($self->{conn_count} >= $self->{max_conn}) {
1714 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1715 if ($self->{conn_count} < $self->{max_conn}) {
1716 undef $w;
1717 $self->accept_connections();
1718 }
1719 });
1720 } else {
1721 $self->accept_connections();
1722 }
1723 };
1724 warn $@ if $@;
1725 });
1726
1727 $self->{term_watch} = AnyEvent->signal(signal => "TERM", cb => sub {
1728 undef $self->{term_watch};
1729 $self->wait_end_loop();
1730 });
1731
1732 $self->{quit_watch} = AnyEvent->signal(signal => "QUIT", cb => sub {
1733 undef $self->{quit_watch};
1734 $self->wait_end_loop();
1735 });
1736
1737 $self->{inotify_poll} = AnyEvent->timer(after => 5, interval => 5, cb => sub {
1738 PVE::INotify::poll(); # read inotify events
1739 });
1740
1741 return $self;
1742 }
1743
1744 # static helper to add directory including all subdirs
1745 # This can be used to setup $self->{dirs}
1746 sub add_dirs {
1747 my ($result_hash, $alias, $subdir) = @_;
1748
1749 $result_hash->{$alias} = $subdir;
1750
1751 my $wanted = sub {
1752 my $dir = $File::Find::dir;
1753 if ($dir =~m!^$subdir(.*)$!) {
1754 my $name = "$alias$1/";
1755 $result_hash->{$name} = "$dir/";
1756 }
1757 };
1758
1759 find({wanted => $wanted, follow => 0, no_chdir => 1}, $subdir);
1760 }
1761
1762 # abstract functions - subclass should overwrite/implement them
1763
1764 sub verify_spice_connect_url {
1765 my ($self, $connect_str) = @_;
1766
1767 die "implement me";
1768
1769 #return ($vmid, $node, $port);
1770 }
1771
1772 # formatters can call this when the generate a new page
1773 sub generate_csrf_prevention_token {
1774 my ($username) = @_;
1775
1776 return undef; # do nothing by default
1777 }
1778
1779 sub auth_handler {
1780 my ($self, $method, $rel_uri, $ticket, $token, $peer_host) = @_;
1781
1782 die "implement me";
1783
1784 # return {
1785 # ticket => $ticket,
1786 # token => $token,
1787 # userid => $username,
1788 # age => $age,
1789 # isUpload => $isUpload,
1790 #};
1791 }
1792
1793 sub rest_handler {
1794 my ($self, $clientip, $method, $rel_uri, $auth, $params, $format) = @_;
1795
1796 # please do not raise exceptions here (always return a result).
1797
1798 return {
1799 status => HTTP_NOT_IMPLEMENTED,
1800 message => "Method '$method $rel_uri' not implemented",
1801 };
1802
1803 # this should return the following properties, which
1804 # are then passed to the Formatter
1805
1806 # status: HTTP status code
1807 # message: Error message
1808 # errors: more detailed error hash (per parameter)
1809 # info: reference to JSON schema definition - useful to format output
1810 # data: result data
1811
1812 # total: additional info passed to output
1813 # changes: additional info passed to output
1814
1815 # if you want to proxy the request to another node return this
1816 # { proxy => $remip, proxynode => $node, proxy_params => $params };
1817
1818 # to pass the request to the local priviledged daemon use:
1819 # { proxy => 'localhost' , proxy_params => $params };
1820
1821 # to download aspecific file use:
1822 # { download => "/path/to/file" };
1823 }
1824
1825 sub check_cert_fingerprint {
1826 my ($self, $cert) = @_;
1827
1828 die "implement me";
1829 }
1830
1831 sub initialize_cert_cache {
1832 my ($self, $node) = @_;
1833
1834 die "implement me";
1835 }
1836
1837 sub remote_node_ip {
1838 my ($self, $node) = @_;
1839
1840 die "implement me";
1841
1842 # return $remip;
1843 }
1844
1845
1846 1;