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