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