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