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