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