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