]> git.proxmox.com Git - pve-http-server.git/blob - src/PVE/APIServer/AnyEvent.pm
e34c06abd1f3b5160958da5db89dd6539b2c0a01
[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 ca_path => '/usr/lib/ssl/certs', # to avoid loading the combined CA cert file
770 verify_cb => sub {
771 my (undef, undef, undef, $depth, undef, undef, $cert) = @_;
772 # we don't care about intermediate or root certificates
773 return 1 if $depth != 0;
774 # check server certificate against cache of pinned FPs
775 return $self->check_cert_fingerprint($cert);
776 },
777 };
778
779 # load and cache cert fingerprint if first time we proxy to this node
780 $self->initialize_cert_cache($node);
781
782 my $w; $w = http_request(
783 $method => $target,
784 headers => $headers,
785 timeout => 30,
786 recurse => 0,
787 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
788 keepalive => $keep_alive,
789 body => $content,
790 tls_ctx => AnyEvent::TLS->new(%{$tls}),
791 sub {
792 my ($body, $hdr) = @_;
793
794 undef $w;
795
796 if (!$reqstate->{hdl}) {
797 warn "proxy detected vanished client connection\n";
798 return;
799 }
800
801 eval {
802 my $code = delete $hdr->{Status};
803 my $msg = delete $hdr->{Reason};
804 my $stream = delete $hdr->{pvestreamfile};
805 delete $hdr->{URL};
806 delete $hdr->{HTTPVersion};
807 my $header = HTTP::Headers->new(%$hdr);
808 if (my $location = $header->header('Location')) {
809 $location =~ s|^http://localhost:85||;
810 $header->header(Location => $location);
811 }
812 if ($stream) {
813 if (!$may_stream_file) {
814 $self->error($reqstate, 403, 'streaming denied');
815 return;
816 }
817 sysopen(my $fh, "$stream", O_NONBLOCK | O_RDONLY)
818 or die "open stream path '$stream' for forwarding failed: $!\n";
819 my $resp = HTTP::Response->new($code, $msg, $header, undef);
820 $self->response($reqstate, $resp, undef, 1, 0, $fh);
821 } else {
822 my $resp = HTTP::Response->new($code, $msg, $header, $body);
823 # Note: disable compression, because body is already compressed
824 $self->response($reqstate, $resp, undef, 1);
825 }
826 };
827 warn $@ if $@;
828 });
829 };
830 warn $@ if $@;
831 }
832
833 # return arrays as \0 separated strings (like CGI.pm)
834 # assume data is UTF8 encoded
835 sub decode_urlencoded {
836 my ($data) = @_;
837
838 my $res = {};
839
840 return $res if !$data;
841
842 foreach my $kv (split(/[\&\;]/, $data)) {
843 my ($k, $v) = split(/=/, $kv);
844 $k =~s/\+/ /g;
845 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
846
847 if (defined($v)) {
848 $v =~s/\+/ /g;
849 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
850
851 $v = Encode::decode('utf8', $v);
852
853 if (defined(my $old = $res->{$k})) {
854 if (ref($old) eq 'ARRAY') {
855 push @$old, $v;
856 $v = $old;
857 } else {
858 $v = [$old, $v];
859 }
860 }
861 }
862
863 $res->{$k} = $v;
864 }
865 return $res;
866 }
867
868 sub extract_params {
869 my ($r, $method) = @_;
870
871 my $params = {};
872
873 if ($method eq 'PUT' || $method eq 'POST') {
874 my $ct;
875 if (my $ctype = $r->header('Content-Type')) {
876 $ct = parse_content_type($ctype);
877 }
878 if (defined($ct) && $ct eq 'application/json') {
879 $params = decode_json($r->content);
880 } else {
881 $params = decode_urlencoded($r->content);
882 }
883 }
884
885 my $query_params = decode_urlencoded($r->url->query());
886
887 foreach my $k (keys %{$query_params}) {
888 $params->{$k} = $query_params->{$k};
889 }
890
891 return $params;
892 }
893
894 sub handle_api2_request {
895 my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_;
896
897 eval {
898 my $r = $reqstate->{request};
899
900 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
901
902 my $formatter = PVE::APIServer::Formatter::get_formatter($format, $method, $rel_uri);
903
904 if (!defined($formatter)) {
905 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no formatter for uri $rel_uri, $format");
906 return;
907 }
908
909 #print Dumper($upload_state) if $upload_state;
910
911 my $params;
912
913 if ($upload_state) {
914 $params = $upload_state->{params};
915 } else {
916 $params = extract_params($r, $method);
917 }
918
919 delete $params->{_dc} if $params; # remove disable cache parameter
920
921 my $clientip = $reqstate->{peer_host};
922
923 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format);
924
925 # HACK: see Note 1
926 Net::SSLeay::ERR_clear_error();
927
928 AnyEvent->now_update(); # in case somebody called sleep()
929
930 my $upgrade = $r->header('upgrade');
931 $upgrade = lc($upgrade) if $upgrade;
932
933 if (my $host = $res->{proxy}) {
934
935 if ($self->{trusted_env}) {
936 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy not allowed");
937 return;
938 }
939
940 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
941 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy loop detected");
942 return;
943 }
944
945 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
946
947 $self->proxy_request(
948 $reqstate, $clientip, $host, $res->{proxynode}, $method, $r->uri, $auth, $res->{proxy_params});
949 return;
950
951 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
952 die "unable to upgrade to protocol '$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
953 my $wsver = $r->header('sec-websocket-version');
954 die "unsupported websocket-version '$wsver'\n" if !$wsver || ($wsver ne '13');
955 my $wsproto = $r->header('sec-websocket-protocol') // "";
956 my $wskey = $r->header('sec-websocket-key');
957 die "missing websocket-key\n" if !$wskey;
958 # Note: Digest::SHA::sha1_base64 has wrong padding
959 my $wsaccept = Digest::SHA::sha1_base64("${wskey}258EAFA5-E914-47DA-95CA-C5AB0DC85B11") . "=";
960 if ($res->{status} == HTTP_OK) {
961 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
962 return;
963 }
964 }
965
966 my $delay = 0;
967 if ($res->{status} == HTTP_UNAUTHORIZED) {
968 # always delay unauthorized calls by 3 seconds
969 $delay = 3 - tv_interval($reqstate->{starttime});
970 $delay = 0 if $delay < 0;
971 }
972
973 my $download = $res->{download};
974 $download //= $res->{data}->{download}
975 if defined($res->{data}) && ref($res->{data}) eq 'HASH';
976 if (defined($download)) {
977 send_file_start($self, $reqstate, $download);
978 return;
979 }
980
981 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
982 $auth, $self->{formatter_config});
983
984 my $resp;
985 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
986 $resp = $raw;
987 } else {
988 $resp = HTTP::Response->new($res->{status}, $res->{message});
989 $resp->header("Content-Type" => $ct);
990 $resp->content($raw);
991 }
992 $self->response($reqstate, $resp, undef, $nocomp, $delay);
993 };
994 if (my $err = $@) {
995 $self->error($reqstate, 501, $err);
996 }
997 }
998
999 sub handle_spice_proxy_request {
1000 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
1001
1002 eval {
1003
1004 my ($minport, $maxport) = PVE::Tools::spice_port_range();
1005 if ($spiceport < $minport || $spiceport > $maxport) {
1006 die "SPICE Port $spiceport is not in allowed range ($minport, $maxport)\n";
1007 }
1008
1009 my $clientip = $reqstate->{peer_host};
1010 my $r = $reqstate->{request};
1011
1012 my $remip;
1013
1014 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
1015 $remip = $self->remote_node_ip($node);
1016 $self->dprint("REMOTE CONNECT $vmid, $remip, $connect_str");
1017 } else {
1018 $self->dprint("CONNECT $vmid, $node, $spiceport");
1019 }
1020
1021 if ($remip && $r->header('PVEDisableProxy')) {
1022 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy loop detected");
1023 return;
1024 }
1025
1026 $reqstate->{hdl}->timeout(0);
1027 $reqstate->{hdl}->wbuf_max(64*10*1024);
1028
1029 my $remhost = $remip ? $remip : "localhost";
1030 my $remport = $remip ? 3128 : $spiceport;
1031
1032 tcp_connect $remhost, $remport, sub {
1033 my ($fh) = @_
1034 or die "connect to '$remhost:$remport' failed: $!";
1035
1036 $self->dprint("CONNECTed to '$remhost:$remport'");
1037 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
1038 fh => $fh,
1039 rbuf_max => 64*1024,
1040 wbuf_max => 64*10*1024,
1041 timeout => 5,
1042 on_eof => sub {
1043 my ($hdl) = @_;
1044 eval {
1045 $self->log_aborted_request($reqstate);
1046 $self->client_do_disconnect($reqstate);
1047 };
1048 if (my $err = $@) { syslog('err', $err); }
1049 },
1050 on_error => sub {
1051 my ($hdl, $fatal, $message) = @_;
1052 eval {
1053 $self->log_aborted_request($reqstate, $message);
1054 $self->client_do_disconnect($reqstate);
1055 };
1056 if (my $err = $@) { syslog('err', "$err"); }
1057 });
1058
1059
1060 my $proxyhdlreader = sub {
1061 my ($hdl) = @_;
1062
1063 my $len = length($hdl->{rbuf});
1064 my $data = substr($hdl->{rbuf}, 0, $len, '');
1065
1066 #print "READ1 $len\n";
1067 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
1068 };
1069
1070 my $hdlreader = sub {
1071 my ($hdl) = @_;
1072
1073 my $len = length($hdl->{rbuf});
1074 my $data = substr($hdl->{rbuf}, 0, $len, '');
1075
1076 #print "READ0 $len\n";
1077 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
1078 };
1079
1080 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
1081
1082 my $startproxy = sub {
1083 $reqstate->{proxyhdl}->timeout(0);
1084 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
1085 $reqstate->{hdl}->on_read($hdlreader);
1086
1087 # todo: use stop_read/start_read if write buffer grows to much
1088
1089 # a response must be followed by an empty line
1090 my $res = "$proto 200 OK\015\012\015\012";
1091 $reqstate->{hdl}->push_write($res);
1092
1093 # log early
1094 $reqstate->{log}->{code} = 200;
1095 $self->log_request($reqstate);
1096 };
1097
1098 if ($remip) {
1099 my $header = "CONNECT ${connect_str} $proto\015\012" .
1100 "Host: ${connect_str}\015\012" .
1101 "Proxy-Connection: keep-alive\015\012" .
1102 "User-Agent: spiceproxy\015\012" .
1103 "PVEDisableProxy: true\015\012" .
1104 "PVEClientIP: $clientip\015\012" .
1105 "\015\012";
1106
1107 $reqstate->{proxyhdl}->push_write($header);
1108 $reqstate->{proxyhdl}->push_read(line => sub {
1109 my ($hdl, $line) = @_;
1110
1111 if ($line =~ m!^$proto 200 OK$!) {
1112 # read the empty line after the 200 OK
1113 $reqstate->{proxyhdl}->unshift_read(line => sub{
1114 &$startproxy();
1115 });
1116 } else {
1117 $reqstate->{hdl}->push_write($line);
1118 $self->client_do_disconnect($reqstate);
1119 }
1120 });
1121 } else {
1122 &$startproxy();
1123 }
1124
1125 };
1126 };
1127 if (my $err = $@) {
1128 warn $err;
1129 $self->log_aborted_request($reqstate, $err);
1130 $self->client_do_disconnect($reqstate);
1131 }
1132 }
1133
1134 sub handle_request {
1135 my ($self, $reqstate, $auth, $method, $path) = @_;
1136
1137 my $base_uri = $self->{base_uri};
1138
1139 eval {
1140 my $r = $reqstate->{request};
1141
1142 # disable timeout on handle (we already have all data we need)
1143 # we re-enable timeout in response()
1144 $reqstate->{hdl}->timeout(0);
1145
1146 if ($path =~ m/^\Q$base_uri\E/) {
1147 $self->handle_api2_request($reqstate, $auth, $method, $path);
1148 return;
1149 }
1150
1151 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
1152 if (ref($handler) eq 'CODE') {
1153 my $params = decode_urlencoded($r->url->query());
1154 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
1155 # HACK: see Note 1
1156 Net::SSLeay::ERR_clear_error();
1157 $self->response($reqstate, $resp);
1158 } elsif (ref($handler) eq 'HASH') {
1159 if (my $filename = $handler->{file}) {
1160 my $fh = IO::File->new($filename) ||
1161 die "unable to open file '$filename' - $!\n";
1162 send_file_start($self, $reqstate, $filename);
1163 } else {
1164 die "internal error - no handler";
1165 }
1166 } else {
1167 die "internal error - no handler";
1168 }
1169 return;
1170 }
1171
1172 if ($self->{dirs} && ($method eq 'GET')) {
1173 # we only allow simple names
1174 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
1175 my ($subdir, $file) = ($1, $2);
1176 if (my $dir = $self->{dirs}->{$subdir}) {
1177 my $filename = "$dir$file";
1178 my $fh = IO::File->new($filename) ||
1179 die "unable to open file '$filename' - $!\n";
1180 send_file_start($self, $reqstate, $filename);
1181 return;
1182 }
1183 }
1184 }
1185
1186 die "no such file '$path'\n";
1187 };
1188 if (my $err = $@) {
1189 $self->error($reqstate, 501, $err);
1190 }
1191 }
1192
1193 my sub assert_form_disposition {
1194 die "wrong Content-Disposition '$_[0]' in multipart, expected 'form-data'\n" if $_[0] ne 'form-data';
1195 }
1196
1197 sub file_upload_multipart {
1198 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
1199
1200 eval {
1201 my $boundary = $rstate->{boundary};
1202 my $hdl = $reqstate->{hdl};
1203 my $startlen = length($hdl->{rbuf});
1204
1205 my $newline_re = qr/\015?\012/;
1206 my $delim_re = qr/--\Q$boundary\E${newline_re}/;
1207 my $close_delim_re = qr/--\Q$boundary\E--/;
1208
1209 # Phase 0 - preserve boundary, but remove everything before
1210 if ($rstate->{phase} == 0 && $hdl->{rbuf} =~ s/^.*?($delim_re)/$1/s) {
1211 $rstate->{read} += $startlen - length($hdl->{rbuf});
1212 $rstate->{phase} = 1;
1213 }
1214
1215 my $remove_until_data = sub {
1216 my ($hdl) = @_;
1217 # remove any remaining multipart "headers" like Content-Type
1218 $hdl->{rbuf} =~ s/^.*?${newline_re}{2}//s;
1219 };
1220
1221 my $extract_form_disposition = sub {
1222 my ($name) = @_;
1223 if ($hdl->{rbuf} =~ s/^${delim_re}.*?Content-Disposition: (.*?); name="$name"(.*?${delim_re})/$2/s) {
1224 assert_form_disposition($1);
1225 $remove_until_data->($hdl);
1226 $hdl->{rbuf} =~ s/^(.*?)(${delim_re})/$2/s;
1227 $rstate->{params}->{$name} = trim($1);
1228 }
1229 };
1230
1231 if ($rstate->{phase} == 1) { # Phase 1 - parse payload without file data
1232 $extract_form_disposition->('content');
1233 $extract_form_disposition->('checksum-algorithm');
1234 $extract_form_disposition->('checksum');
1235
1236 if ($hdl->{rbuf} =~ s/^${delim_re}Content-Disposition: (.*?); name="(.*?)"; filename="([^"]+)"//s) {
1237 assert_form_disposition($1);
1238 die "wrong field name '$2' for file upload, expected 'filename'" if $2 ne "filename";
1239 $rstate->{phase} = 2;
1240 $rstate->{params}->{filename} = trim($3);
1241 $remove_until_data->($hdl); # any remaining multipart "headers" like Content-Type
1242 }
1243 }
1244
1245 if ($rstate->{phase} == 2) { # Phase 2 - dump content into file
1246 my ($data, $write_length);
1247 if ($hdl->{rbuf} =~ s/^(.*?)${newline_re}?+${close_delim_re}.*$//s) {
1248 $data = $1;
1249 $write_length = length($data);
1250 $rstate->{phase} = 100;
1251 } else {
1252 $write_length = length($hdl->{rbuf}) - $rstate->{boundlen};
1253 $data = substr($hdl->{rbuf}, 0, $write_length, '') if $write_length > 0;
1254 }
1255
1256 if ($write_length > 0) {
1257 syswrite($rstate->{outfh}, $data) == $write_length or die "write to temporary file failed - $!\n";
1258 $rstate->{bytes} += $write_length;
1259 }
1260 }
1261
1262 if ($rstate->{phase} == 100) { # Phase 100 - transfer finished
1263 my $elapsed = tv_interval($rstate->{starttime});
1264 syslog('info', "multipart upload complete (size: %dB time: %.3fs rate: %.2fMiB/s filename: %s)",
1265 $rstate->{bytes}, $elapsed, $rstate->{bytes} / ($elapsed * 1024 * 1024),
1266 $rstate->{params}->{filename}
1267 );
1268 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1269 }
1270
1271 $rstate->{read} += $startlen - length($hdl->{rbuf});
1272
1273 if ($rstate->{read} + length($hdl->{rbuf}) >= $rstate->{size} && $rstate->{phase} != 100) {
1274 die "upload failed";
1275 }
1276 };
1277 if (my $err = $@) {
1278 syslog('err', $err);
1279 $self->error($reqstate, 501, $err);
1280 }
1281 }
1282
1283 sub parse_content_type {
1284 my ($ctype) = @_;
1285
1286 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
1287
1288 foreach my $v (@params) {
1289 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1290 return wantarray ? ($ct, $1) : $ct;
1291 }
1292 }
1293
1294 return wantarray ? ($ct) : $ct;
1295 }
1296
1297 my $tmpfile_seq_no = 0;
1298
1299 sub get_upload_filename {
1300 # choose unpredictable tmpfile name
1301
1302 $tmpfile_seq_no++;
1303 return "/var/tmp/pveupload-" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1304 }
1305
1306 sub unshift_read_header {
1307 my ($self, $reqstate, $state) = @_;
1308
1309 $state = { size => 0, count => 0 } if !$state;
1310
1311 $reqstate->{hdl}->unshift_read(line => sub {
1312 my ($hdl, $line) = @_;
1313
1314 eval {
1315 # print "$$: got header: $line\n" if $self->{debug};
1316
1317 die "too many http header lines (> $limit_max_headers)\n" if ++$state->{count} >= $limit_max_headers;
1318 die "http header too large\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1319
1320 my $r = $reqstate->{request};
1321 if ($line eq '') {
1322
1323 $r->push_header($state->{key}, $state->{val})
1324 if $state->{key};
1325
1326 return if !$self->process_header($reqstate);
1327 return if !$self->ensure_tls_connection($reqstate);
1328
1329 $self->authenticate_and_handle_request($reqstate);
1330
1331 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1332 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1333 ($state->{key}, $state->{val}) = ($1, $2);
1334 $self->unshift_read_header($reqstate, $state);
1335 } elsif ($line =~ /^\s+(.*)/) {
1336 $state->{val} .= " $1";
1337 $self->unshift_read_header($reqstate, $state);
1338 } else {
1339 $self->error($reqstate, 506, "unable to parse request header");
1340 }
1341 };
1342 warn $@ if $@;
1343 });
1344 };
1345
1346 # sends an (error) response and returns 0 in case of errors
1347 sub process_header {
1348 my ($self, $reqstate) = @_;
1349
1350 my $request = $reqstate->{request};
1351
1352 my $path = uri_unescape($request->uri->path());
1353 my $method = $request->method();
1354
1355 if (!$known_methods->{$method}) {
1356 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available");
1357 $self->response($reqstate, $resp);
1358 return 0;
1359 }
1360
1361 my $conn = $request->header('Connection');
1362 my $accept_enc = $request->header('Accept-Encoding');
1363 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1364
1365 if ($conn) {
1366 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1367 } else {
1368 if ($reqstate->{proto}->{ver} < 1001) {
1369 $reqstate->{keep_alive} = 0;
1370 }
1371 }
1372
1373 my $te = $request->header('Transfer-Encoding');
1374 if ($te && lc($te) eq 'chunked') {
1375 # Handle chunked transfer encoding
1376 $self->error($reqstate, 501, "chunked transfer encoding not supported");
1377 return 0;
1378 } elsif ($te) {
1379 $self->error($reqstate, 501, "Unknown transfer encoding '$te'");
1380 return 0;
1381 }
1382
1383 my $pveclientip = $request->header('PVEClientIP');
1384
1385 # fixme: how can we make PVEClientIP header trusted?
1386 if ($self->{trusted_env} && $pveclientip) {
1387 $reqstate->{peer_host} = $pveclientip;
1388 } else {
1389 $request->header('PVEClientIP', $reqstate->{peer_host});
1390 }
1391
1392 if (my $rpcenv = $self->{rpcenv}) {
1393 $rpcenv->set_request_host($request->header('Host'));
1394 }
1395
1396 return 1;
1397 }
1398
1399 # sends an (redirect) response, disconnects the client and returns 0 if
1400 # connection is not TLS-protected
1401 sub ensure_tls_connection {
1402 my ($self, $reqstate) = @_;
1403
1404 # Skip if server doesn't use TLS
1405 if (!$self->{tls_ctx}) {
1406 return 1;
1407 }
1408
1409 # TLS session exists, so the handshake has succeeded
1410 if ($reqstate->{hdl}->{tls}) {
1411 return 1;
1412 }
1413
1414 my $request = $reqstate->{request};
1415 my $method = $request->method();
1416
1417 my $h_host = $reqstate->{request}->header('Host');
1418
1419 die "Header field 'Host' not found in request\n"
1420 if !$h_host;
1421
1422 my $secure_host = "https://" . ($h_host =~ s/^http(s)?:\/\///r);
1423
1424 my $header = HTTP::Headers->new('Location' => $secure_host . $request->uri());
1425
1426 if ($method eq 'GET' || $method eq 'HEAD') {
1427 $self->error($reqstate, 301, 'Moved Permanently', $header);
1428 } else {
1429 $self->error($reqstate, 308, 'Permanent Redirect', $header);
1430 }
1431
1432 # disconnect the client so they may immediately connect again via HTTPS
1433 $self->client_do_disconnect($reqstate);
1434
1435 return 0;
1436 }
1437
1438 sub authenticate_and_handle_request {
1439 my ($self, $reqstate) = @_;
1440
1441 my $request = $reqstate->{request};
1442 my $method = $request->method();
1443
1444 my $path = uri_unescape($request->uri->path());
1445 my $base_uri = $self->{base_uri};
1446
1447 my $auth = {};
1448
1449 if ($self->{spiceproxy}) {
1450 my $connect_str = $request->header('Host');
1451 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
1452
1453 if (!(defined($vmid) && $node && $port)) {
1454 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket");
1455 return;
1456 }
1457
1458 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1459 return;
1460
1461 } elsif ($path =~ m/^\Q$base_uri\E/) {
1462 my $token = $request->header('CSRFPreventionToken');
1463 my $cookie = $request->header('Cookie');
1464 my $auth_header = $request->header('Authorization');
1465
1466 # prefer actual cookie
1467 my $ticket = PVE::APIServer::Formatter::extract_auth_value(
1468 $cookie,
1469 $self->{cookie_name}
1470 );
1471
1472 # fallback to cookie in 'Authorization' header
1473 if (!$ticket) {
1474 $ticket = PVE::APIServer::Formatter::extract_auth_value(
1475 $auth_header,
1476 $self->{cookie_name}
1477 );
1478 }
1479
1480 # finally, fallback to API token if no ticket has been provided so far
1481 my $api_token;
1482 if (!$ticket) {
1483 $api_token = PVE::APIServer::Formatter::extract_auth_value(
1484 $auth_header,
1485 $self->{apitoken_name}
1486 );
1487 }
1488
1489 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1490 if (!$format) {
1491 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri");
1492 return;
1493 }
1494
1495 eval {
1496 $auth = $self->auth_handler(
1497 $method,
1498 $rel_uri,
1499 $ticket,
1500 $token,
1501 $api_token,
1502 $reqstate->{peer_host}
1503 );
1504 };
1505 if (my $err = $@) {
1506 # HACK: see Note 1
1507 Net::SSLeay::ERR_clear_error();
1508 # always delay unauthorized calls by 3 seconds
1509 my $delay = 3;
1510
1511 if (ref($err) eq "PVE::Exception") {
1512
1513 $err->{code} ||= HTTP_INTERNAL_SERVER_ERROR,
1514 my $resp = HTTP::Response->new($err->{code}, $err->{msg});
1515 $self->response($reqstate, $resp, undef, 0, $delay);
1516
1517 } elsif (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
1518 my ($raw, $ct, $nocomp) =
1519 $formatter->($path, $auth, $self->{formatter_config});
1520
1521 my $resp;
1522 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1523 $resp = $raw;
1524
1525 } else {
1526 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required");
1527 $resp->header("Content-Type" => $ct);
1528 $resp->content($raw);
1529 }
1530
1531 $self->response($reqstate, $resp, undef, $nocomp, $delay);
1532
1533 } else {
1534 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1535 $self->response($reqstate, $resp, undef, 0, $delay);
1536 }
1537
1538 return;
1539 }
1540 }
1541
1542 $reqstate->{log}->{userid} = $auth->{userid};
1543 my $len = $request->header('Content-Length');
1544
1545 if ($len) {
1546
1547 if (!($method eq 'PUT' || $method eq 'POST')) {
1548 $self->error($reqstate, 501, "Unexpected content for method '$method'");
1549 return;
1550 }
1551
1552 my $ctype = $request->header('Content-Type');
1553 my ($ct, $boundary) = $ctype ? parse_content_type($ctype) : ();
1554
1555 if ($auth->{isUpload} && !$self->{trusted_env}) {
1556 die "upload 'Content-Type '$ctype' not implemented\n"
1557 if !($boundary && $ct && ($ct eq 'multipart/form-data'));
1558
1559 die "upload without content length header not supported" if !$len;
1560
1561 die "upload without content length header not supported" if !$len;
1562
1563 $self->dprint("start upload $path $ct $boundary");
1564
1565 my $tmpfilename = get_upload_filename();
1566 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1567 die "unable to create temporary upload file '$tmpfilename'";
1568
1569 $reqstate->{keep_alive} = 0;
1570
1571 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1572
1573 my $state = {
1574 size => $len,
1575 boundary => $boundary,
1576 boundlen => $boundlen,
1577 maxheader => 2048 + $boundlen, # should be large enough
1578 params => decode_urlencoded($request->url->query()),
1579 phase => 0,
1580 read => 0,
1581 post_size => 0,
1582 starttime => [gettimeofday],
1583 outfh => $outfh,
1584 };
1585
1586 die "'tmpfilename' query parameter is not allowed for file uploads\n"
1587 if exists $state->{params}->{tmpfilename};
1588
1589 $reqstate->{tmpfilename} = $tmpfilename;
1590 $reqstate->{hdl}->on_read(sub {
1591 $self->file_upload_multipart($reqstate, $auth, $method, $path, $state);
1592 });
1593
1594 return;
1595 }
1596
1597 if ($len > $limit_max_post) {
1598 $self->error($reqstate, 501, "for data too large");
1599 return;
1600 }
1601
1602 if (!$ct || $ct eq 'application/x-www-form-urlencoded' || $ct eq 'application/json') {
1603 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1604 my ($hdl, $data) = @_;
1605 $request->content($data);
1606 $self->handle_request($reqstate, $auth, $method, $path);
1607 });
1608
1609 } else {
1610 $self->error($reqstate, 506, "upload 'Content-Type '$ctype' not implemented");
1611 }
1612
1613 } else {
1614 $self->handle_request($reqstate, $auth, $method, $path);
1615 }
1616 }
1617
1618 sub push_request_header {
1619 my ($self, $reqstate) = @_;
1620
1621 eval {
1622 $reqstate->{hdl}->push_read(line => sub {
1623 my ($hdl, $line) = @_;
1624
1625 eval {
1626 # print "got request header: $line\n" if $self->{debug};
1627
1628 $reqstate->{keep_alive}--;
1629
1630 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1631 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1632
1633 if ($maj != 1) {
1634 $self->error($reqstate, 506, "http protocol version $maj.$min not supported");
1635 return;
1636 }
1637 if ($url =~ m|^[^/]*@|) {
1638 # if an '@' comes before the first slash proxy forwarding might consider
1639 # the frist part of the url to be part of an authority...
1640 $self->error($reqstate, 400, "invalid url");
1641 return;
1642 }
1643
1644 $self->{request_count}++; # only count valid request headers
1645 if ($self->{request_count} >= $self->{max_requests}) {
1646 $self->{end_loop} = 1;
1647 }
1648 $reqstate->{log} = { requestline => $line };
1649 $reqstate->{proto}->{str} = "HTTP/$maj.$min";
1650 $reqstate->{proto}->{maj} = $maj;
1651 $reqstate->{proto}->{min} = $min;
1652 $reqstate->{proto}->{ver} = $maj*1000+$min;
1653 $reqstate->{request} = HTTP::Request->new($method, $url);
1654 $reqstate->{starttime} = [gettimeofday];
1655
1656 $self->unshift_read_header($reqstate);
1657 } elsif ($line eq '') {
1658 # ignore empty lines before requests (browser bugs?)
1659 $self->push_request_header($reqstate);
1660 } else {
1661 $self->error($reqstate, 400, 'bad request');
1662 }
1663 };
1664 warn $@ if $@;
1665 });
1666 };
1667 warn $@ if $@;
1668 }
1669
1670 sub accept {
1671 my ($self) = @_;
1672
1673 my $clientfh;
1674
1675 return if $self->{end_loop};
1676
1677 # we need to m make sure that only one process calls accept
1678 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1679 next if $! == EINTR;
1680 die "could not get lock on file '$self->{lockfile}' - $!\n";
1681 }
1682
1683 my $again = 0;
1684 my $errmsg;
1685 eval {
1686 while (!$self->{end_loop} &&
1687 !defined($clientfh = $self->{socket}->accept()) &&
1688 ($! == EINTR)) {};
1689
1690 if ($self->{end_loop}) {
1691 $again = 0;
1692 } else {
1693 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1694 if (!defined($clientfh)) {
1695 $errmsg = "failed to accept connection: $!\n";
1696 }
1697 }
1698 };
1699 warn $@ if $@;
1700
1701 flock($self->{lockfh}, Fcntl::LOCK_UN());
1702
1703 if (!defined($clientfh)) {
1704 return if $again;
1705 die $errmsg if $errmsg;
1706 }
1707
1708 fh_nonblocking $clientfh, 1;
1709
1710 return $clientfh;
1711 }
1712
1713 sub wait_end_loop {
1714 my ($self) = @_;
1715
1716 $self->{end_loop} = 1;
1717
1718 undef $self->{socket_watch};
1719
1720 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1721
1722 if ($self->{conn_count} <= 0) {
1723 $self->{end_cond}->send(1);
1724 return;
1725 }
1726
1727 # fork and exit, so that parent starts a new worker
1728 if (fork()) {
1729 exit(0);
1730 }
1731
1732 # else we need to wait until all open connections gets closed
1733 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1734 eval {
1735 # todo: test for active connections instead (we can abort idle connections)
1736 if ($self->{conn_count} <= 0) {
1737 undef $w;
1738 $self->{end_cond}->send(1);
1739 }
1740 };
1741 warn $@ if $@;
1742 });
1743 }
1744
1745
1746 sub check_host_access {
1747 my ($self, $clientip) = @_;
1748
1749 $clientip = PVE::APIServer::Utils::normalize_v4_in_v6($clientip);
1750 my $cip = Net::IP->new($clientip);
1751
1752 if (!$cip) {
1753 $self->dprint("client IP not parsable: $@");
1754 return 0;
1755 }
1756
1757 my $match_allow = 0;
1758 my $match_deny = 0;
1759
1760 if ($self->{allow_from}) {
1761 foreach my $t (@{$self->{allow_from}}) {
1762 if ($t->overlaps($cip)) {
1763 $match_allow = 1;
1764 $self->dprint("client IP allowed: ". $t->prefix());
1765 last;
1766 }
1767 }
1768 }
1769
1770 if ($self->{deny_from}) {
1771 foreach my $t (@{$self->{deny_from}}) {
1772 if ($t->overlaps($cip)) {
1773 $self->dprint("client IP denied: ". $t->prefix());
1774 $match_deny = 1;
1775 last;
1776 }
1777 }
1778 }
1779
1780 if ($match_allow == $match_deny) {
1781 # match both allow and deny, or no match
1782 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1783 }
1784
1785 return $match_allow;
1786 }
1787
1788 sub accept_connections {
1789 my ($self) = @_;
1790
1791 my ($clientfh, $handle_creation);
1792 eval {
1793
1794 while ($clientfh = $self->accept()) {
1795
1796 my $reqstate = { keep_alive => $self->{keep_alive} };
1797
1798 # stop keep-alive when there are many open connections
1799 if ($self->{conn_count} + 1 >= $self->{max_conn_soft_limit}) {
1800 $reqstate->{keep_alive} = 0;
1801 }
1802
1803 if (my $sin = getpeername($clientfh)) {
1804 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1805 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1806 } else {
1807 $self->dprint("getpeername failed: $!");
1808 close($clientfh);
1809 next;
1810 }
1811
1812 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1813 $self->dprint("ABORT request from $reqstate->{peer_host} - access denied");
1814 $reqstate->{log}->{code} = 403;
1815 $self->log_request($reqstate);
1816 close($clientfh);
1817 next;
1818 }
1819
1820 # Increment conn_count before creating new handle, since creation
1821 # triggers callbacks, which can potentialy decrement (e.g.
1822 # on_error) conn_count before AnyEvent::Handle->new() returns.
1823 $handle_creation = 1;
1824 $self->{conn_count}++;
1825 $reqstate->{hdl} = AnyEvent::Handle->new(
1826 fh => $clientfh,
1827 rbuf_max => 64*1024,
1828 timeout => $self->{timeout},
1829 linger => 0, # avoid problems with ssh - really needed ?
1830 on_eof => sub {
1831 my ($hdl) = @_;
1832 eval {
1833 $self->log_aborted_request($reqstate);
1834 $self->client_do_disconnect($reqstate);
1835 };
1836 if (my $err = $@) { syslog('err', $err); }
1837 },
1838 on_error => sub {
1839 my ($hdl, $fatal, $message) = @_;
1840 eval {
1841 $self->log_aborted_request($reqstate, $message);
1842 $self->client_do_disconnect($reqstate);
1843 };
1844 if (my $err = $@) { syslog('err', "$err"); }
1845 },
1846 );
1847 $handle_creation = 0;
1848
1849 $self->dprint("ACCEPT FH" . $clientfh->fileno() . " CONN$self->{conn_count}");
1850
1851 if ($self->{tls_ctx}) {
1852 $self->dprint("Setting TLS to autostart");
1853 $reqstate->{hdl}->unshift_read(tls_autostart => $self->{tls_ctx}, "accept");
1854 }
1855
1856 $self->push_request_header($reqstate);
1857 }
1858 };
1859
1860 if (my $err = $@) {
1861 syslog('err', $err);
1862 $self->dprint("connection accept error: $err");
1863 close($clientfh);
1864 if ($handle_creation) {
1865 if ($self->{conn_count} <= 0) {
1866 warn "connection count <= 0 not decrementing!\n";
1867 } else {
1868 $self->{conn_count}--;
1869 }
1870 }
1871 $self->{end_loop} = 1;
1872 }
1873
1874 $self->wait_end_loop() if $self->{end_loop};
1875 }
1876
1877 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1878 # because we write from multiple processes, and that would arbitrarily mix output
1879 # of all processes.
1880 sub open_access_log {
1881 my ($self, $filename) = @_;
1882
1883 my $old_mask = umask(0137);;
1884 my $logfh = IO::File->new($filename, ">>") ||
1885 die "unable to open log file '$filename' - $!\n";
1886 umask($old_mask);
1887
1888 $logfh->autoflush(1);
1889
1890 $self->{logfh} = $logfh;
1891 }
1892
1893 sub write_log {
1894 my ($self, $data) = @_;
1895
1896 return if !defined($self->{logfh}) || !$data;
1897
1898 my $res = $self->{logfh}->print($data);
1899
1900 if (!$res) {
1901 delete $self->{logfh};
1902 syslog('err', "error writing access log");
1903 $self->{end_loop} = 1; # terminate asap
1904 }
1905 }
1906
1907 sub atfork_handler {
1908 my ($self) = @_;
1909
1910 eval {
1911 # something else do to ?
1912 close($self->{socket});
1913 };
1914 warn $@ if $@;
1915 }
1916
1917 sub run {
1918 my ($self) = @_;
1919
1920 $self->{end_cond}->recv;
1921 }
1922
1923 sub new {
1924 my ($this, %args) = @_;
1925
1926 my $class = ref($this) || $this;
1927
1928 foreach my $req (qw(socket lockfh lockfile)) {
1929 die "misssing required argument '$req'" if !defined($args{$req});
1930 }
1931
1932 my $self = bless { %args }, $class;
1933
1934 $self->{cookie_name} //= 'PVEAuthCookie';
1935 $self->{apitoken_name} //= 'PVEAPIToken';
1936 $self->{base_uri} //= "/api2";
1937 $self->{dirs} //= {};
1938 $self->{title} //= 'API Inspector';
1939 $self->{compression} //= 1;
1940
1941 # formatter_config: we pass some configuration values to the Formatter
1942 $self->{formatter_config} = {};
1943 foreach my $p (qw(apitoken_name cookie_name base_uri title)) {
1944 $self->{formatter_config}->{$p} = $self->{$p};
1945 }
1946 $self->{formatter_config}->{csrfgen_func} =
1947 $self->can('generate_csrf_prevention_token');
1948
1949 # add default dirs which includes jquery and bootstrap
1950 my $jsbase = '/usr/share/javascript';
1951 add_dirs($self->{dirs}, '/js/' => "$jsbase/");
1952 # libjs-bootstrap uses symlinks for this, which we do not want to allow..
1953 my $glyphicons = '/usr/share/fonts/truetype/glyphicons/';
1954 add_dirs($self->{dirs}, '/js/bootstrap/fonts/' => "$glyphicons");
1955
1956 # init inotify
1957 PVE::INotify::inotify_init();
1958
1959 fh_nonblocking($self->{socket}, 1);
1960
1961 $self->{end_loop} = 0;
1962 $self->{conn_count} = 0;
1963 $self->{request_count} = 0;
1964 $self->{timeout} = 5 if !$self->{timeout};
1965 $self->{keep_alive} = 0 if !defined($self->{keep_alive});
1966 $self->{max_conn} = 800 if !$self->{max_conn};
1967 $self->{max_requests} = 8000 if !$self->{max_requests};
1968
1969 $self->{policy} = 'allow' if !$self->{policy};
1970
1971 $self->{end_cond} = AnyEvent->condvar;
1972
1973 if ($self->{ssl}) {
1974 my $ssl_defaults = {
1975 # Note: older versions are considered insecure, for example
1976 # search for "Poodle"-Attack
1977 method => 'any',
1978 sslv2 => 0,
1979 sslv3 => 0,
1980 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',
1981 honor_cipher_order => 1,
1982 };
1983
1984 # workaround until anyevent supports TLS 1.3 ciphersuites directly
1985 my $ciphersuites = delete $self->{ssl}->{ciphersuites};
1986
1987 foreach my $k (keys %$ssl_defaults) {
1988 $self->{ssl}->{$k} //= $ssl_defaults->{$k};
1989 }
1990
1991 if (!defined($self->{ssl}->{dh_file})) {
1992 $self->{ssl}->{dh} = 'skip2048';
1993 }
1994
1995 my $tls_ctx_flags = 0;
1996 $tls_ctx_flags |= &Net::SSLeay::OP_NO_COMPRESSION;
1997 $tls_ctx_flags |= &Net::SSLeay::OP_SINGLE_ECDH_USE;
1998 $tls_ctx_flags |= &Net::SSLeay::OP_SINGLE_DH_USE;
1999 $tls_ctx_flags |= &Net::SSLeay::OP_NO_RENEGOTIATION;
2000 if (delete $self->{ssl}->{honor_cipher_order}) {
2001 $tls_ctx_flags |= &Net::SSLeay::OP_CIPHER_SERVER_PREFERENCE;
2002 }
2003 # workaround until anyevent supports disabling TLS 1.3 directly
2004 if (exists($self->{ssl}->{tlsv1_3}) && !$self->{ssl}->{tlsv1_3}) {
2005 $tls_ctx_flags |= &Net::SSLeay::OP_NO_TLSv1_3;
2006 }
2007
2008
2009 $self->{tls_ctx} = AnyEvent::TLS->new(%{$self->{ssl}});
2010 Net::SSLeay::CTX_set_options($self->{tls_ctx}->{ctx}, $tls_ctx_flags);
2011 if (defined($ciphersuites)) {
2012 warn "Failed to set TLS 1.3 ciphersuites '$ciphersuites'\n"
2013 if !Net::SSLeay::CTX_set_ciphersuites($self->{tls_ctx}->{ctx}, $ciphersuites);
2014 }
2015 }
2016
2017 if ($self->{spiceproxy}) {
2018 $known_methods = { CONNECT => 1 };
2019 }
2020
2021 $self->open_access_log($self->{logfile}) if $self->{logfile};
2022
2023 $self->{max_conn_soft_limit} = $self->{max_conn} > 100 ? $self->{max_conn} - 20 : $self->{max_conn};
2024
2025 $self->{socket_watch} = AnyEvent->io(fh => $self->{socket}, poll => 'r', cb => sub {
2026 eval {
2027 if ($self->{conn_count} >= $self->{max_conn}) {
2028 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
2029 if ($self->{conn_count} < $self->{max_conn}) {
2030 undef $w;
2031 $self->accept_connections();
2032 }
2033 });
2034 } else {
2035 $self->accept_connections();
2036 }
2037 };
2038 warn $@ if $@;
2039 });
2040
2041 $self->{term_watch} = AnyEvent->signal(signal => "TERM", cb => sub {
2042 undef $self->{term_watch};
2043 $self->wait_end_loop();
2044 });
2045
2046 $self->{quit_watch} = AnyEvent->signal(signal => "QUIT", cb => sub {
2047 undef $self->{quit_watch};
2048 $self->wait_end_loop();
2049 });
2050
2051 $self->{inotify_poll} = AnyEvent->timer(after => 5, interval => 5, cb => sub {
2052 PVE::INotify::poll(); # read inotify events
2053 });
2054
2055 return $self;
2056 }
2057
2058 # static helper to add directory including all subdirs
2059 # This can be used to setup $self->{dirs}
2060 sub add_dirs {
2061 my ($result_hash, $alias, $subdir) = @_;
2062
2063 $result_hash->{$alias} = $subdir;
2064
2065 my $wanted = sub {
2066 my $dir = $File::Find::dir;
2067 if ($dir =~m!^$subdir(.*)$!) {
2068 my $name = "$alias$1/";
2069 $result_hash->{$name} = "$dir/";
2070 }
2071 };
2072
2073 find({wanted => $wanted, follow => 0, no_chdir => 1}, $subdir);
2074 }
2075
2076 # abstract functions - subclass should overwrite/implement them
2077
2078 sub verify_spice_connect_url {
2079 my ($self, $connect_str) = @_;
2080
2081 die "implement me";
2082
2083 #return ($vmid, $node, $port);
2084 }
2085
2086 # formatters can call this when the generate a new page
2087 sub generate_csrf_prevention_token {
2088 my ($username) = @_;
2089
2090 return undef; # do nothing by default
2091 }
2092
2093 sub auth_handler {
2094 my ($self, $method, $rel_uri, $ticket, $token, $api_token, $peer_host) = @_;
2095
2096 die "implement me";
2097
2098 # return {
2099 # ticket => $ticket,
2100 # token => $token,
2101 # userid => $username,
2102 # age => $age,
2103 # isUpload => $isUpload,
2104 # api_token => $api_token,
2105 #};
2106 }
2107
2108 sub rest_handler {
2109 my ($self, $clientip, $method, $rel_uri, $auth, $params, $format) = @_;
2110
2111 # please do not raise exceptions here (always return a result).
2112
2113 return {
2114 status => HTTP_NOT_IMPLEMENTED,
2115 message => "Method '$method $rel_uri' not implemented",
2116 };
2117
2118 # this should return the following properties, which
2119 # are then passed to the Formatter
2120
2121 # status: HTTP status code
2122 # message: Error message
2123 # errors: more detailed error hash (per parameter)
2124 # info: reference to JSON schema definition - useful to format output
2125 # data: result data
2126
2127 # total: additional info passed to output
2128 # changes: additional info passed to output
2129
2130 # if you want to proxy the request to another node return this
2131 # { proxy => $remip, proxynode => $node, proxy_params => $params };
2132
2133 # to pass the request to the local priviledged daemon use:
2134 # { proxy => 'localhost' , proxy_params => $params };
2135
2136 # to download aspecific file use:
2137 # { download => "/path/to/file" };
2138 }
2139
2140 sub check_cert_fingerprint {
2141 my ($self, $cert) = @_;
2142
2143 die "implement me";
2144 }
2145
2146 sub initialize_cert_cache {
2147 my ($self, $node) = @_;
2148
2149 die "implement me";
2150 }
2151
2152 sub remote_node_ip {
2153 my ($self, $node) = @_;
2154
2155 die "implement me";
2156
2157 # return $remip;
2158 }
2159
2160
2161 1;