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