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