source: fedkit/fed-tun.pl @ f64fa81

axis_examplecompt_changesinfo-opsversion-1.30version-2.00version-3.01version-3.02
Last change on this file since f64fa81 was f64fa81, checked in by Ted Faber <faber@…>, 16 years ago

event stuff

  • Property mode set to 100755
File size: 9.5 KB
Line 
1#!/usr/bin/perl -w
2
3# Kevin Lahey, lahey@isi.edu
4# July 11, 2007
5
6# Set up ssh tunnel infrastructure for federation:
7#
8# * Parse the configuration file provided.
9#
10# * Figure out whether we're the initiator or the reciever;  if we're
11#   the receiver, we just need to set up ssh keys and exit.
12#
13# * Pick out the experimental interface, remove the IP address
14#
15# * Create a layer 2 ssh tunnel, set up bridging, and hang loose.
16#
17
18use strict;
19use Getopt::Std;
20use POSIX qw(strftime);
21use Sys::Hostname;
22use IO::File;
23
24my $IFCONFIG = "/sbin/ifconfig";
25my $TMCC = "/usr/local/etc/emulab/tmcc";
26my $SSH = "/usr/local/bin/ssh";
27my $NC = "/usr/bin/nc";
28my $SSH_PORT = 22;
29my $ROUTE_GET = "/sbin/route get";  # XXX:  works on FreeBSD, but should
30                                    #       should be 'ip route get' for Linux
31
32# Ports that are forwarded between testbeds
33my $TMCD_PORT = 7777;
34my $SMBFS_PORT = 139;
35my $PUBSUB_PORT = 16505;
36
37sub setup_bridging;
38sub setup_tunnel_cfg;
39sub parse_config;
40
41# Option use is as follows:
42#    -f         filename containing config file
43#    -d         turn on debugging output
44#    -r         remotely invoked
45#               (if remotely invoked the last two args are the tun interface
46#               number and the remote address of the tunnel)
47
48my $usage = "Usage: fed-tun.pl [-r] [-d] [-f config-filename] [count addr]\n";
49
50my %opts;       # Note that this is used for both getops and the options file
51my @expected_opts = qw(active tunnelcfg bossname fsname type
52                       peer pubkeys privkeys);
53my $filename;
54my $remote;
55my $debug = 1;
56my $count;
57my $addr;
58my $active;
59my $type;
60my $tunnelcfg;
61my $ssh_port_fwds = "";
62my $remote_script_dir;          # location of the other sides fed-tun.pl
63
64if ($#ARGV != 0 && !getopts('df:r', \%opts)) {
65    die "$usage";
66}
67
68if (defined($opts{'d'})) {
69    $debug = 1;
70}
71
72if (defined($opts{'f'})) {
73    $filename = $opts{'f'};
74}
75
76if (defined($opts{'r'})) {
77    $remote = 1;
78    die "$usage" if ($#ARGV != 1);
79   
80    $count = pop @ARGV;
81    $addr = pop @ARGV;
82}
83
84die "$usage" if (!defined($remote) && !defined($filename));
85
86if (defined($filename)) {
87    &parse_config("$filename", \%opts) || 
88        die "Cannot read config file $filename: $!\n";
89
90    foreach my $opt (@expected_opts) {
91        warn "Missing $opt option\n" if (!defined($opts{$opt}));
92    }
93
94    $active = 1 if ($opts{'active'} =~ /true/i);
95    $tunnelcfg = 1 if ($opts{'tunnelcfg'} =~ /true/i);
96    $type = $opts{'type'};
97    $type =~ tr/A-Z/a-z/;
98    $remote_script_dir = $opts{'remotescriptdir'} || ".";
99
100    if (defined($opts{'fsname'})) {
101        $ssh_port_fwds = "-R :$SMBFS_PORT:$opts{'fsname'}:$SMBFS_PORT ";
102    }
103
104    if (defined($opts{'bossname'})) {
105        my $remote_pubsub_port = $PUBSUB_PORT - 1;  # There will be a local
106                                                    # pubsubd running, so we
107                                                    # dodge the port on the
108                                                    # remote tunnel node.
109        $ssh_port_fwds .= "-R :$TMCD_PORT:$opts{'bossname'}:$TMCD_PORT ";
110        $ssh_port_fwds .= "-R :$remote_pubsub_port:$opts{'eventservername'}:" . 
111            "$PUBSUB_PORT ";
112    }
113
114    $ssh_port_fwds = "" if ($opts{'type'} eq 'experiment');
115
116    print "ssh_port_fwds = $ssh_port_fwds\n" if ($debug);
117}
118
119# Need these to make the Ethernet tap and bridge to work...
120
121system("kldload /boot/kernel/if_bridge.ko");
122system("kldload /boot/kernel/if_tap.ko");
123
124if ($tunnelcfg && !$remote) {
125    # Most Emulab-like testbeds use globally-routable addresses on the
126    # control net;  at DETER, we isolate the control net from the Internet.
127    # On DETER-like testbeds, we need to create special tunneling nodes
128    # with external access.  Set up the external addresses as necessary.
129    &setup_tunnel_cfg(%opts);
130}
131
132if (!$remote) {
133    system("umask 077 && cp $opts{'privkeys'} /root/.ssh/id_rsa");
134    system("umask 077 && cp $opts{'pubkeys'} /root/.ssh/id_rsa.pub");
135    system("umask 077 && cat $opts{'pubkeys'} >> /root/.ssh/authorized_keys");
136}
137
138if ($active) {
139    # If we're the initiator, open up a separate tunnel to the remote
140    # host for each of the different experiment net interfaces on this
141    # machine.  Execute this startup script on the far end, but with
142    # the -r option to indicate that it's getting invoked remotely and
143    # we should just handle the remote-end tasks.
144
145    # Set up synchronization, so that the various user machines won't try to
146    # contact boss before the tunnels are set up.  (Thanks jjh!)
147
148    do {
149        system("$NC -z $opts{'peer'} $SSH_PORT");
150    } until (!$?);
151
152    # XXX:  Do we need to clear out previously created bridge interfaces?
153
154    my $count = 0;
155    my @SSHCMD;
156
157    # If we are just setting up a control net connection, just fire up
158    # ssh with the null command, and hang loose.
159
160    if ($type eq "control") {
161        system("$SSH $ssh_port_fwds -Nno \"StrictHostKeyChecking no\" $opts{'peer'} &"); #or die "Failed to run ssh";
162
163        exit;
164    }
165
166    open(IFFILE, "/var/emulab/boot/ifmap") || die "couldn't open ifmap\n";
167    while (<IFFILE>) {
168        my @a = split(' ');
169        my $iface = $a[0];
170        my $addr = $a[1];
171        my $bridge = "bridge" . $count;
172        my $tun = "tap" . $count;
173
174        print "Found $iface, $addr, to bridge on $bridge\n" if ($debug);
175
176        # Note that we're going to fire off an ssh which will never return;
177        # we need the connection to stay up to keep the tunnel up.
178        # In order to check for problems, we open it this way and read
179        # the expected single line of output when the tunnel is connected.
180
181        open($SSHCMD[$count], "$SSH -w $count:$count $ssh_port_fwds -o \"StrictHostKeyChecking no\" $opts{'peer'}  \"$remote_script_dir/fed-tun.pl -r $addr $count\" |") or die "Failed to run ssh";
182
183        my $check = <$SSHCMD[$count]>;  # Make sure something ran...
184        print "Got line [$check] from remote side\n" if ($debug);
185
186        &setup_bridging($tun, $bridge, $iface, $addr);
187        $count++;
188        $ssh_port_fwds = "";  # only do this on the first connection
189    }
190    close(IFFILE);
191} elsif ($remote) {
192    # We're on the remote system;  figure out which interface to
193    # tweak, based on the IP address passed in.
194
195    my $iter = 0;
196    my $iface;
197
198    open(RTFILE, "$ROUTE_GET $addr |") || die "couldn't do $ROUTE_GET\n";
199    while (<RTFILE>) {
200        if (/interface: (\w+)/) {
201            $iface = $1;
202        }
203    }
204    close(RTFILE);
205
206    die "Couldn't find interface to use." if (!defined($iface));
207    my $bridge = "bridge" . $count;
208    my $tun = "tap" . $count;
209
210    &setup_bridging($tun, $bridge, $iface, $addr);
211    print "Remote connection all set up!\n";  # Trigger other end with output
212} else {
213    print "inactive end of a connection, finishing" if ($debug);
214}
215
216print "all done!\n" if ($debug);
217exit;
218
219
220# Set up the bridging for the new stuff...
221
222sub setup_bridging($; $; $; $) {
223    my ($tun, $bridge, $iface, $addr) = @_;
224
225    print "Waiting to see if new iface $tun is up\n" if ($debug);
226
227    do {
228        sleep 1;
229        system("$IFCONFIG $tun");
230    } until (!$?);
231
232    print "setting up $bridge with $iface and nuking $addr\n" if ($debug);
233
234    system("ifconfig $bridge create");
235    system("ifconfig $iface delete $addr");
236    system("ifconfig $bridge addm $iface up");
237    system("ifconfig $bridge addm $tun");
238}
239
240# Set up tunnel info for DETER-like testbeds.
241
242sub setup_tunnel_cfg {
243    my (%opts) = @_;
244    my $tunnel_iface = "em0";   # XXX
245    my $tunnel_ip;
246    my $tunnel_mask;
247    my $tunnel_mac;
248    my $tunnel_router;
249
250    print "Opening $TMCC tunnelip\n" if ($debug);
251
252    open(TMCD, "$TMCC tunnelip |") || die "tmcc failed\n";
253    print "Opened $TMCC tunnelip\n" if ($debug);
254    while (<TMCD>) {
255        print "got one line from tmcc\n" if ($debug);
256        print if ($debug);
257        if (/^TUNNELIP=([0-9.]*) TUNNELMASK=([0-9.]*) TUNNELMAC=(\w*) TUNNELROUTER=([0-9.]*)$/) {
258            $tunnel_ip = $1;
259            $tunnel_mask = $2;
260            $tunnel_mac = $3;
261            $tunnel_router = $4;
262        }
263    }
264    close(TMCD);
265
266    die "Unable to determine tunnel node configuration information"
267        if (!defined($tunnel_router));
268
269    print "tunnel options:  ip=$tunnel_ip mask=$tunnel_mask mac=$tunnel_mac router=$tunnel_router\n" if ($debug);
270
271    # Sadly, we ignore the tunnel mac for now -- we should eventually
272    # use it to determine which interface to use, just like the
273    # Emulab startup scripts.
274
275    system("ifconfig $tunnel_iface $tunnel_ip" .
276           ($tunnel_mask ? " netmask $tunnel_mask" : ""));
277    warn "configuration of tunnel interface failed" if ($?);
278
279    # Sometimes the insertion of DNS names lags a bit.  Retry this
280    # configuration a few times to let DNS catch up.  Might want to really
281    # check the DNS name before we try this...
282    my $config_succeeded = 0;
283    my $tries = 0;
284    my $max_retries = 6;
285
286    do {
287        system("route add $opts{'peer'} $tunnel_router");
288        if ( $? ) {
289            warn "configuration routes via tunnel interface failed";
290            $tries++;
291            sleep(10);
292        }
293        else { $config_succeeded = 1; }
294    } until ( $config_succeeded || $tries > $max_retries );
295
296    print "setup_tunnel_cfg done\n" if ($debug);
297}
298
299# Trick config-file parsing code from Ted Faber:
300
301# Parse the config file.  The format is a colon-separated parameter name
302# followed by the value of that parameter to the end of the line.  This parses
303# that format and puts the parameters into the referenced hash.  Parameter
304# names are mapped to lower case, parameter values are unchanged.  Returns 0 on
305# failure (e.g. file open) and 1 on success.
306sub parse_config {
307    my($file, $href) = @_;
308    my($fh) = new IO::File($file);
309       
310    unless ($fh) {
311        warn "Can't open $file: $!\n";
312        return 0;
313    }
314
315    while (<$fh>) {
316        next if /^\s*#/ || /^\s*$/;     # Skip comments & blanks
317        chomp;
318        /^([^:]+):\s*(.*)/ && do {
319            my($key) = $1; 
320
321            $key =~ tr/A-Z/a-z/;
322            $href->{$key} = $2;
323            next;
324        };
325        warn "Unparasble line in $file: $_\n";
326    }
327    $fh->close();   # It will close when it goes out of scope, but...
328    return 1;
329}
Note: See TracBrowser for help on using the repository browser.