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