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