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