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