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