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