all the python scripts are for python2, and fedora31 requires to be specific
[vsys-scripts.git] / root-context / exec / raw_tcp_port
1 #!/usr/bin/perl
2
3 use strict;
4
5 $|=1;
6
7 my $slicename;
8 my $portnumber;
9 my $ipaddress;
10
11 $slicename = $ARGV[0];
12 $portnumber = <STDIN>;
13 $ipaddress = <STDIN>;
14
15 chop($portnumber);
16 chop($ipaddress);
17
18 if (-f "/dev/shm/rawtcp-$slicename") {
19         print "Sorry, only 1 port reservation is allowed per slice. You reserved ".`cat /dev/shm/rawtcp-$slicename`;
20 }
21
22 if ($ipaddress!~/^\d+\.\d+\.\d+\.\d+/) {
23         die("$ipaddress is not an ip address");
24 }
25
26 if ($portnumber!~/^\d+$/) {
27         die("$portnumber is not a port number");
28 }
29
30 $portnumber=int($portnumber);
31 open CMD1,"vcontext --ctx 1 --migrate -- ncontext --nid 1 --migrate fuser -n tcp $portnumber 2>/dev/null |";
32 my @f = <CMD1>;
33 my $fuser = join '',@f;
34 $fuser=~s/\s//g;
35 close CMD1;
36
37 if ($fuser) {
38         open CMD2,"chcontext --ctx 1 -- cat /proc/$fuser/vinfo|";
39
40         my $vinfo = <CMD2>;
41         my @userinfo;
42         @userinfo = split /\s/,$vinfo;
43         my $uid = $userinfo[1];
44         my $slice_id = `id -u $slicename`;
45         chop($slice_id);
46
47         if ($slice_id eq $uid) {
48                 my $default_route = `ip route get $ipaddress`;
49                 my $dev;
50                 $default_route =~ /dev ([^\s]+)/;
51                 $dev = $1;
52                 if ($dev !~ /$uid/) {
53                         print $ipaddress;
54                         print $default_route;
55                         die("Sorry, you don't own the next hop for that route, which is $dev");
56                 }
57                 
58                 #### If we made it here, it means:
59                 #### 1. The user is bound to the desired port, which is in the 61000+ range.
60                 #### 2. There is a local device for the supplied IP address.
61                 #### 3. The calling user owns that device.
62                 ####
63                 #### Next: Bridge the port with the device
64
65                 my $iptables_cmd = "iptables -t nat -A PREROUTING -m tcp -p tcp --dport $portnumber -j DNAT --to $ipaddress:$portnumber";
66                 system($iptables_cmd);
67                 system("echo $portnumber > /dev/shm/rawtcp-$slicename");
68                 print "Port reservation commands executed";
69         }
70         else {
71                 print "$portnumber is taken by somebody else, sorry";
72         }
73         close CMD2;
74 } else {
75         print "Please bind to $portnumber first."
76 }