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