]> git.proxmox.com Git - pve-manager.git/blob - PVE/HTTPServer.pm
call $rpcenv->init_request before calling remote_node_ip
[pve-manager.git] / PVE / HTTPServer.pm
1 package PVE::HTTPServer;
2
3 use strict;
4 use warnings;
5 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
6 use Socket qw(IPPROTO_TCP TCP_NODELAY SOMAXCONN);
7 use POSIX qw(strftime EINTR EAGAIN);
8 use Fcntl;
9 use IO::File;
10 use File::stat qw();
11 use Digest::MD5;
12 # use AnyEvent::Strict; # only use this for debugging
13 use AnyEvent::Util qw(guard fh_nonblocking WSAEWOULDBLOCK WSAEINPROGRESS);
14 use AnyEvent::Socket;
15 use AnyEvent::Handle;
16 use AnyEvent::TLS;
17 use AnyEvent::IO;
18 use AnyEvent::HTTP;
19 use Fcntl ();
20 use Compress::Zlib;
21 use PVE::SafeSyslog;
22 use PVE::INotify;
23 use PVE::RPCEnvironment;
24 use PVE::REST;
25
26 use Net::IP;
27 use URI;
28 use HTTP::Status qw(:constants);
29 use HTTP::Headers;
30 use HTTP::Response;
31 use Data::Dumper;
32
33 my $limit_max_headers = 30;
34 my $limit_max_header_size = 8*1024;
35 my $limit_max_post = 16*1024;
36
37
38 my $known_methods = {
39 GET => 1,
40 POST => 1,
41 PUT => 1,
42 DELETE => 1,
43 };
44
45 my $baseuri = "/api2";
46
47 sub split_abs_uri {
48 my ($abs_uri) = @_;
49
50 my ($format, $rel_uri) = $abs_uri =~ m/^\Q$baseuri\E\/+(html|text|json|extjs|png|htmljs|spiceconfig)(\/.*)?$/;
51 $rel_uri = '/' if !$rel_uri;
52
53 return wantarray ? ($rel_uri, $format) : $rel_uri;
54 }
55
56 sub log_request {
57 my ($self, $reqstate) = @_;
58
59 my $loginfo = $reqstate->{log};
60
61 # like apache2 common log format
62 # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
63
64 return if $loginfo->{written}; # avoid duplicate logs
65 $loginfo->{written} = 1;
66
67 my $peerip = $reqstate->{peer_host} || '-';
68 my $userid = $loginfo->{userid} || '-';
69 my $content_length = defined($loginfo->{content_length}) ? $loginfo->{content_length} : '-';
70 my $code = $loginfo->{code} || 500;
71 my $requestline = $loginfo->{requestline} || '-';
72 my $timestr = strftime("%d/%b/%Y:%H:%M:%S %z", localtime());
73
74 my $msg = "$peerip - $userid [$timestr] \"$requestline\" $code $content_length\n";
75
76 $self->write_log($msg);
77 }
78
79 sub log_aborted_request {
80 my ($self, $reqstate, $error) = @_;
81
82 my $r = $reqstate->{request};
83 return if !$r; # no active request
84
85 if ($error) {
86 syslog("err", "problem with client $reqstate->{peer_host}; $error");
87 }
88
89 $self->log_request($reqstate);
90 }
91
92 sub cleanup_reqstate {
93 my ($reqstate) = @_;
94
95 delete $reqstate->{log};
96 delete $reqstate->{request};
97 delete $reqstate->{proto};
98 delete $reqstate->{accept_gzip};
99
100 if ($reqstate->{tmpfilename}) {
101 unlink $reqstate->{tmpfilename};
102 delete $reqstate->{tmpfilename};
103 }
104 }
105
106 sub client_do_disconnect {
107 my ($self, $reqstate) = @_;
108
109 cleanup_reqstate($reqstate);
110
111 my $shutdown_hdl = sub {
112 my $hdl = shift;
113
114 shutdown($hdl->{fh}, 1);
115 # clear all handlers
116 $hdl->on_drain(undef);
117 $hdl->on_read(undef);
118 $hdl->on_eof(undef);
119 };
120
121 if (my $proxyhdl = delete $reqstate->{proxyhdl}) {
122 &$shutdown_hdl($proxyhdl);
123 }
124
125 my $hdl = delete $reqstate->{hdl};
126
127 if (!$hdl) {
128 syslog('err', "detected empty handle");
129 return;
130 }
131
132 print "close connection $hdl\n" if $self->{debug};
133
134 &$shutdown_hdl($hdl);
135
136 $self->{conn_count}--;
137
138 print "$$: CLOSE FH" . $hdl->{fh}->fileno() . " CONN$self->{conn_count}\n" if $self->{debug};
139 }
140
141 sub finish_response {
142 my ($self, $reqstate) = @_;
143
144 my $hdl = $reqstate->{hdl};
145
146 cleanup_reqstate($reqstate);
147
148 if (!$self->{end_loop} && $reqstate->{keep_alive} > 0) {
149 # print "KEEPALIVE $reqstate->{keep_alive}\n" if $self->{debug};
150 $hdl->on_read(sub {
151 eval { $self->push_request_header($reqstate); };
152 warn $@ if $@;
153 });
154 } else {
155 $hdl->on_drain (sub {
156 eval {
157 $self->client_do_disconnect($reqstate);
158 };
159 warn $@ if $@;
160 });
161 }
162 }
163
164 sub response {
165 my ($self, $reqstate, $resp, $mtime, $nocomp) = @_;
166
167 #print "$$: send response: " . Dumper($resp);
168
169 # activate timeout
170 $reqstate->{hdl}->timeout_reset();
171 $reqstate->{hdl}->timeout($self->{timeout});
172
173 $nocomp = 1 if !$reqstate->{accept_gzip};
174
175 my $code = $resp->code;
176 my $msg = $resp->message || HTTP::Status::status_message($code);
177 ($msg) = $msg =~m/^(.*)$/m;
178 my $content = $resp->content;
179
180 if ($code =~ /^(1\d\d|[23]04)$/) {
181 # make sure content we have no content
182 $content = "";
183 }
184
185 $reqstate->{keep_alive} = 0 if ($code >= 400) || $self->{end_loop};
186
187 $reqstate->{log}->{code} = $code;
188
189 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
190 my $res = "$proto $code $msg\015\012";
191
192 my $ctime = time();
193 my $date = HTTP::Date::time2str($ctime);
194 $resp->header('Date' => $date);
195 if ($mtime) {
196 $resp->header('Last-Modified' => HTTP::Date::time2str($mtime));
197 } else {
198 $resp->header('Expires' => $date);
199 $resp->header('Cache-Control' => "max-age=0");
200 $resp->header("Pragma", "no-cache");
201 }
202
203 $resp->header('Server' => "pve-api-daemon/3.0");
204
205 my $content_length;
206 if ($content) {
207
208 $content_length = length($content);
209
210 if (!$nocomp && ($content_length > 1024)) {
211 my $comp = Compress::Zlib::memGzip($content);
212 $resp->header('Content-Encoding', 'gzip');
213 $content = $comp;
214 $content_length = length($content);
215 }
216 $resp->header("Content-Length" => $content_length);
217 $reqstate->{log}->{content_length} = $content_length;
218
219 } else {
220 $resp->remove_header("Content-Length");
221 }
222
223 if ($reqstate->{keep_alive} > 0) {
224 $resp->push_header('Connection' => 'Keep-Alive');
225 } else {
226 $resp->header('Connection' => 'close');
227 }
228
229 $res .= $resp->headers_as_string("\015\012");
230 #print "SEND(without content) $res\n" if $self->{debug};
231
232 $res .= "\015\012";
233 $res .= $content if $content;
234
235 $self->log_request($reqstate, $reqstate->{request});
236
237 $reqstate->{hdl}->push_write($res);
238 $self->finish_response($reqstate);
239 }
240
241 sub error {
242 my ($self, $reqstate, $code, $msg, $hdr, $content) = @_;
243
244 eval {
245 my $resp = HTTP::Response->new($code, $msg, $hdr, $content);
246 $self->response($reqstate, $resp);
247 };
248 warn $@ if $@;
249 }
250
251 sub send_file_start {
252 my ($self, $reqstate, $filename) = @_;
253
254 eval {
255 # print "SEND FILE $filename\n";
256 # Note: aio_load() this is not really async unless we use IO::AIO!
257 eval {
258
259 my $r = $reqstate->{request};
260
261 my $fh = IO::File->new($filename, '<') ||
262 die "$!\n";
263 my $stat = File::stat::stat($fh) ||
264 die "$!\n";
265
266 my $mtime = $stat->mtime;
267
268 if (my $ifmod = $r->header('if-modified-since')) {
269 my $iftime = HTTP::Date::str2time($ifmod);
270 if ($mtime <= $iftime) {
271 my $resp = HTTP::Response->new(304, "NOT MODIFIED");
272 $self->response($reqstate, $resp, $mtime);
273 return;
274 }
275 }
276
277 my $data;
278 my $len = sysread($fh, $data, $stat->size);
279 die "got short file\n" if !defined($len) || $len != $stat->size;
280
281 my $ct;
282 my $nocomp;
283 if ($filename =~ m/\.css$/) {
284 $ct = 'text/css';
285 } elsif ($filename =~ m/\.js$/) {
286 $ct = 'application/javascript';
287 } elsif ($filename =~ m/\.png$/) {
288 $ct = 'image/png';
289 $nocomp = 1;
290 } elsif ($filename =~ m/\.gif$/) {
291 $ct = 'image/gif';
292 $nocomp = 1;
293 } elsif ($filename =~ m/\.jar$/) {
294 $ct = 'application/java-archive';
295 $nocomp = 1;
296 } else {
297 die "unable to detect content type";
298 }
299
300 my $header = HTTP::Headers->new(Content_Type => $ct);
301 my $resp = HTTP::Response->new(200, "OK", $header, $data);
302 $self->response($reqstate, $resp, $mtime, $nocomp);
303 };
304 if (my $err = $@) {
305 $self->error($reqstate, 501, $err);
306 }
307 };
308
309 warn $@ if $@;
310 }
311
312 sub proxy_request {
313 my ($self, $reqstate, $clientip, $host, $method, $uri, $ticket, $token, $params) = @_;
314
315 eval {
316 my $target;
317 my $keep_alive = 1;
318 if ($host eq 'localhost') {
319 $target = "http://$host:85$uri";
320 # keep alive for localhost is not worth (connection setup is about 0.2ms)
321 $keep_alive = 0;
322 } else {
323 $target = "https://$host:8006$uri";
324 }
325
326 my $headers = {
327 PVEDisableProxy => 'true',
328 PVEClientIP => $clientip,
329 };
330
331 my $cookie_name = 'PVEAuthCookie';
332
333 $headers->{'cookie'} = PVE::REST::create_auth_cookie($ticket) if $ticket;
334 $headers->{'CSRFPreventionToken'} = $token if $token;
335 $headers->{'Accept-Encoding'} = 'gzip' if $reqstate->{accept_gzip};
336
337 my $content;
338
339 if ($method eq 'POST' || $method eq 'PUT') {
340 $headers->{'Content-Type'} = 'application/x-www-form-urlencoded';
341 # use URI object to format application/x-www-form-urlencoded content.
342 my $url = URI->new('http:');
343 $url->query_form(%$params);
344 $content = $url->query;
345 if (defined($content)) {
346 $headers->{'Content-Length'} = length($content);
347 }
348 }
349
350 my $w; $w = http_request(
351 $method => $target,
352 headers => $headers,
353 timeout => 30,
354 recurse => 0,
355 proxy => undef, # avoid use of $ENV{HTTP_PROXY}
356 keepalive => $keep_alive,
357 body => $content,
358 tls_ctx => $self->{tls_ctx},
359 sub {
360 my ($body, $hdr) = @_;
361
362 undef $w;
363
364 if (!$reqstate->{hdl}) {
365 warn "proxy detected vanished client connection\n";
366 return;
367 }
368
369 eval {
370 my $code = delete $hdr->{Status};
371 my $msg = delete $hdr->{Reason};
372 delete $hdr->{URL};
373 delete $hdr->{HTTPVersion};
374 my $header = HTTP::Headers->new(%$hdr);
375 my $resp = HTTP::Response->new($code, $msg, $header, $body);
376 # Note: disable compression, because body is already compressed
377 $self->response($reqstate, $resp, undef, 1);
378 };
379 warn $@ if $@;
380 });
381 };
382 warn $@ if $@;
383 }
384
385 # return arrays as \0 separated strings (like CGI.pm)
386 sub decode_urlencoded {
387 my ($data) = @_;
388
389 my $res = {};
390
391 return $res if !$data;
392
393 foreach my $kv (split(/[\&\;]/, $data)) {
394 my ($k, $v) = split(/=/, $kv);
395 $k =~s/\+/ /g;
396 $k =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
397 $v =~s/\+/ /g;
398 $v =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/eg;
399
400 if (defined(my $old = $res->{$k})) {
401 $res->{$k} = "$old\0$v";
402 } else {
403 $res->{$k} = $v;
404 }
405 }
406 return $res;
407 }
408
409 sub extract_params {
410 my ($r, $method) = @_;
411
412 my $params = {};
413
414 if ($method eq 'PUT' || $method eq 'POST') {
415 $params = decode_urlencoded($r->content);
416 }
417
418 my $query_params = decode_urlencoded($r->url->query());
419
420 foreach my $k (keys %{$query_params}) {
421 $params->{$k} = $query_params->{$k};
422 }
423
424 return PVE::Tools::decode_utf8_parameters($params);
425 }
426
427 sub handle_api2_request {
428 my ($self, $reqstate, $auth, $upload_state) = @_;
429
430 eval {
431 my $r = $reqstate->{request};
432 my $method = $r->method();
433 my $path = $r->uri->path();
434
435 my ($rel_uri, $format) = split_abs_uri($path);
436 if (!$format) {
437 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri");
438 return;
439 }
440
441 #print Dumper($upload_state) if $upload_state;
442
443 my $rpcenv = $self->{rpcenv};
444
445 my $params;
446
447 if ($upload_state) {
448 $params = $upload_state->{params};
449 } else {
450 $params = extract_params($r, $method);
451 }
452
453 delete $params->{_dc}; # remove disable cache parameter
454
455 my $clientip = $reqstate->{peer_host};
456
457 $rpcenv->init_request();
458
459 my $res = PVE::REST::rest_handler($rpcenv, $clientip, $method, $rel_uri, $auth, $params);
460
461 AnyEvent->now_update(); # in case somebody called sleep()
462
463 $rpcenv->set_user(undef); # clear after request
464
465 if ($res->{proxy}) {
466
467 if ($self->{trusted_env}) {
468 $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, "proxy not allowed");
469 return;
470 }
471
472 $res->{proxy_params}->{tmpfilename} = $reqstate->{tmpfilename} if $upload_state;
473
474 $self->proxy_request($reqstate, $clientip, $res->{proxy}, $method,
475 $r->uri, $auth->{ticket}, $auth->{token}, $res->{proxy_params});
476 return;
477
478 }
479
480 PVE::REST::prepare_response_data($format, $res);
481 my ($raw, $ct, $nocomp) = PVE::REST::format_response_data($format, $res, $path);
482
483 my $resp = HTTP::Response->new($res->{status}, $res->{message});
484 $resp->header("Content-Type" => $ct);
485 $resp->content($raw);
486 $self->response($reqstate, $resp, $nocomp);
487 };
488 if (my $err = $@) {
489 $self->error($reqstate, 501, $err);
490 }
491 }
492
493 sub handle_spice_proxy_request {
494 my ($self, $reqstate, $connect_str, $vmid, $node, $spiceport) = @_;
495
496 eval {
497
498 my $rpcenv = $self->{rpcenv};
499 $rpcenv->init_request();
500
501 my $remip;
502
503 if ($node ne 'localhost' && $node ne PVE::INotify::nodename()) {
504 $remip = PVE::Cluster::remote_node_ip($node);
505 die "unable to get remote IP address for node '$node'\n" if !$remip;
506 print "REMOTE CONNECT $vmid, $remip, $connect_str\n" if $self->{debug};
507 } else {
508 print "$$: CONNECT $vmid, $node, $spiceport\n" if $self->{debug};
509 }
510
511 $reqstate->{hdl}->timeout(0);
512 $reqstate->{hdl}->wbuf_max(64*10*1024);
513
514 my $remhost = $remip ? $remip : "127.0.0.1";
515 my $remport = $remip ? 3128 : $spiceport;
516
517 tcp_connect $remhost, $remport, sub {
518 my ($fh) = @_
519 or die "connect to '$remhost:$remport' failed: $!";
520
521 print "$$: CONNECTed to '$remhost:$remport'\n" if $self->{debug};
522 $reqstate->{proxyhdl} = AnyEvent::Handle->new(
523 fh => $fh,
524 rbuf_max => 64*1024,
525 wbuf_max => 64*10*1024,
526 timeout => 5,
527 on_eof => sub {
528 my ($hdl) = @_;
529 eval {
530 $self->log_aborted_request($reqstate);
531 $self->client_do_disconnect($reqstate);
532 };
533 if (my $err = $@) { syslog('err', $err); }
534 },
535 on_error => sub {
536 my ($hdl, $fatal, $message) = @_;
537 eval {
538 $self->log_aborted_request($reqstate, $message);
539 $self->client_do_disconnect($reqstate);
540 };
541 if (my $err = $@) { syslog('err', "$err"); }
542 });
543
544
545 my $proxyhdlreader = sub {
546 my ($hdl) = @_;
547
548 my $len = length($hdl->{rbuf});
549 my $data = substr($hdl->{rbuf}, 0, $len, '');
550
551 #print "READ1 $len\n";
552 $reqstate->{hdl}->push_write($data) if $reqstate->{hdl};
553 };
554
555 my $hdlreader = sub {
556 my ($hdl) = @_;
557
558 my $len = length($hdl->{rbuf});
559 my $data = substr($hdl->{rbuf}, 0, $len, '');
560
561 #print "READ0 $len\n";
562 $reqstate->{proxyhdl}->push_write($data) if $reqstate->{proxyhdl};
563 };
564
565 my $proto = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0';
566
567 my $startproxy = sub {
568 $reqstate->{proxyhdl}->timeout(0);
569 $reqstate->{proxyhdl}->on_read($proxyhdlreader);
570 $reqstate->{hdl}->on_read($hdlreader);
571
572 # todo: use stop_read/start_read if write buffer grows to much
573
574 my $res = "$proto 200 OK\015\012"; # hope this is the right answer?
575 $reqstate->{hdl}->push_write($res);
576
577 # log early
578 $reqstate->{log}->{code} = 200;
579 $self->log_request($reqstate);
580 };
581
582 if ($remip) {
583 my $header = "CONNECT ${connect_str} $proto\015\012" .
584 "Host: ${connect_str}\015\012" .
585 "Proxy-Connection: keep-alive\015\012" .
586 "User-Agent: spiceproxy\015\012" .
587 "\015\012";
588 $reqstate->{proxyhdl}->push_write($header);
589 $reqstate->{proxyhdl}->push_read(line => sub {
590 my ($hdl, $line) = @_;
591
592 if ($line =~ m!^$proto 200 OK$!) {
593 &$startproxy();
594 } else {
595 $reqstate->{hdl}->push_write($line);
596 $self->client_do_disconnect($reqstate);
597 }
598 });
599 } else {
600 &$startproxy();
601 }
602
603 };
604 };
605 if (my $err = $@) {
606 $self->log_aborted_request($reqstate, $err);
607 $self->client_do_disconnect($reqstate);
608 }
609 }
610
611 sub handle_request {
612 my ($self, $reqstate, $auth) = @_;
613
614 eval {
615 my $r = $reqstate->{request};
616 my $method = $r->method();
617 my $path = $r->uri->path();
618
619 # disable timeout on handle (we already have all data we need)
620 # we re-enable timeout in response()
621 $reqstate->{hdl}->timeout(0);
622
623 if ($path =~ m!$baseuri!) {
624 $self->handle_api2_request($reqstate, $auth);
625 return;
626 }
627
628 if ($self->{pages} && ($method eq 'GET') && (my $handler = $self->{pages}->{$path})) {
629 if (ref($handler) eq 'CODE') {
630 my $params = decode_urlencoded($r->url->query());
631 my ($resp, $userid) = &$handler($self, $reqstate->{request}, $params);
632 $self->response($reqstate, $resp);
633 } elsif (ref($handler) eq 'HASH') {
634 if (my $filename = $handler->{file}) {
635 my $fh = IO::File->new($filename) ||
636 die "unable to open file '$filename' - $!\n";
637 send_file_start($self, $reqstate, $filename);
638 } else {
639 die "internal error - no handler";
640 }
641 } else {
642 die "internal error - no handler";
643 }
644 return;
645 }
646
647 if ($self->{dirs} && ($method eq 'GET')) {
648 # we only allow simple names
649 if ($path =~ m!^(/\S+/)([a-zA-Z0-9\-\_\.]+)$!) {
650 my ($subdir, $file) = ($1, $2);
651 if (my $dir = $self->{dirs}->{$subdir}) {
652 my $filename = "$dir$file";
653 my $fh = IO::File->new($filename) ||
654 die "unable to open file '$filename' - $!\n";
655 send_file_start($self, $reqstate, $filename);
656 return;
657 }
658 }
659 }
660
661 die "no such file '$path'";
662 };
663 if (my $err = $@) {
664 $self->error($reqstate, 501, $err);
665 }
666 }
667
668 sub file_upload_multipart {
669 my ($self, $reqstate, $auth, $rstate) = @_;
670
671 eval {
672 my $boundary = $rstate->{boundary};
673 my $hdl = $reqstate->{hdl};
674
675 my $startlen = length($hdl->{rbuf});
676
677 if ($rstate->{phase} == 0) { # skip everything until start
678 if ($hdl->{rbuf} =~ s/^.*?--\Q$boundary\E \015?\012
679 ((?:[^\015]+\015\012)* ) \015?\012//xs) {
680 my $header = $1;
681 my ($ct, $disp, $name, $filename);
682 foreach my $line (split(/\015?\012/, $header)) {
683 # assume we have single line headers
684 if ($line =~ m/^Content-Type\s*:\s*(.*)/i) {
685 $ct = parse_content_type($1);
686 } elsif ($line =~ m/^Content-Disposition\s*:\s*(.*)/i) {
687 ($disp, $name, $filename) = parse_content_disposition($1);
688 }
689 }
690
691 if (!($disp && $disp eq 'form-data' && $name)) {
692 syslog('err', "wrong content disposition in multipart - abort upload");
693 $rstate->{phase} = -1;
694 } else {
695
696 $rstate->{fieldname} = $name;
697
698 if ($filename) {
699 if ($name eq 'filename') {
700 # found file upload data
701 $rstate->{phase} = 1;
702 $rstate->{filename} = $filename;
703 } else {
704 syslog('err', "wrong field name for file upload - abort upload");
705 $rstate->{phase} = -1;
706 }
707 } else {
708 # found form data for field $name
709 $rstate->{phase} = 2;
710 }
711 }
712 } else {
713 my $len = length($hdl->{rbuf});
714 substr($hdl->{rbuf}, 0, $len - $rstate->{maxheader}, '')
715 if $len > $rstate->{maxheader}; # skip garbage
716 }
717 } elsif ($rstate->{phase} == 1) { # inside file - dump until end marker
718 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
719 my ($rest, $eof) = ($1, $3);
720 my $len = length($rest);
721 die "write to temporary file failed - $!"
722 if syswrite($rstate->{outfh}, $rest) != $len;
723 $rstate->{ctx}->add($rest);
724 $rstate->{params}->{filename} = $rstate->{filename};
725 $rstate->{md5sum} = $rstate->{ctx}->hexdigest;
726 $rstate->{bytes} += $len;
727 $rstate->{phase} = $eof ? 100 : 0;
728 } else {
729 my $len = length($hdl->{rbuf});
730 my $wlen = $len - $rstate->{boundlen};
731 if ($wlen > 0) {
732 my $data = substr($hdl->{rbuf}, 0, $wlen, '');
733 die "write to temporary file failed - $!"
734 if syswrite($rstate->{outfh}, $data) != $wlen;
735 $rstate->{bytes} += $wlen;
736 $rstate->{ctx}->add($data);
737 }
738 }
739 } elsif ($rstate->{phase} == 2) { # inside normal field
740
741 if ($hdl->{rbuf} =~ s/^(.*?)\015?\012(--\Q$boundary\E(--)? \015?\012(.*))$/$2/xs) {
742 my ($rest, $eof) = ($1, $3);
743 my $len = length($rest);
744 $rstate->{post_size} += $len;
745 if ($rstate->{post_size} < $limit_max_post) {
746 $rstate->{params}->{$rstate->{fieldname}} = $rest;
747 $rstate->{phase} = $eof ? 100 : 0;
748 } else {
749 syslog('err', "form data to large - abort upload");
750 $rstate->{phase} = -1; # skip
751 }
752 }
753 } else { # skip
754 my $len = length($hdl->{rbuf});
755 substr($hdl->{rbuf}, 0, $len, ''); # empty rbuf
756 }
757
758 $rstate->{read} += ($startlen - length($hdl->{rbuf}));
759
760 if (!$rstate->{done} && ($rstate->{read} + length($hdl->{rbuf})) >= $rstate->{size}) {
761 $rstate->{done} = 1; # make sure we dont get called twice
762 if ($rstate->{phase} < 0 || !$rstate->{md5sum}) {
763 die "upload failed\n";
764 } else {
765 my $elapsed = tv_interval($rstate->{starttime});
766
767 my $rate = int($rstate->{bytes}/($elapsed*1024*1024));
768 syslog('info', "multipart upload complete " .
769 "(size: %d time: %ds rate: %.2fMiB/s md5sum: $rstate->{md5sum})",
770 $rstate->{bytes}, $elapsed, $rate);
771 $self->handle_api2_request($reqstate, $auth, $rstate);
772 }
773 }
774 };
775 if (my $err = $@) {
776 syslog('err', $err);
777 $self->error($reqstate, 501, $err);
778 }
779 }
780
781 sub parse_content_type {
782 my ($ctype) = @_;
783
784 my ($ct, @params) = split(/\s*[;,]\s*/o, $ctype);
785
786 foreach my $v (@params) {
787 if ($v =~ m/^\s*boundary\s*=\s*(\S+?)\s*$/o) {
788 return wantarray ? ($ct, $1) : $ct;
789 }
790 }
791
792 return wantarray ? ($ct) : $ct;
793 }
794
795 sub parse_content_disposition {
796 my ($line) = @_;
797
798 my ($disp, @params) = split(/\s*[;,]\s*/o, $line);
799 my $name;
800 my $filename;
801
802 foreach my $v (@params) {
803 if ($v =~ m/^\s*name\s*=\s*(\S+?)\s*$/o) {
804 $name = $1;
805 $name =~ s/^"(.*)"$/$1/;
806 } elsif ($v =~ m/^\s*filename\s*=\s*(.+?)\s*$/o) {
807 $filename = $1;
808 $filename =~ s/^"(.*)"$/$1/;
809 }
810 }
811
812 return wantarray ? ($disp, $name, $filename) : $disp;
813 }
814
815 my $tmpfile_seq_no = 0;
816
817 sub get_upload_filename {
818 # choose unpredictable tmpfile name
819
820 $tmpfile_seq_no++;
821 return "/var/tmp/pveupload-" . Digest::MD5::md5_hex($tmpfile_seq_no . time() . $$);
822 }
823
824 sub unshift_read_header {
825 my ($self, $reqstate, $state) = @_;
826
827 $state = { size => 0, count => 0 } if !$state;
828
829 $reqstate->{hdl}->unshift_read(line => sub {
830 my ($hdl, $line) = @_;
831
832 eval {
833 # print "$$: got header: $line\n" if $self->{debug};
834
835 die "to many http header lines\n" if ++$state->{count} >= $limit_max_headers;
836 die "http header too large\n" if ($state->{size} += length($line)) >= $limit_max_header_size;
837
838 my $r = $reqstate->{request};
839 if ($line eq '') {
840
841 my $path = $r->uri->path();
842 my $method = $r->method();
843
844 $r->push_header($state->{key}, $state->{val})
845 if $state->{key};
846
847 if (!$known_methods->{$method}) {
848 my $resp = HTTP::Response->new(HTTP_NOT_IMPLEMENTED, "method '$method' not available");
849 $self->response($reqstate, $resp);
850 return;
851 }
852
853 my $conn = $r->header('Connection');
854 my $accept_enc = $r->header('Accept-Encoding');
855 $reqstate->{accept_gzip} = ($accept_enc && $accept_enc =~ m/gzip/) ? 1 : 0;
856
857 if ($conn) {
858 $reqstate->{keep_alive} = 0 if $conn =~ m/close/oi;
859 } else {
860 if ($reqstate->{proto}->{ver} < 1001) {
861 $reqstate->{keep_alive} = 0;
862 }
863 }
864
865 my $te = $r->header('Transfer-Encoding');
866 if ($te && lc($te) eq 'chunked') {
867 # Handle chunked transfer encoding
868 $self->error($reqstate, 501, "chunked transfer encoding not supported");
869 return;
870 } elsif ($te) {
871 $self->error($reqstate, 501, "Unknown transfer encoding '$te'");
872 return;
873 }
874
875 my $pveclientip = $r->header('PVEClientIP');
876
877 # fixme: how can we make PVEClientIP header trusted?
878 if ($self->{trusted_env} && $pveclientip) {
879 $reqstate->{peer_host} = $pveclientip;
880 } else {
881 $r->header('PVEClientIP', $reqstate->{peer_host});
882 }
883
884 my $len = $r->header('Content-Length');
885
886 # header processing complete - authenticate now
887
888 my $auth = {};
889 if ($self->{spiceproxy}) {
890 my $connect_str = $r->header('Host');
891 my ($vmid, $node, $port) = PVE::AccessControl::verify_spice_connect_url($connect_str);
892 if (!($vmid && $node && $port)) {
893 $self->error($reqstate, HTTP_UNAUTHORIZED, "invalid ticket");
894 return;
895 }
896 $self->handle_spice_proxy_request($reqstate, $connect_str, $vmid, $node, $port);
897 return;
898 } elsif ($path =~ m!$baseuri!) {
899 my $token = $r->header('CSRFPreventionToken');
900 my $cookie = $r->header('Cookie');
901 my $ticket = PVE::REST::extract_auth_cookie($cookie);
902
903 my ($rel_uri, $format) = split_abs_uri($path);
904 if (!$format) {
905 $self->error($reqstate, HTTP_NOT_IMPLEMENTED, "no such uri");
906 return;
907 }
908
909 eval {
910 $auth = PVE::REST::auth_handler($self->{rpcenv}, $reqstate->{peer_host}, $method,
911 $rel_uri, $ticket, $token);
912 };
913 if (my $err = $@) {
914 $self->error($reqstate, HTTP_UNAUTHORIZED, $err);
915 return;
916 }
917 }
918
919 $reqstate->{log}->{userid} = $auth->{userid};
920
921 if ($len) {
922
923 if (!($method eq 'PUT' || $method eq 'POST')) {
924 $self->error($reqstate, 501, "Unexpected content for method '$method'");
925 return;
926 }
927
928 my $ctype = $r->header('Content-Type');
929 my ($ct, $boundary) = parse_content_type($ctype) if $ctype;
930
931 if ($auth->{isUpload} && !$self->{trusted_env}) {
932 die "upload 'Content-Type '$ctype' not implemented\n"
933 if !($boundary && $ct && ($ct eq 'multipart/form-data'));
934
935 die "upload without content length header not supported" if !$len;
936
937 die "upload without content length header not supported" if !$len;
938
939 print "start upload $path $ct $boundary\n" if $self->{debug};
940
941 my $tmpfilename = get_upload_filename();
942 my $outfh = IO::File->new($tmpfilename, O_RDWR|O_CREAT|O_EXCL, 0600) ||
943 die "unable to create temporary upload file '$tmpfilename'";
944
945 $reqstate->{keep_alive} = 0;
946
947 my $boundlen = length($boundary) + 8; # \015?\012--$boundary--\015?\012
948
949 my $state = {
950 size => $len,
951 boundary => $boundary,
952 ctx => Digest::MD5->new,
953 boundlen => $boundlen,
954 maxheader => 2048 + $boundlen, # should be large enough
955 params => decode_urlencoded($r->url->query()),
956 phase => 0,
957 read => 0,
958 post_size => 0,
959 starttime => [gettimeofday],
960 outfh => $outfh,
961 };
962 $reqstate->{tmpfilename} = $tmpfilename;
963 $reqstate->{hdl}->on_read(sub { $self->file_upload_multipart($reqstate, $auth, $state); });
964 return;
965 }
966
967 if ($len > $limit_max_post) {
968 $self->error($reqstate, 501, "for data too large");
969 return;
970 }
971
972 if (!$ct || $ct eq 'application/x-www-form-urlencoded') {
973 $reqstate->{hdl}->unshift_read(chunk => $len, sub {
974 my ($hdl, $data) = @_;
975 $r->content($data);
976 $self->handle_request($reqstate, $auth);
977 });
978 } else {
979 $self->error($reqstate, 506, "upload 'Content-Type '$ctype' not implemented");
980 }
981 } else {
982 $self->handle_request($reqstate, $auth);
983 }
984 } elsif ($line =~ /^([^:\s]+)\s*:\s*(.*)/) {
985 $r->push_header($state->{key}, $state->{val}) if $state->{key};
986 ($state->{key}, $state->{val}) = ($1, $2);
987 $self->unshift_read_header($reqstate, $state);
988 } elsif ($line =~ /^\s+(.*)/) {
989 $state->{val} .= " $1";
990 $self->unshift_read_header($reqstate, $state);
991 } else {
992 $self->error($reqstate, 506, "unable to parse request header");
993 }
994 };
995 warn $@ if $@;
996 });
997 };
998
999 sub push_request_header {
1000 my ($self, $reqstate) = @_;
1001
1002 eval {
1003 $reqstate->{hdl}->push_read(line => sub {
1004 my ($hdl, $line) = @_;
1005
1006 eval {
1007 # print "got request header: $line\n" if $self->{debug};
1008
1009 $reqstate->{keep_alive}--;
1010
1011 if ($line =~ /(\S+)\040(\S+)\040HTTP\/(\d+)\.(\d+)/o) {
1012 my ($method, $uri, $maj, $min) = ($1, $2, $3, $4);
1013
1014 if ($maj != 1) {
1015 $self->error($reqstate, 506, "http protocol version $maj.$min not supported");
1016 return;
1017 }
1018
1019 $self->{request_count}++; # only count valid request headers
1020 if ($self->{request_count} >= $self->{max_requests}) {
1021 $self->{end_loop} = 1;
1022 }
1023 $reqstate->{log} = { requestline => $line };
1024 $reqstate->{proto}->{str} = "HTTP/$maj.$min";
1025 $reqstate->{proto}->{maj} = $maj;
1026 $reqstate->{proto}->{min} = $min;
1027 $reqstate->{proto}->{ver} = $maj*1000+$min;
1028 $reqstate->{request} = HTTP::Request->new($method, $uri);
1029
1030 $self->unshift_read_header($reqstate);
1031 } elsif ($line eq '') {
1032 # ignore empty lines before requests (browser bugs?)
1033 $self->push_request_header($reqstate);
1034 } else {
1035 $self->error($reqstate, 400, 'bad request');
1036 }
1037 };
1038 warn $@ if $@;
1039 });
1040 };
1041 warn $@ if $@;
1042 }
1043
1044 sub accept {
1045 my ($self) = @_;
1046
1047 my $clientfh;
1048
1049 return if $self->{end_loop};
1050
1051 # we need to m make sure that only one process calls accept
1052 while (!flock($self->{lockfh}, Fcntl::LOCK_EX())) {
1053 next if $! == EINTR;
1054 die "could not get lock on file '$self->{lockfile}' - $!\n";
1055 }
1056
1057 my $again = 0;
1058 my $errmsg;
1059 eval {
1060 while (!$self->{end_loop} &&
1061 !defined($clientfh = $self->{socket}->accept()) &&
1062 ($! == EINTR)) {};
1063
1064 if ($self->{end_loop}) {
1065 $again = 0;
1066 } else {
1067 $again = ($! == EAGAIN || $! == WSAEWOULDBLOCK);
1068 if (!defined($clientfh)) {
1069 $errmsg = "failed to accept connection: $!\n";
1070 }
1071 }
1072 };
1073 warn $@ if $@;
1074
1075 flock($self->{lockfh}, Fcntl::LOCK_UN());
1076
1077 if (!defined($clientfh)) {
1078 return if $again;
1079 die $errmsg if $errmsg;
1080 }
1081
1082 fh_nonblocking $clientfh, 1;
1083
1084 $self->{conn_count}++;
1085
1086 return $clientfh;
1087 }
1088
1089 sub wait_end_loop {
1090 my ($self) = @_;
1091
1092 $self->{end_loop} = 1;
1093
1094 undef $self->{socket_watch};
1095
1096 if ($self->{conn_count} <= 0) {
1097 $self->{end_cond}->send(1);
1098 return;
1099 }
1100
1101 # else we need to wait until all open connections gets closed
1102 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1103 eval {
1104 # todo: test for active connections instead (we can abort idle connections)
1105 if ($self->{conn_count} <= 0) {
1106 undef $w;
1107 $self->{end_cond}->send(1);
1108 }
1109 };
1110 warn $@ if $@;
1111 });
1112 }
1113
1114
1115 sub check_host_access {
1116 my ($self, $clientip) = @_;
1117
1118 my $cip = Net::IP->new($clientip);
1119
1120 my $match_allow = 0;
1121 my $match_deny = 0;
1122
1123 if ($self->{allow_from}) {
1124 foreach my $t (@{$self->{allow_from}}) {
1125 if ($t->overlaps($cip)) {
1126 $match_allow = 1;
1127 last;
1128 }
1129 }
1130 }
1131
1132 if ($self->{deny_from}) {
1133 foreach my $t (@{$self->{deny_from}}) {
1134 if ($t->overlaps($cip)) {
1135 $match_deny = 1;
1136 last;
1137 }
1138 }
1139 }
1140
1141 if ($match_allow == $match_deny) {
1142 # match both allow and deny, or no match
1143 return $self->{policy} && $self->{policy} eq 'allow' ? 1 : 0;
1144 }
1145
1146 return $match_allow;
1147 }
1148
1149 sub accept_connections {
1150 my ($self) = @_;
1151
1152 eval {
1153
1154 while (my $clientfh = $self->accept()) {
1155
1156 my $reqstate = { keep_alive => $self->{keep_alive} };
1157
1158 # stop keep-alive when there are many open connections
1159 if ($self->{conn_count} >= $self->{max_conn_soft_limit}) {
1160 $reqstate->{keep_alive} = 0;
1161 }
1162
1163 if (my $sin = getpeername($clientfh)) {
1164 my ($pport, $phost) = Socket::unpack_sockaddr_in($sin);
1165 ($reqstate->{peer_port}, $reqstate->{peer_host}) = ($pport, Socket::inet_ntoa($phost));
1166 }
1167
1168 if (!$self->{trusted_env} && !$self->check_host_access($reqstate->{peer_host})) {
1169 print "$$: ABORT request from $reqstate->{peer_host} - access denied\n" if $self->{debug};
1170 $reqstate->{log}->{code} = 403;
1171 $self->log_request($reqstate);
1172 next;
1173 }
1174
1175 $reqstate->{hdl} = AnyEvent::Handle->new(
1176 fh => $clientfh,
1177 rbuf_max => 64*1024,
1178 timeout => $self->{timeout},
1179 linger => 0, # avoid problems with ssh - really needed ?
1180 on_eof => sub {
1181 my ($hdl) = @_;
1182 eval {
1183 $self->log_aborted_request($reqstate);
1184 $self->client_do_disconnect($reqstate);
1185 };
1186 if (my $err = $@) { syslog('err', $err); }
1187 },
1188 on_error => sub {
1189 my ($hdl, $fatal, $message) = @_;
1190 eval {
1191 $self->log_aborted_request($reqstate, $message);
1192 $self->client_do_disconnect($reqstate);
1193 };
1194 if (my $err = $@) { syslog('err', "$err"); }
1195 },
1196 ($self->{tls_ctx} ? (tls => "accept", tls_ctx => $self->{tls_ctx}) : ()));
1197
1198 print "$$: ACCEPT FH" . $clientfh->fileno() . " CONN$self->{conn_count}\n" if $self->{debug};
1199
1200 $self->push_request_header($reqstate);
1201 }
1202 };
1203
1204 if (my $err = $@) {
1205 syslog('err', $err);
1206 $self->{end_loop} = 1;
1207 }
1208
1209 $self->wait_end_loop() if $self->{end_loop};
1210 }
1211
1212 # Note: We can't open log file in non-blocking mode and use AnyEvent::Handle,
1213 # because we write from multiple processes, and that would arbitrarily mix output
1214 # of all processes.
1215 sub open_access_log {
1216 my ($self, $filename) = @_;
1217
1218 my $old_mask = umask(0137);;
1219 my $logfh = IO::File->new($filename, ">>") ||
1220 die "unable to open log file '$filename' - $!\n";
1221 umask($old_mask);
1222
1223 $logfh->autoflush(1);
1224
1225 $self->{logfh} = $logfh;
1226 }
1227
1228 sub write_log {
1229 my ($self, $data) = @_;
1230
1231 return if !defined($self->{logfh}) || !$data;
1232
1233 my $res = $self->{logfh}->print($data);
1234
1235 if (!$res) {
1236 delete $self->{logfh};
1237 syslog('err', "error writing access log");
1238 $self->{end_loop} = 1; # terminate asap
1239 }
1240 }
1241
1242 sub atfork_handler {
1243 my ($self) = @_;
1244
1245 eval {
1246 # something else do to ?
1247 close($self->{socket});
1248 };
1249 warn $@ if $@;
1250 }
1251
1252 sub new {
1253 my ($this, %args) = @_;
1254
1255 my $class = ref($this) || $this;
1256
1257 foreach my $req (qw(socket lockfh lockfile)) {
1258 die "misssing required argument '$req'" if !defined($args{$req});
1259 }
1260
1261 my $self = bless { %args }, $class;
1262
1263 # init inotify
1264 PVE::INotify::inotify_init();
1265
1266 $self->{rpcenv} = PVE::RPCEnvironment->init(
1267 $self->{trusted_env} ? 'priv' : 'pub', atfork => sub { $self-> atfork_handler() });
1268
1269 fh_nonblocking($self->{socket}, 1);
1270
1271 $self->{end_loop} = 0;
1272 $self->{conn_count} = 0;
1273 $self->{request_count} = 0;
1274 $self->{timeout} = 5 if !$self->{timeout};
1275 $self->{keep_alive} = 0 if !defined($self->{keep_alive});
1276 $self->{max_conn} = 800 if !$self->{max_conn};
1277 $self->{max_requests} = 8000 if !$self->{max_requests};
1278
1279 $self->{policy} = 'allow' if !$self->{policy};
1280
1281 $self->{end_cond} = AnyEvent->condvar;
1282
1283 if ($self->{ssl}) {
1284 $self->{tls_ctx} = AnyEvent::TLS->new(%{$self->{ssl}});
1285 }
1286
1287 if ($self->{spiceproxy}) {
1288 $known_methods = { CONNECT => 1 };
1289 }
1290
1291 $self->open_access_log($self->{logfile}) if $self->{logfile};
1292
1293 $self->{max_conn_soft_limit} = $self->{max_conn} > 100 ? $self->{max_conn} - 20 : $self->{max_conn};
1294
1295 $self->{socket_watch} = AnyEvent->io(fh => $self->{socket}, poll => 'r', cb => sub {
1296 eval {
1297 if ($self->{conn_count} >= $self->{max_conn}) {
1298 my $w; $w = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1299 if ($self->{conn_count} < $self->{max_conn}) {
1300 undef $w;
1301 $self->accept_connections();
1302 }
1303 });
1304 } else {
1305 $self->accept_connections();
1306 }
1307 };
1308 warn $@ if $@;
1309 });
1310
1311 $self->{term_watch} = AnyEvent->signal(signal => "TERM", cb => sub {
1312 undef $self->{term_watch};
1313 $self->wait_end_loop();
1314 });
1315
1316 $self->{quit_watch} = AnyEvent->signal(signal => "QUIT", cb => sub {
1317 undef $self->{quit_watch};
1318 $self->wait_end_loop();
1319 });
1320
1321 $self->{inotify_poll} = AnyEvent->timer(after => 5, interval => 5, cb => sub {
1322 PVE::INotify::poll(); # read inotify events
1323 });
1324
1325 return $self;
1326 }
1327
1328 sub run {
1329 my ($self) = @_;
1330
1331 $self->{end_cond}->recv;
1332 }
1333
1334 1;