AtlatestRepositorysigil-nat

sigil-nat / tree / tools / nat / reflectorsnat-probe.pl

1#!/usr/bin/perl
2# Base-Perl two-port reflector. Private fixed-size protocol; not a STUN server.
3use strict;
4use warnings;
5use IO::Socket::INET;
6use IO::Select;
7use Socket qw(sockaddr_in inet_aton inet_ntoa);
8use Time::HiRes qw(time);
9use Fcntl qw(O_WRONLY O_CREAT O_EXCL);
11my $config_path = shift @ARGV or die "Private config path required\n";
12my @info = stat($config_path);
13die "Config must be private and owned\n" unless @info && $info[4] == $< && ($info[2] & 077) == 0 && $info[7] <= 8192;
14open(my $config, '<', $config_path) or die "Cannot read private config\n";
15my @lines = <$config>;
16close($config);
17chomp(@lines);
18my ($bind, $token_hex, $lifetime_ms, $state_path, @requested_ports) = @lines;
19die "Invalid bounded reflector config\n" unless (@lines == 4 || @lines == 6) &&
20 defined($bind) && $bind =~ /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/ &&
21 defined($token_hex) && $token_hex =~ /^[0-9a-f]{64}$/ &&
22 defined($lifetime_ms) && $lifetime_ms =~ /^[0-9]+$/ && $lifetime_ms >= 1 && $lifetime_ms <= 900000 &&
23 defined($state_path) && $state_path =~ m{^/} && $state_path !~ /[\x00-\x1f]/;
24my @octets = split(/\./, $bind);
25die "Bind must name an exact unicast IPv4 interface\n" if grep { $_ > 255 } @octets;
26die "Bind must name an exact unicast IPv4 interface\n" if $octets[0] == 0 || $octets[0] >= 224;
27die "Explicit ports must be distinct high UDP ports\n" if @requested_ports &&
28 (grep { !/^[0-9]+$/ || $_ < 1024 || $_ > 65535 } @requested_ports);
29die "Explicit ports must be distinct high UDP ports\n" if @requested_ports && $requested_ports[0] == $requested_ports[1];
30@requested_ports = (0, 0) unless @requested_ports;
31my $token = pack('H*', $token_hex);
32my @sockets;
33for my $port (@requested_ports) {
34 my $socket = IO::Socket::INET->new(LocalAddr => $bind, LocalPort => $port, Proto => 'udp')
35 or die "Cannot bind owned UDP socket\n";
36 die "Kernel selected a low UDP port\n" if $socket->sockport < 1024;
37 push @sockets, $socket;
39my @ports = map { $_->sockport } @sockets;
40my $selector = IO::Select->new(@sockets);
41my $running = 1;
42$SIG{TERM} = sub { $running = 0; };
43$SIG{INT} = sub { $running = 0; };
44$SIG{ALRM} = sub { $running = 0; };
45alarm(int(($lifetime_ms + 999) / 1000));
46my $end = time() + $lifetime_ms / 1000;
47my ($received, $accepted, $sent, $errors) = (0, 0, 0, 0);
48my %entries;
49my $client_address;
50sub record_file {
51 my ($path, $json) = @_;
52 sysopen(my $file, $path, O_WRONLY | O_CREAT | O_EXCL, 0600) or die "Cannot create private reflector receipt\n";
53 print {$file} $json, "\n";
54 close($file) or die "Cannot finish private reflector receipt\n";
56sub send_packet {
57 my ($socket, $target, $transaction, $operation, $address, $port) = @_;
58 return 0 unless $running && $sent < 256;
59 my $bytes = pack('a4a32a12Ca4na9', 'SNP1', $token, $transaction, $operation,
60 defined($address) ? $address : "\0" x 4, defined($port) ? $port : 0, "\0" x 9);
61 my $written = $socket->send($bytes, 0, $target);
62 if (!defined($written) || $written != 64) { $errors++; return 0; }
63 $sent++;
64 return 1;
66record_file($state_path, '{"pid":' . $$ . ',"address":"' . $bind . '","ports":[' . join(',', @ports) . '],"ready":true}');
67$| = 1;
68print "RESULT reflector-ready sockets=2 lifetimeMs=$lifetime_ms\n";
69while ($running && time() < $end && $received < 512 && $sent < 256) {
70 for my $socket ($selector->can_read(0.1)) {
71 my $bytes = '';
72 my $source = $socket->recv($bytes, 65);
73 $received++;
74 next unless defined($source) && length($bytes) == 64;
75 my ($magic, $supplied_token, $transaction, $operation, $target_address, $target_port, $reserved) =
76 unpack('a4a32a12Ca4na9', $bytes);
77 next unless $magic eq 'SNP1' && $supplied_token eq $token && $reserved eq "\0" x 9 &&
78 $target_address eq "\0" x 4 && $target_port == 0;
79 my ($source_port, $source_address) = sockaddr_in($source);
80 next if $source_port < 1024;
81 # Only the first valid run-token holder's observed IP is admitted. Tokens
82 # stay in private config/receipts and are never returned to another IP.
83 $client_address = $source_address unless defined($client_address);
84 next unless $client_address eq $source_address;
85 $accepted++;
86 my $id = unpack('H*', $transaction);
87 if ($operation == 1) {
88 next if exists($entries{$id}) && $entries{$id}->{source} ne $source;
89 next if !exists($entries{$id}) && scalar(keys(%entries)) >= 64;
90 $entries{$id} //= { source => $source, delivered => 0 };
91 send_packet($socket, $source, $transaction, 2, $source_address, $source_port);
92 } elsif ($socket == $sockets[0] && $operation == 3) {
93 if (send_packet($sockets[1], $source, $transaction, 6, undef, undef)) {
94 send_packet($sockets[0], $source, $transaction, 7, undef, undef);
95 }
96 } elsif ($socket == $sockets[0] && $operation == 8) {
97 my $entry = $entries{$id};
98 next unless $entry && !$entry->{delivered};
99 $entry->{delivered} = 1;
100 if (send_packet($sockets[0], $entry->{source}, $transaction, 6, undef, undef)) {
101 send_packet($sockets[0], $source, $transaction, 7, undef, undef);
102 }
103 }
104 }
106alarm(0);
107for my $socket (@sockets) { close($socket); }
108record_file($state_path . '.done', '{"stopped":true,"received":' . $received . ',"accepted":' . $accepted . ',"sent":' . $sent . ',"errors":' . $errors . '}');
109print "RESULT reflector-stopped sockets=2 received=$received sent=$sent errors=$errors\n";
110exit($errors ? 1 : 0);