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