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