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