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