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