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