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