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