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