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