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