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