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