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