]> git.proxmox.com Git - pve-http-server.git/blame - PVE/APIServer/AnyEvent.pm
fix debian/rules permissions
[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
d8218001
DM
670 my $params;
671
672 if ($upload_state) {
673 $params = $upload_state->{params};
674 } else {
675 $params = extract_params($r, $method);
676 }
677
678 delete $params->{_dc}; # remove disable cache parameter
679
680 my $clientip = $reqstate->{peer_host};
681
d8218001
DM
682 my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params);
683
684 AnyEvent->now_update(); # in case somebody called sleep()
685
d8218001
DM
686 my $upgrade = $r->header('upgrade');
687 $upgrade = lc($upgrade) if $upgrade;
688
689 if (my $host = $res->{proxy}) {
690
691 if ($self->{trusted_env}) {
692 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy not allowed");
693 return;
694 }
695
696 if ($host ne 'localhost' && $r->header('PVEDisableProxy')) {
697 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy loop detected");
698 return;
699 }
700
701 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
702
703 $self->proxy_request($reqstate, $clientip, $host, $res->{proxynode}, $method,
704 $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params}, $res->{proxynode});
705 return;
706
707 } elsif ($upgrade && ($method eq 'GET') && ($path =~ m|websocket$|)) {
708 die "unable to upgrade to protocol '$upgrade'\n" if !$upgrade || ($upgrade ne 'websocket');
709 my $wsver = $r->header('sec-websocket-version');
710 die "unsupported websocket-version '$wsver'\n" if !$wsver || ($wsver ne '13');
711 my $wsproto_str = $r->header('sec-websocket-protocol');
712 die "missing websocket-protocol header" if !$wsproto_str;
713 my $wsproto;
714 foreach my $p (PVE::Tools::split_list($wsproto_str)) {
715 $wsproto = $p if !$wsproto && $p eq 'base64';
716 $wsproto = $p if $p eq 'binary';
717 }
718 die "unsupported websocket-protocol protocol '$wsproto_str'\n" if !$wsproto;
719 my $wskey = $r->header('sec-websocket-key');
720 die "missing websocket-key\n" if !$wskey;
721 # Note: Digest::SHA::sha1_base64 has wrong padding
722 my $wsaccept = Digest::SHA::sha1_base64("${wskey}258EAFA5-E914-47DA-95CA-C5AB0DC85B11") . "=";
723 if ($res->{status} == HTTP_OK) {
724 $self->websocket_proxy($reqstate, $wsaccept, $wsproto, $res->{data});
725 return;
726 }
727 }
728
729 my $delay = 0;
730 if ($res->{status} == HTTP_UNAUTHORIZED) {
731 # always delay unauthorized calls by 3 seconds
732 $delay = 3 - tv_interval($reqstate->{starttime});
733 $delay = 0 if $delay < 0;
734 }
735
ca304f91
DM
736 my ($raw, $ct, $nocomp) = $formatter->($res, $res->{data}, $params, $path,
737 $auth, $self->{formatter_config});
d8218001
DM
738
739 my $resp;
740 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
741 $resp = $raw;
742 } else {
743 $resp = HTTP::Response->new($res->{status}, $res->{message});
744 $resp->header("Content-Type" => $ct);
745 $resp->content($raw);
746 }
747 $self->response($reqstate, $resp, undef, $nocomp, $delay);
748 };
749 if (my $err = $@) {
750 $self->error($reqstate, 501, $err);
751 }
752}
753
754sub handle_spice_proxy_request {
755 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
756
757 eval {
758
759 die "Port $spiceport is not allowed" if ($spiceport < 61000 || $spiceport > 61099);
760
d8218001
DM
761 my $clientip = $reqstate->{peer_host};
762 my $r = $reqstate->{request};
763
764 my $remip;
765
766 if ($node ne 'localhost' && PVE::INotify::nodename() !~ m/^$node$/i) {
767 $remip = $self->remote_node_ip($node);
768 print "REMOTE CONNECT $vmid, $remip, $connect_str\n" if $self->{debug};
769 } else {
770 print "$$: CONNECT $vmid, $node, $spiceport\n" if $self->{debug};
771 }
772
773 if ($remip && $r->header('PVEDisableProxy')) {
774 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy loop detected");
775 return;
776 }
777
778 $reqstate->{hdl}->timeout(0);
779 $reqstate->{hdl}->wbuf_max(64*10*1024);
780
781 my $remhost = $remip ? $remip : "localhost";
782 my $remport = $remip ? 3128 : $spiceport;
783
784 tcp_connect $remhost, $remport, sub {
5f14e56e 785 my ($fh) = @_
d8218001
DM
786 or die "connect to '$remhost:$remport' failed: $!";
787
788 print "$$: CONNECTed to '$remhost:$remport'\n" if $self->{debug};
789 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
790 fh => $fh,
791 rbuf_max => 64*1024,
792 wbuf_max => 64*10*1024,
793 timeout => 5,
794 on_eof => sub {
795 my ($hdl) = @_;
796 eval {
797 $self->log_aborted_request($reqstate);
798 $self->client_do_disconnect($reqstate);
799 };
800 if (my $err = $@) { syslog('err', $err); }
801 },
802 on_error => sub {
803 my ($hdl, $fatal, $message) = @_;
804 eval {
805 $self->log_aborted_request($reqstate, $message);
806 $self->client_do_disconnect($reqstate);
807 };
808 if (my $err = $@) { syslog('err', "$err"); }
809 });
810
811
812 my $proxyhdlreader = sub {
813 my ($hdl) = @_;
814
815 my $len = length($hdl->{rbuf});
816 my $data = substr($hdl->{rbuf}, 0, $len, '');
817
818 #print "READ1 $len\n";
819 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
820 };
821
822 my $hdlreader = sub {
823 my ($hdl) = @_;
824
825 my $len = length($hdl->{rbuf});
826 my $data = substr($hdl->{rbuf}, 0, $len, '');
827
828 #print "READ0 $len\n";
829 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
830 };
831
832 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
833
834 my $startproxy = sub {
835 $reqstate->{proxyhdl}->timeout(0);
836 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
837 $reqstate->{hdl}->on_read($hdlreader);
838
839 # todo: use stop_read/start_read if write buffer grows to much
840
841 my $res = "$proto 200 OK\015\012"; # hope this is the right answer?
842 $reqstate->{hdl}->push_write($res);
843
844 # log early
845 $reqstate->{log}->{code} = 200;
846 $self->log_request($reqstate);
847 };
848
849 if ($remip) {
850 my $header = "CONNECT ${connect_str} $proto\015\012" .
851 "Host: ${connect_str}\015\012" .
852 "Proxy-Connection: keep-alive\015\012" .
853 "User-Agent: spiceproxy\015\012" .
854 "PVEDisableProxy: true\015\012" .
855 "PVEClientIP: $clientip\015\012" .
856 "\015\012";
857
858 $reqstate->{proxyhdl}->push_write($header);
859 $reqstate->{proxyhdl}->push_read(line => sub {
860 my ($hdl, $line) = @_;
5f14e56e 861
d8218001
DM
862 if ($line =~ m!^$proto 200 OK$!) {
863 &$startproxy();
864 } else {
865 $reqstate->{hdl}->push_write($line);
866 $self->client_do_disconnect($reqstate);
867 }
868 });
869 } else {
870 &$startproxy();
871 }
872
873 };
874 };
875 if (my $err = $@) {
876 warn $err;
877 $self->log_aborted_request($reqstate, $err);
878 $self->client_do_disconnect($reqstate);
879 }
880}
881
882sub handle_request {
883 my ($self, $reqstate, $auth, $method, $path) = @_;
884
885 my $base_uri = $self->{base_uri};
886
887 eval {
888 my $r = $reqstate->{request};
5f14e56e 889
d8218001
DM
890 # disable timeout on handle (we already have all data we need)
891 # we re-enable timeout in response()
892 $reqstate->{hdl}->timeout(0);
893
894 if ($path =~ m/^\Q$base_uri\E/) {
895 $self->handle_api2_request($reqstate, $auth, $method, $path);
896 return;
897 }
898
899 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
900 if (ref($handler) eq 'CODE') {
901 my $params = decode_urlencoded($r->url->query());
902 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
903 $self->response($reqstate, $resp);
904 } elsif (ref($handler) eq 'HASH') {
905 if (my $filename = $handler->{file}) {
906 my $fh = IO::File->new($filename) ||
907 die "unable to open file '$filename' - $!\n";
908 send_file_start($self, $reqstate, $filename);
909 } else {
910 die "internal error - no handler";
911 }
912 } else {
913 die "internal error - no handler";
914 }
915 return;
916 }
917
918 if ($self->{dirs} && ($method eq 'GET')) {
919 # we only allow simple names
920 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
921 my ($subdir, $file) = ($1, $2);
922 if (my $dir = $self->{dirs}->{$subdir}) {
923 my $filename = "$dir$file";
924 my $fh = IO::File->new($filename) ||
925 die "unable to open file '$filename' - $!\n";
926 send_file_start($self, $reqstate, $filename);
927 return;
928 }
929 }
930 }
931
932 die "no such file '$path'";
933 };
934 if (my $err = $@) {
935 $self->error($reqstate, 501, $err);
936 }
937}
938
939sub file_upload_multipart {
940 my ($self, $reqstate, $auth, $method, $path, $rstate) = @_;
941
942 eval {
943 my $boundary = $rstate->{boundary};
944 my $hdl = $reqstate->{hdl};
945
946 my $startlen = length($hdl->{rbuf});
947
948 if ($rstate->{phase} == 0) { # skip everything until start
949 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
950 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
951 my $header = $1;
952 my ($ct, $disp, $name, $filename);
953 foreach my $line (split(/\015?\012/, $header)) {
954 # assume we have single line headers
955 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
956 $ct = parse_content_type($1);
957 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
958 ($disp, $name, $filename) = parse_content_disposition($1);
959 }
960 }
961
962 if (!($disp && $disp eq 'form-data' && $name)) {
963 syslog('err', "wrong content disposition in multipart - abort upload");
964 $rstate->{phase} = -1;
965 } else {
966
967 $rstate->{fieldname} = $name;
968
969 if ($filename) {
970 if ($name eq 'filename') {
971 # found file upload data
972 $rstate->{phase} = 1;
973 $rstate->{filename} = $filename;
974 } else {
975 syslog('err', "wrong field name for file upload - abort upload");
976 $rstate->{phase} = -1;
977 }
978 } else {
979 # found form data for field $name
980 $rstate->{phase} = 2;
981 }
982 }
983 } else {
984 my $len = length($hdl->{rbuf});
5f14e56e 985 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
d8218001
DM
986 if $len > $rstate->{maxheader}; # skip garbage
987 }
988 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
989 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
990 my ($rest, $eof) = ($1, $3);
991 my $len = length($rest);
5f14e56e 992 die "write to temporary file failed - $!"
d8218001
DM
993 if syswrite($rstate->{outfh}, $rest) != $len;
994 $rstate->{ctx}->add($rest);
995 $rstate->{params}->{filename} = $rstate->{filename};
996 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
997 $rstate->{bytes} += $len;
998 $rstate->{phase} = $eof ? 100 : 0;
999 } else {
1000 my $len = length($hdl->{rbuf});
1001 my $wlen = $len - $rstate->{boundlen};
1002 if ($wlen > 0) {
1003 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
5f14e56e 1004 die "write to temporary file failed - $!"
d8218001
DM
1005 if syswrite($rstate->{outfh}, $data) != $wlen;
1006 $rstate->{bytes} += $wlen;
1007 $rstate->{ctx}->add($data);
1008 }
1009 }
1010 } elsif ($rstate->{phase} == 2) { # inside normal field
1011
1012 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
1013 my ($rest, $eof) = ($1, $3);
1014 my $len = length($rest);
1015 $rstate->{post_size} += $len;
1016 if ($rstate->{post_size} < $limit_max_post) {
1017 $rstate->{params}->{$rstate->{fieldname}} = $rest;
1018 $rstate->{phase} = $eof ? 100 : 0;
1019 } else {
1020 syslog('err', "form data to large - abort upload");
1021 $rstate->{phase} = -1; # skip
1022 }
1023 }
5f14e56e 1024 } else { # skip
d8218001
DM
1025 my $len = length($hdl->{rbuf});
1026 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
1027 }
1028
1029 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
1030
1031 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
5f14e56e 1032 $rstate->{done} = 1; # make sure we dont get called twice
d8218001 1033 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
5f14e56e 1034 die "upload failed\n";
d8218001
DM
1035 } else {
1036 my $elapsed = tv_interval($rstate->{starttime});
1037
1038 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
5f14e56e
DM
1039 syslog('info', "multipart upload complete " .
1040 "(size: %d time: %ds rate: %.2fMiB/s md5sum: $rstate->{md5sum})",
d8218001
DM
1041 $rstate->{bytes}, $elapsed, $rate);
1042 $self->handle_api2_request($reqstate, $auth, $method, $path, $rstate);
1043 }
1044 }
1045 };
1046 if (my $err = $@) {
1047 syslog('err', $err);
1048 $self->error($reqstate, 501, $err);
1049 }
1050}
1051
1052sub parse_content_type {
1053 my ($ctype) = @_;
1054
1055 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
5f14e56e 1056
d8218001
DM
1057 foreach my $v (@params) {
1058 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
1059 return wantarray ? ($ct, $1) : $ct;
1060 }
1061 }
5f14e56e 1062
d8218001
DM
1063 return wantarray ? ($ct) : $ct;
1064}
1065
1066sub parse_content_disposition {
1067 my ($line) = @_;
1068
1069 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
1070 my $name;
1071 my $filename;
1072
1073 foreach my $v (@params) {
1074 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
1075 $name = $1;
1076 $name =~ s/^"(.*)"$/$1/;
1077 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
1078 $filename = $1;
1079 $filename =~ s/^"(.*)"$/$1/;
1080 }
1081 }
5f14e56e 1082
d8218001
DM
1083 return wantarray ? ($disp, $name, $filename) : $disp;
1084}
1085
1086my $tmpfile_seq_no = 0;
1087
1088sub get_upload_filename {
1089 # choose unpredictable tmpfile name
5f14e56e 1090
d8218001
DM
1091 $tmpfile_seq_no++;
1092 return "/var/tmp/pveupload-" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
1093}
1094
1095sub unshift_read_header {
1096 my ($self, $reqstate, $state) = @_;
1097
1098 $state = { size => 0, count => 0 } if !$state;
1099
1100 $reqstate->{hdl}->unshift_read(line => sub {
1101 my ($hdl, $line) = @_;
1102
1103 eval {
1104 # print "$$: got header: $line\n" if $self->{debug};
1105
1106 die "to many http header lines\n" if ++$state->{count} >= $limit_max_headers;
1107 die "http header too large\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
1108
1109 my $r = $reqstate->{request};
1110 if ($line eq '') {
1111
1112 my $path = uri_unescape($r->uri->path());
1113 my $method = $r->method();
1114
1115 $r->push_header($state->{key}, $state->{val})
1116 if $state->{key};
1117
1118 if (!$known_methods->{$method}) {
1119 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available");
1120 $self->response($reqstate, $resp);
1121 return;
1122 }
1123
1124 my $conn = $r->header('Connection');
1125 my $accept_enc = $r->header('Accept-Encoding');
1126 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
1127
1128 if ($conn) {
1129 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
1130 } else {
1131 if ($reqstate->{proto}->{ver} < 1001) {
1132 $reqstate->{keep_alive} = 0;
1133 }
1134 }
1135
1136 my $te = $r->header('Transfer-Encoding');
1137 if ($te && lc($te) eq 'chunked') {
1138 # Handle chunked transfer encoding
1139 $self->error($reqstate, 501, "chunked transfer encoding not supported");
1140 return;
1141 } elsif ($te) {
1142 $self->error($reqstate, 501, "Unknown transfer encoding '$te'");
1143 return;
1144 }
1145
1146 my $pveclientip = $r->header('PVEClientIP');
1147 my $base_uri = $self->{base_uri};
1148
1149 # fixme: how can we make PVEClientIP header trusted?
1150 if ($self->{trusted_env} && $pveclientip) {
1151 $reqstate->{peer_host} = $pveclientip;
1152 } else {
1153 $r->header('PVEClientIP', $reqstate->{peer_host});
1154 }
1155
1156 my $len = $r->header('Content-Length');
1157
1158 # header processing complete - authenticate now
1159
1160 my $auth = {};
1161 if ($self->{spiceproxy}) {
1162 my $connect_str = $r->header('Host');
403964f2 1163 my ($vmid, $node, $port) = $self->verify_spice_connect_url($connect_str);
d8218001
DM
1164 if (!(defined($vmid) && $node && $port)) {
1165 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket");
1166 return;
1167 }
1168 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
1169 return;
1170 } elsif ($path =~ m/^\Q$base_uri\E/) {
1171 my $token = $r->header('CSRFPreventionToken');
1172 my $cookie = $r->header('Cookie');
63307beb 1173 my $ticket = PVE::APIServer::Formatter::extract_auth_cookie($cookie, $self->{cookie_name});
d8218001
DM
1174
1175 my ($rel_uri, $format) = &$split_abs_uri($path, $self->{base_uri});
1176 if (!$format) {
1177 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri");
1178 return;
1179 }
1180
d8218001 1181 eval {
58ddb769
DM
1182 $auth = $self->auth_handler($method, $rel_uri, $ticket, $token,
1183 $reqstate->{peer_host});
d8218001
DM
1184 };
1185 if (my $err = $@) {
1186 # always delay unauthorized calls by 3 seconds
1187 my $delay = 3;
63307beb 1188 if (my $formatter = PVE::APIServer::Formatter::get_login_formatter($format)) {
ca304f91
DM
1189 my ($raw, $ct, $nocomp) =
1190 $formatter->($path, $auth, $self->{formatter_config});
d8218001
DM
1191 my $resp;
1192 if (ref($raw) && (ref($raw) eq 'HTTP::Response')) {
1193 $resp = $raw;
1194 } else {
1195 $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, "Login Required");
1196 $resp->header("Content-Type" => $ct);
1197 $resp->content($raw);
1198 }
1199 $self->response($reqstate, $resp, undef, $nocomp, 3);
1200 } else {
1201 my $resp = HTTP::Response->new(HTTP_UNAUTHORIZED, $err);
1202 $self->response($reqstate, $resp, undef, 0, $delay);
1203 }
1204 return;
1205 }
1206 }
1207
1208 $reqstate->{log}->{userid} = $auth->{userid};
1209
1210 if ($len) {
1211
1212 if (!($method eq 'PUT' || $method eq 'POST')) {
1213 $self->error($reqstate, 501, "Unexpected content for method '$method'");
1214 return;
1215 }
1216
1217 my $ctype = $r->header('Content-Type');
1218 my ($ct, $boundary) = parse_content_type($ctype) if $ctype;
1219
1220 if ($auth->{isUpload} && !$self->{trusted_env}) {
5f14e56e 1221 die "upload 'Content-Type '$ctype' not implemented\n"
d8218001
DM
1222 if !($boundary && $ct && ($ct eq 'multipart/form-data'));
1223
1224 die "upload without content length header not supported" if !$len;
1225
1226 die "upload without content length header not supported" if !$len;
1227
1228 print "start upload $path $ct $boundary\n" if $self->{debug};
1229
1230 my $tmpfilename = get_upload_filename();
1231 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
1232 die "unable to create temporary upload file '$tmpfilename'";
1233
1234 $reqstate->{keep_alive} = 0;
1235
1236 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
1237
1238 my $state = {
1239 size => $len,
1240 boundary => $boundary,
1241 ctx => Digest::MD5->new,
1242 boundlen => $boundlen,
1243 maxheader => 2048 + $boundlen, # should be large enough
1244 params => decode_urlencoded($r->url->query()),
1245 phase => 0,
1246 read => 0,
1247 post_size => 0,
1248 starttime => [gettimeofday],
1249 outfh => $outfh,
1250 };
1251 $reqstate->{tmpfilename} = $tmpfilename;
1252 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $method, $path, $state); });
1253 return;
1254 }
1255
1256 if ($len > $limit_max_post) {
1257 $self->error($reqstate, 501, "for data too large");
1258 return;
1259 }
1260
1261 if (!$ct || $ct eq 'application/x-www-form-urlencoded') {
1262 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
1263 my ($hdl, $data) = @_;
1264 $r->content($data);
1265 $self->handle_request($reqstate, $auth, $method, $path);
1266 });
1267 } else {
1268 $self->error($reqstate, 506, "upload 'Content-Type '$ctype' not implemented");
1269 }
1270 } else {
1271 $self->handle_request($reqstate, $auth, $method, $path);
1272 }
1273 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
1274 $r->push_header($state->{key}, $state->{val}) if $state->{key};
1275 ($state->{key}, $state->{val}) = ($1, $2);
1276 $self->unshift_read_header($reqstate, $state);
1277 } elsif ($line =~ /^\s+(.*)/) {
1278 $state->{val} .= " $1";
1279 $self->unshift_read_header($reqstate, $state);
1280 } else {
1281 $self->error($reqstate, 506, "unable to parse request header");
1282 }
1283 };
1284 warn $@ if $@;
1285 });
1286};
1287
1288sub push_request_header {
1289 my ($self, $reqstate) = @_;
1290
1291 eval {
1292 $reqstate->{hdl}->push_read(line => sub {
1293 my ($hdl, $line) = @_;
1294
1295 eval {
1296 # print "got request header: $line\n" if $self->{debug};
1297
1298 $reqstate->{keep_alive}--;
1299
1300 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1301 my ($method, $url, $maj, $min) = ($1, $2, $3, $4);
1302
1303 if ($maj != 1) {
1304 $self->error($reqstate, 506, "http protocol version $maj.$min not supported");
1305 return;
1306 }
1307
1308 $self->{request_count}++; # only count valid request headers
1309 if ($self->{request_count} >= $self->{max_requests}) {
1310 $self->{end_loop} = 1;
1311 }
1312 $reqstate->{log} = { requestline => $line };
1313 $reqstate->{proto}->{str} = "HTTP/$maj.$min";
1314 $reqstate->{proto}->{maj} = $maj;
1315 $reqstate->{proto}->{min} = $min;
1316 $reqstate->{proto}->{ver} = $maj*1000+$min;
1317 $reqstate->{request} = HTTP::Request->new($method, $url);
1318 $reqstate->{starttime} = [gettimeofday],
1319
1320 $self->unshift_read_header($reqstate);
1321 } elsif ($line eq '') {
1322 # ignore empty lines before requests (browser bugs?)
1323 $self->push_request_header($reqstate);
1324 } else {
1325 $self->error($reqstate, 400, 'bad request');
1326 }
1327 };
1328 warn $@ if $@;
1329 });
1330 };
1331 warn $@ if $@;
1332}
1333
1334sub accept {
1335 my ($self) = @_;
1336
1337 my $clientfh;
1338
1339 return if $self->{end_loop};
1340
1341 # we need to m make sure that only one process calls accept
1342 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1343 next if $! == EINTR;
1344 die "could not get lock on file '$self->{lockfile}' - $!\n";
1345 }
1346
1347 my $again = 0;
1348 my $errmsg;
1349 eval {
1350 while (!$self->{end_loop} &&
1351 !defined($clientfh = $self->{socket}->accept()) &&
1352 ($! == EINTR)) {};
1353
1354 if ($self->{end_loop}) {
1355 $again = 0;
1356 } else {
1357 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1358 if (!defined($clientfh)) {
1359 $errmsg = "failed to accept connection: $!\n";
1360 }
1361 }
1362 };
1363 warn $@ if $@;
1364
1365 flock($self->{lockfh}, Fcntl::LOCK_UN());
1366
1367 if (!defined($clientfh)) {
1368 return if $again;
1369 die $errmsg if $errmsg;
1370 }
1371
1372 fh_nonblocking $clientfh, 1;
1373
1374 $self->{conn_count}++;
1375
1376 return $clientfh;
1377}
1378
1379sub wait_end_loop {
1380 my ($self) = @_;
1381
1382 $self->{end_loop} = 1;
1383
1384 undef $self->{socket_watch};
1385
1386 $0 = "$0 (shutdown)" if $0 !~ m/\(shutdown\)$/;
1387
1388 if ($self->{conn_count} <= 0) {
1389 $self->{end_cond}->send(1);
1390 return;
1391 }
1392
1393 # fork and exit, so that parent starts a new worker
1394 if (fork()) {
1395 exit(0);
1396 }
1397
1398 # else we need to wait until all open connections gets closed
1399 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1400 eval {
1401 # todo: test for active connections instead (we can abort idle connections)
1402 if ($self->{conn_count} <= 0) {
1403 undef $w;
1404 $self->{end_cond}->send(1);
1405 }
1406 };
1407 warn $@ if $@;
1408 });
1409}
1410
1411
1412sub check_host_access {
1413 my ($self, $clientip) = @_;
5f14e56e 1414
d8218001
DM
1415 my $cip = Net::IP->new($clientip);
1416
1417 my $match_allow = 0;
1418 my $match_deny = 0;
1419
1420 if ($self->{allow_from}) {
1421 foreach my $t (@{$self->{allow_from}}) {
1422 if ($t->overlaps($cip)) {
1423 $match_allow = 1;
1424 last;
1425 }
1426 }
1427 }
1428
1429 if ($self->{deny_from}) {
1430 foreach my $t (@{$self->{deny_from}}) {
1431 if ($t->overlaps($cip)) {
1432 $match_deny = 1;
1433 last;
1434 }
1435 }
1436 }
1437
1438 if ($match_allow == $match_deny) {
1439 # match both allow and deny, or no match
1440 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1441 }
1442
1443 return $match_allow;
1444}
1445
1446sub accept_connections {
1447 my ($self) = @_;
1448
1449 eval {
1450
1451 while (my $clientfh = $self->accept()) {
1452
1453 my $reqstate = { keep_alive => $self->{keep_alive} };
1454
1455 # stop keep-alive when there are many open connections
1456 if ($self->{conn_count} >= $self->{max_conn_soft_limit}) {
1457 $reqstate->{keep_alive} = 0;
1458 }
1459
1460 if (my $sin = getpeername($clientfh)) {
1461 my ($pfamily, $pport, $phost) = PVE::Tools::unpack_sockaddr_in46($sin);
1462 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntop($pfamily, $phost));
1463 }
1464
1465 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1466 print "$$: ABORT request from $reqstate->{peer_host} - access denied\n" if $self->{debug};
1467 $reqstate->{log}->{code} = 403;
1468 $self->log_request($reqstate);
1469 next;
1470 }
1471
1472 $reqstate->{hdl} = AnyEvent::Handle->new(
1473 fh => $clientfh,
1474 rbuf_max => 64*1024,
1475 timeout => $self->{timeout},
1476 linger => 0, # avoid problems with ssh - really needed ?
1477 on_eof => sub {
1478 my ($hdl) = @_;
1479 eval {
1480 $self->log_aborted_request($reqstate);
1481 $self->client_do_disconnect($reqstate);
1482 };
1483 if (my $err = $@) { syslog('err', $err); }
1484 },
1485 on_error => sub {
1486 my ($hdl, $fatal, $message) = @_;
1487 eval {
1488 $self->log_aborted_request($reqstate, $message);
1489 $self->client_do_disconnect($reqstate);
1490 };
1491 if (my $err = $@) { syslog('err', "$err"); }
1492 },
1493 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1494
1495 print "$$: ACCEPT FH" . $clientfh->fileno() . " CONN$self->{conn_count}\n" if $self->{debug};
1496
1497 $self->push_request_header($reqstate);
1498 }
1499 };
1500
1501 if (my $err = $@) {
1502 syslog('err', $err);
1503 $self->{end_loop} = 1;
1504 }
1505
1506 $self->wait_end_loop() if $self->{end_loop};
1507}
1508
1509# Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1510# because we write from multiple processes, and that would arbitrarily mix output
1511# of all processes.
1512sub open_access_log {
1513 my ($self, $filename) = @_;
1514
1515 my $old_mask = umask(0137);;
1516 my $logfh = IO::File->new($filename, ">>") ||
1517 die "unable to open log file '$filename' - $!\n";
1518 umask($old_mask);
1519
1520 $logfh->autoflush(1);
1521
1522 $self->{logfh} = $logfh;
1523}
1524
1525sub write_log {
1526 my ($self, $data) = @_;
1527
1528 return if !defined($self->{logfh}) || !$data;
1529
1530 my $res = $self->{logfh}->print($data);
1531
1532 if (!$res) {
1533 delete $self->{logfh};
1534 syslog('err', "error writing access log");
1535 $self->{end_loop} = 1; # terminate asap
1536 }
1537}
1538
1539sub atfork_handler {
1540 my ($self) = @_;
1541
1542 eval {
1543 # something else do to ?
1544 close($self->{socket});
1545 };
1546 warn $@ if $@;
1547}
1548
fbc42b33
DM
1549sub run {
1550 my ($self) = @_;
1551
1552 $self->{end_cond}->recv;
1553}
1554
d8218001
DM
1555sub new {
1556 my ($this, %args) = @_;
1557
1558 my $class = ref($this) || $this;
1559
af76fd78 1560 foreach my $req (qw(socket lockfh lockfile)) {
d8218001
DM
1561 die "misssing required argument '$req'" if !defined($args{$req});
1562 }
1563
1564 my $self = bless { %args }, $class;
1565
1566 $self->{cookie_name} //= 'PVEAuthCookie';
1567 $self->{base_uri} //= "/api2";
911ede9b 1568 $self->{dirs} //= {};
fc87cd5e 1569 $self->{title} //= 'API Inspector';
d8218001 1570
ca304f91
DM
1571 # formatter_config: we pass some configuration values to the Formatter
1572 $self->{formatter_config} = {};
1573 foreach my $p (qw(cookie_name base_uri title)) {
1574 $self->{formatter_config}->{$p} = $self->{$p};
1575 }
1576 $self->{formatter_config}->{csrfgen_func} =
1577 $self->can('generate_csrf_prevention_token');
1578
1579 # add default dirs which includes jquery and bootstrap
6edb39f6
DM
1580 my $base = '/usr/share/libpve-http-server-perl';
1581 add_dirs($self->{dirs}, '/css/' => "$base/css/");
1582 add_dirs($self->{dirs}, '/js/' => "$base/js/");
1583 add_dirs($self->{dirs}, '/fonts/' => "$base/fonts/");
1584
d8218001
DM
1585 # init inotify
1586 PVE::INotify::inotify_init();
1587
d8218001
DM
1588 fh_nonblocking($self->{socket}, 1);
1589
1590 $self->{end_loop} = 0;
1591 $self->{conn_count} = 0;
1592 $self->{request_count} = 0;
1593 $self->{timeout} = 5 if !$self->{timeout};
1594 $self->{keep_alive} = 0 if !defined($self->{keep_alive});
1595 $self->{max_conn} = 800 if !$self->{max_conn};
1596 $self->{max_requests} = 8000 if !$self->{max_requests};
1597
1598 $self->{policy} = 'allow' if !$self->{policy};
1599
1600 $self->{end_cond} = AnyEvent->condvar;
1601
1602 if ($self->{ssl}) {
1603 $self->{tls_ctx} = AnyEvent::TLS->new(%{$self->{ssl}});
5f14e56e
DM
1604 # TODO : openssl >= 1.0.2 supports SSL_CTX_set_ecdh_auto to select a curve depending on
1605 # server and client availability from SSL_CTX_set1_curves.
d8218001
DM
1606 # that way other curves like 25519 can be used.
1607 # openssl 1.0.1 can only support 1 curve at a time.
1608 my $curve = Net::SSLeay::OBJ_txt2nid('prime256v1');
1609 my $ecdh = Net::SSLeay::EC_KEY_new_by_curve_name($curve);
1610 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);
1611 Net::SSLeay::CTX_set_tmp_ecdh($self->{tls_ctx}->{ctx}, $ecdh);
1612 Net::SSLeay::EC_KEY_free($ecdh);
1613 }
1614
1615 if ($self->{spiceproxy}) {
1616 $known_methods = { CONNECT => 1 };
1617 }
1618
1619 $self->open_access_log($self->{logfile}) if $self->{logfile};
1620
1621 $self->{max_conn_soft_limit} = $self->{max_conn} > 100 ? $self->{max_conn} - 20 : $self->{max_conn};
1622
1623 $self->{socket_watch} = AnyEvent->io(fh => $self->{socket}, poll => 'r', cb => sub {
1624 eval {
1625 if ($self->{conn_count} >= $self->{max_conn}) {
1626 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1627 if ($self->{conn_count} < $self->{max_conn}) {
1628 undef $w;
1629 $self->accept_connections();
1630 }
1631 });
1632 } else {
1633 $self->accept_connections();
1634 }
1635 };
1636 warn $@ if $@;
1637 });
1638
1639 $self->{term_watch} = AnyEvent->signal(signal => "TERM", cb => sub {
1640 undef $self->{term_watch};
1641 $self->wait_end_loop();
1642 });
1643
1644 $self->{quit_watch} = AnyEvent->signal(signal => "QUIT", cb => sub {
1645 undef $self->{quit_watch};
1646 $self->wait_end_loop();
1647 });
1648
1649 $self->{inotify_poll} = AnyEvent->timer(after => 5, interval => 5, cb => sub {
1650 PVE::INotify::poll(); # read inotify events
1651 });
1652
1653 return $self;
1654}
1655
911ede9b
DM
1656# static helper to add directory including all subdirs
1657# This can be used to setup $self->{dirs}
1658sub add_dirs {
1659 my ($result_hash, $alias, $subdir) = @_;
1660
1661 $result_hash->{$alias} = $subdir;
1662
1663 my $wanted = sub {
1664 my $dir = $File::Find::dir;
1665 if ($dir =~m!^$subdir(.*)$!) {
1666 my $name = "$alias$1/";
1667 $result_hash->{$name} = "$dir/";
1668 }
1669 };
1670
1671 find({wanted => $wanted, follow => 0, no_chdir => 1}, $subdir);
1672}
1673
fbc42b33
DM
1674# abstract functions - subclass should overwrite/implement them
1675
403964f2
DM
1676sub verify_spice_connect_url {
1677 my ($self, $connect_str) = @_;
1678
1679 die "implement me";
1680
1681 #return ($vmid, $node, $port);
1682}
1683
a3bb6070
DM
1684# formatters can call this when the generate a new page
1685sub generate_csrf_prevention_token {
1686 my ($username) = @_;
1687
1688 return undef; # do nothing by default
1689}
1690
d8218001 1691sub auth_handler {
58ddb769 1692 my ($self, $method, $rel_uri, $ticket, $token, $peer_host) = @_;
d8218001 1693
b639f458 1694 die "implement me";
d8218001 1695
b639f458
DM
1696 # return {
1697 # ticket => $ticket,
1698 # token => $token,
1699 # userid => $username,
1700 # age => $age,
1701 # isUpload => $isUpload,
b639f458 1702 #};
d8218001
DM
1703}
1704
d8218001
DM
1705sub rest_handler {
1706 my ($self, $clientip, $method, $rel_uri, $auth, $params) = @_;
1707
c5f0a96f
DM
1708 # please do not raise exceptions here (always return a result).
1709
b639f458
DM
1710 return {
1711 status => HTTP_NOT_IMPLEMENTED,
1712 message => "Method '$method $rel_uri' not implemented",
d8218001 1713 };
c5f0a96f
DM
1714
1715 # this should return the following properties, which
1716 # are then passed to the Formatter
1717
1718 # status: HTTP status code
1719 # message: Error message
1720 # errors: more detailed error hash (per parameter)
1721 # info: reference to JSON schema definition - useful to format output
1722 # data: result data
1723
1724 # total: additional info passed to output
1725 # changes: additional info passed to output
1726
1727 # if you want to proxy the request to another node return this
1728 # { proxy => $remip, proxynode => $node, proxy_params => $params };
1729
1730 # to pass the request to the local priviledged daemon use:
1731 # { proxy => 'localhost' , proxy_params => $params };
d8218001
DM
1732}
1733
1734sub check_cert_fingerprint {
1735 my ($self, $cert) = @_;
1736
b639f458
DM
1737 die "implement me";
1738 }
d8218001
DM
1739
1740sub initialize_cert_cache {
1741 my ($self, $node) = @_;
1742
b639f458 1743 die "implement me";
d8218001
DM
1744}
1745
1746sub remote_node_ip {
1747 my ($self, $node) = @_;
1748
b639f458 1749 die "implement me";
d8218001 1750
b639f458 1751 # return $remip;
d8218001
DM
1752}
1753
d8218001
DM
1754
17551;