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