liblocsetup.pm 74.1 KB
Newer Older
1
#!/usr/bin/perl -wT
Leigh Stoller's avatar
Leigh Stoller committed
2
#
3
# Copyright (c) 2000-2017 University of Utah and the Flux Group.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
Leigh Stoller's avatar
Leigh Stoller committed
23 24
#

25 26 27 28 29 30 31
#
# Linux specific routines and constants for the client bootime setup stuff.
#
package liblocsetup;
use Exporter;
@ISA = "Exporter";
@EXPORT =
32
    qw ( $CP $EGREP $NFSMOUNT $UMOUNT $TMPASSWD $SFSSD $SFSCD $RPMCMD
33
	 $HOSTSFILE $LOOPBACKMOUNT $TMGROUP $TMSHADOW $TMGSHADOW $CHMOD
34
	 os_account_cleanup os_ifconfig_line os_etchosts_line
35
	 os_setup os_groupadd os_useradd os_userdel os_usermod os_mkdir
36
	 os_ifconfig_veth os_viface_name os_modpasswd
37 38
	 os_routing_enable_forward os_routing_enable_gated
	 os_routing_add_manual os_routing_del_manual os_homedirdel
39
	 os_groupdel os_getnfsmounts os_islocaldir os_mountextrafs
40
	 os_fwconfig_line os_fwrouteconfig_line os_config_gre
41
	 os_get_disks os_get_disk_size os_get_partition_info os_nfsmount
42
	 os_get_ctrlnet_ip
43
	 os_getarpinfo os_createarpentry os_removearpentry
44
	 os_getstaticarp os_setstaticarp os_ismounted os_unmount os_mount
45 46
       );

47 48
sub VERSION()	{ return 1.0; }

49 50
# Must come after package declaration!
use English;
51
use Fcntl;
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
# Load up the paths. Its conditionalized to be compatabile with older images.
# Note this file has probably already been loaded by the caller.
BEGIN
{
    if (-e "/etc/emulab/paths.pm") {
	require "/etc/emulab/paths.pm";
	import emulabpaths;
    }
    else {
	my $ETCDIR  = "/etc/rc.d/testbed";
	my $BINDIR  = "/etc/rc.d/testbed";
	my $VARDIR  = "/etc/rc.d/testbed";
	my $BOOTDIR = "/etc/rc.d/testbed";
    }
}
68

69 70
# Convenience.
sub REMOTE()	{ return libsetup::REMOTE(); }
71
sub REMOTEDED()	{ return libsetup::REMOTEDED(); }
72
sub PLAB()	{ return libsetup::PLAB(); }
73 74 75
sub LINUXJAILED()  { return libsetup::LINUXJAILED(); }
sub GENVNODE()     { return libsetup::GENVNODE(); }
sub GENVNODETYPE() { return libsetup::GENVNODETYPE(); }
76
sub INXENVM()   { return libsetup::INXENVM(); }
77
sub INVZVM()    { return libsetup::INVZVM(); }
78
sub INDOCKERVM()    { return libsetup::INDOCKERVM(); }
79

80 81
#
# Various programs and things specific to Linux and that we want to export.
82
#
83
$CP		= "/bin/cp";
Mike Hibler's avatar
Mike Hibler committed
84
$DF		= "/bin/df";
85
$EGREP		= "/bin/egrep -q";
86 87 88
# Note that we try multiple versions in os_nfsmount below; this is for legacy
# code, or code where the mount is best done in the caller itself... or code
# I didn't want to convert!
89
$NFSMOUNT	= "/bin/mount -o nolock,udp";
90
$LOOPBACKMOUNT	= "/bin/mount -n -o bind ";
91
$UMOUNT		= "/bin/umount";
92
$MOUNT		= "/bin/mount";
93
$TMPASSWD	= "$ETCDIR/passwd";
94 95 96
$TMGROUP	= "$ETCDIR/group";
$TMSHADOW       = "$ETCDIR/shadow";
$TMGSHADOW      = "$ETCDIR/gshadow";
97 98
$SFSSD		= "/usr/local/sbin/sfssd";
$SFSCD		= "/usr/local/sbin/sfscd";
99
$RPMCMD		= "/bin/rpm";
100
$HOSTSFILE	= "/etc/hosts";
101
$WGET		= "/usr/bin/wget";
102
$CHMOD		= "/bin/chmod";
103
$ARP		= "/sbin/arp";
104 105 106 107

#
# These are not exported
#
108 109 110
my $TMGROUP	= "$ETCDIR/group";
my $TMSHADOW    = "$ETCDIR/shadow";
my $TMGSHADOW   = "$ETCDIR/gshadow";
111 112 113 114
my $USERADD     = "/usr/sbin/useradd";
my $USERDEL     = "/usr/sbin/userdel";
my $USERMOD     = "/usr/sbin/usermod";
my $GROUPADD	= "/usr/sbin/groupadd";
115
my $GROUPDEL	= "/usr/sbin/groupdel";
116
my $IPBIN       = "/sbin/ip";
117 118
my $IFCONFIGBIN = "/sbin/ifconfig";
my $IFCONFIG    = "$IFCONFIGBIN %s inet %s netmask %s";
119
my $VLANCONFIG  = "/sbin/vconfig";
Mike Hibler's avatar
Mike Hibler committed
120 121
# XXX 10000 is probably not right, but we don't use mii-tool here
my $IFC_10000MBS = "10000baseTx";
122
my $IFC_1000MBS  = "1000baseTx";
123 124 125 126
my $IFC_100MBS  = "100baseTx";
my $IFC_10MBS   = "10baseT";
my $IFC_FDUPLEX = "FD";
my $IFC_HDUPLEX = "HD";
127
my @LOCKFILES   = ("/etc/group.lock", "/etc/gshadow.lock");
128
my $MKDIR	= "/bin/mkdir";
129 130
my $GATED	= "/usr/sbin/gated";
my $ROUTE	= "/sbin/route";
131 132
my $SHELLS	= "/etc/shells";
my $DEFSHELL	= "/bin/tcsh";
133 134 135 136 137 138
my $IWCONFIG    = '/usr/local/sbin/iwconfig';
my $WLANCONFIG  = '/usr/local/bin/wlanconfig';
my $RMMOD       = '/sbin/rmmod';
my $MODPROBE    = '/sbin/modprobe';
my $IWPRIV      = '/usr/local/sbin/iwpriv';
my $BRCTL       = "/usr/sbin/brctl";
139
my $ISCSI	= "/sbin/iscsiadm";
140

141 142 143 144
my $PASSDB   = "$VARDIR/db/passdb";
my $GROUPDB  = "$VARDIR/db/groupdb";
my $SYSETCDIR = "/etc";

145 146
my $debug = 0;

147 148
#
# OS dependent part of cleanup node state.
149
#
150
sub os_account_cleanup($)
151
{
152 153 154 155 156 157
    # XXX this stuff should be lifted up into rc.accounts, sigh
    my ($updatemasterpasswdfiles) = @_;
    if (!defined($updatemasterpasswdfiles)) {
	$updatemasterpasswdfiles = 0;
    }

158 159 160
    #
    # Don't just splat the master passwd/group files into place from $ETCDIR.
    # Instead, grab the current Emulab uids/gids, grab the current group/passwd
161
    # files and their shadow counterparts, remove any emulab u/gids from the
162 163 164 165 166
    # loaded instance of the current files, then push any new/changed uid/gids
    # into the master files in $ETCDIR.  Also, we remove accounts from the
    # master files if they no longer appear in the current files.  Finally, we
    # strip deleted uids from any groups they might appear in (!).
    #
167 168 169 170 171 172 173 174
    # And now we only do the merge if told to do so.  This is the default 
    # coming from prepare, now.  If not merging, we just overwrite the real 
    # files with the master files -- we do not update the master files.
    #
    # We *do* output the diff to say what *would* have changed, so that
    # an operator can know that they need to manually add a user to the 
    # master files.
    #
175 176 177
    my %PDB;
    my %GDB;

178
    dbmopen(%PDB, $PASSDB, 0660) or
179
	die "Cannot open $PASSDB: $!";
180
    dbmopen(%GDB, $GROUPDB, 0660) or
181
	die "Cannot open $GROUPDB: $!";
182

183 184 185 186 187 188
    if ($debug) {
	use Data::Dumper;
	print Dumper(%PDB) . "\n\n";
	print Dumper(%GDB) . "\n\n";
    }

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    my %lineHash = ();
    my %lineList = ();

    foreach my $file ("$SYSETCDIR/passwd","$SYSETCDIR/group",
		      "$SYSETCDIR/shadow","$SYSETCDIR/gshadow",
		      "$ETCDIR/passwd","$ETCDIR/group",
		      "$ETCDIR/shadow","$ETCDIR/gshadow") {
	open(FD,$file)
	    or die "open($file): $!";
	my $i = 0;
	my $lineCounter = 1;
	while (my $line = <FD>) {
	    chomp($line);

	    # store the line in the list
	    if (!defined($lineList{$file})) {
		$lineList{$file} = [];
	    }
	    $lineList{$file}->[$i] = $line;

	    # fill the hash for fast lookups, and place the array idx of the
	    # element in the lineList as the hash value so that we can undef
	    # it if deleting it, while still preserving the line orderings in
	    # the original files.  whoo!
	    if ($line ne '' && $line =~ /^([^:]+):.*$/) {
		if (!defined($lineHash{$file})) {
		    $lineHash{$file} = {};
		}
		$lineHash{$file}->{$1} = $i++;
	    }
	    else {
		print STDERR "malformed line $lineCounter in $file, ignoring!\n";
	    }
	    ++$lineCounter;
	}
    }

226 227 228
    print Dumper(%lineHash) . "\n\n\n"
	if ($debug);

229 230
    # remove emulab groups first (save a bit of work):
    while (my ($group,$gid) = each(%GDB)) {
231 232
	print "DEBUG: $group/$gid\n"
	    if ($debug);
233 234 235 236 237
	foreach my $file ("$SYSETCDIR/group","$SYSETCDIR/gshadow") {
	    if (defined($lineHash{$file}->{$group})) {
		# undef its line
		$lineList{$file}->[$lineHash{$file}->{$group}] = undef;
		delete $lineHash{$file}->{$group};
238 239
		print "DEBUG: deleted group $group from $file\n"
		    if ($debug);
240 241 242 243 244 245 246 247 248 249 250 251
	    }
	}
    }

    # now remove emulab users from users files, AND from the group list
    # in any groups :-)
    while (my ($user,$uid) = each(%PDB)) {
	foreach my $file ("$SYSETCDIR/passwd","$SYSETCDIR/shadow") {
	    if (defined($lineHash{$file}->{$user})) {
		# undef its line
		$lineList{$file}->[$lineHash{$file}->{$user}] = undef;
		delete $lineHash{$file}->{$user};
252 253
		print "DEBUG: deleted user  $user from $file\n"
		    if ($debug);
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
	    }
	}

	# this is indeed a lot of extra text processing, but whatever
	foreach my $file ("$SYSETCDIR/group","$SYSETCDIR/gshadow") {
	    foreach my $group (keys(%{$lineHash{$file}})) {
		my $groupLine = $lineList{$file}->[$lineHash{$file}->{$group}];
		# grab the fields
		# split using -1 to make sure our empty trailing fields are
		# added!
		my @elms = split(/\s*:\s*/,$groupLine,-1);
		# grab the user list
		my @ulist = split(/\s*,\s*/,$elms[scalar(@elms)-1]);
		# build a new list
		my @newulist = ();
		my $j = 0;
		my $k = 0;
		for ($j = 0; $j < scalar(@ulist); ++$j) {
		    # only add to the new user list if it's not the user we're
		    # removing.
		    my $suser = $ulist[$j];
		    if ($suser ne $user) {
			$newulist[$k++] = $suser;
		    }
		}
		# rebuild the user list
		$elms[scalar(@elms)-1] = join(',',@newulist);
		# rebuild the line from the fields
		$groupLine = join(':',@elms);
		# stick the line back into the "file"
		$lineList{$file}->[$lineHash{$file}->{$group}] = $groupLine;
	    }
	}
287
    }
288 289 290 291 292 293 294 295 296 297 298 299 300

    # now, merge current files into masters.
    foreach my $pairRef (["$SYSETCDIR/passwd","$ETCDIR/passwd"],
			 ["$SYSETCDIR/group","$ETCDIR/group"],
			 ["$SYSETCDIR/shadow","$ETCDIR/shadow"],
			 ["$SYSETCDIR/gshadow","$ETCDIR/gshadow"]) {
	my ($real,$master) = @$pairRef;

	foreach my $ent (keys(%{$lineHash{$real}})) {
	    # push new entities into master
	    if (!defined($lineHash{$master}->{$ent})) {
		# append new "line"
		$lineHash{$master}->{$ent} = scalar(@{$lineList{$master}});
301
		$lineList{$master}->[$lineHash{$master}->{$ent}] =
302
		    $lineList{$real}->[$lineHash{$real}->{$ent}];
303 304
		print "DEBUG: adding $ent to $master\n"
		    if ($debug);
305 306
	    }
	    # or replace modified entities
307
	    elsif ($lineList{$real}->[$lineHash{$real}->{$ent}]
308
		   ne $lineList{$master}->[$lineHash{$master}->{$ent}]) {
309
		$lineList{$master}->[$lineHash{$master}->{$ent}] =
310
		    $lineList{$real}->[$lineHash{$real}->{$ent}];
311 312
		print "DEBUG: updating $ent in $master\n"
		    if ($debug);
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	    }
	}

	# now remove stale lines from the master
	my @todelete = ();
	foreach my $ent (keys(%{$lineHash{$master}})) {
	    if (!defined($lineHash{$real}->{$ent})) {
		# undef its line
		$lineList{$master}->[$lineHash{$master}->{$ent}] = undef;
		push @todelete, $ent;
	    }
	}
	foreach my $delent (@todelete) {
	    delete $lineHash{$master}->{$delent};
	}
328
    }
329

330
    # now write the masters to .new files so we can diff, do the diff for
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    # files that are world-readable, then mv into place over the masters.
    my %modes = ( "$ETCDIR/passwd" => 0644,"$ETCDIR/group" => 0644,
		  "$ETCDIR/shadow" => 0600,"$ETCDIR/gshadow" => 0600 );
    foreach my $file (keys(%modes)) {
	sysopen(FD,"${file}.new",O_CREAT | O_WRONLY | O_TRUNC,$modes{$file})
	    # safe to die here cause we haven't moved any .new files into
	    # place
	    or die "sysopen(${file}.new): $!";
	for (my $i = 0; $i < scalar(@{$lineList{$file}}); ++$i) {
	    # remember, some lines may be undef cause we deleted them
	    if (defined($lineList{$file}->[$i])) {
		print FD $lineList{$file}->[$i] . "\n";
	    }
	}
	close(FD);
    }
    foreach my $file (keys(%modes)) {
	my $retval;
	if ($modes{$file} == 0644) {
	    print STDERR "Running 'diff -u $file ${file}.new'\n";
	    $retval = system("diff -u $file ${file}.new");
	    if ($retval) {
353 354 355 356 357 358 359 360 361 362 363
		if ($updatemasterpasswdfiles) {
		    print STDERR "Files ${file}.new and $file differ; updating $file.\n";
		    system("mv ${file}.new $file");
		}
		else {
		    print STDERR "Files ${file}.new and $file differ, but I was told not to update the master files!.\n";
		    system("rm -f ${file}.new");
		}
	    }
	    else {
		system("rm -f ${file}.new");
364 365 366 367 368 369
	    }
	}
	else {
	    print STDERR "Running 'diff -q -u $file ${file}.new'\n";
	    $retval = system("diff -q -u $file ${file}.new");
	    if ($retval) {
370 371 372 373 374 375 376 377 378 379 380
		if ($updatemasterpasswdfiles) {
		    print STDERR "Files ${file}.new and $file differ, but we can't show the changes!  Updating $file anyway!\n";
		    system("mv ${file}.new $file");
		}
		else {
		    print STDERR "Files ${file}.new and $file differ, but we can't show the changes, and I was told not to update the master files!\n";
		    system("rm -f ${file}.new");
		}
	    }
	    else {
		system("rm -f ${file}.new");
381 382 383 384 385 386 387
	    }
	}
    }

    dbmclose(%PDB);
    dbmclose(%GDB);

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    #
    # Splat the new files into place, doh
    #
    unlink @LOCKFILES;

    printf STDOUT "Resetting passwd and group files\n";
    if (system("$CP -f $TMGROUP $TMPASSWD /etc") != 0) {
        print STDERR "Could not copy default group file into place: $!\n";
        return -1;
    }

    if (system("$CP -f $TMSHADOW $TMGSHADOW /etc") != 0) {
        print STDERR "Could not copy default passwd file into place: $!\n";
        return -1;
    }

404 405 406 407 408 409 410
    return 0;
}

#
# Generate and return an ifconfig line that is approriate for putting
# into a shell script (invoked at bootup).
#
411
sub os_ifconfig_line($$$$$$$$;$$$)
412
{
413
    my ($iface, $inet, $mask, $speed, $duplex, $aliases, $iface_type, $lan,
414
	$settings, $rtabid, $cookie) = @_;
415 416 417
    my ($miirest, $miisleep, $miisetspd, $media);
    my ($uplines, $downlines);

418 419 420 421 422 423 424 425 426 427 428
    #
    # Inside a container, we get a regular interface, but tmcd sets the
    # type=gre so we know to set the MTU properly. This number seems to
    # work for both openvz and xen containers. 
    #
    if ($iface_type eq "gre" && GENVNODE()) {
	$uplines   = "$IFCONFIGBIN $iface $inet netmask $mask mtu 1450 up";
	$downlines = "$IFCONFIGBIN $iface down";
	return ($uplines, $downlines);
    }

429 430
    #
    # Special handling for new style interfaces (which have settings).
431
    # This should all move into per-type modules at some point.
432
    #
433
    if ($iface_type eq "ath" && defined($settings)) {
434

435 436 437 438 439
        # Get a handle on the "VAP" interface we will create when
        # setting up this interface.
        my ($ifnum) = $iface =~ /wifi(\d+)/;
        my $athiface = "ath" . $ifnum;

440 441 442 443 444
	#
	# Setting the protocol is special and appears to be card specific.
	# How stupid is that!
	#
	my $protocol = $settings->{"protocol"};
445
        my $privcmd = "/usr/local/sbin/iwpriv $athiface mode ";
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

        SWITCH1: for ($protocol) {
          /^80211a$/ && do {
              $privcmd .= "1";
              last SWITCH1;
          };
          /^80211b$/ && do {
              $privcmd .= "2";
              last SWITCH1;
          };
          /^80211g$/ && do {
              $privcmd .= "3";
              last SWITCH1;
          };
        }
461

462 463 464 465
	#
	# At the moment, we expect just the various flavors of 80211, and
	# we treat them all the same, configuring with iwconfig and iwpriv.
	#
466 467 468
	my $iwcmd = "/usr/local/sbin/iwconfig $athiface ";
        my $wlccmd = "/usr/local/bin/wlanconfig $athiface create ".
            "wlandev $iface ";
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499

	#
	# We demand to be given an ssid.
	#
	if (!exists($settings->{"ssid"})) {
	    warn("*** WARNING: No SSID provided for $iface!\n");
	    return undef;
	}
	$iwcmd .= "essid ". $settings->{"ssid"};

	# If we do not get a channel, pick one.
	if (exists($settings->{"channel"})) {
	    $iwcmd .= " channel " . $settings->{"channel"};
	}
	else {
	    $iwcmd .= " channel 3";
	}

	# txpower and rate default to auto if not specified.
	if (exists($settings->{"rate"})) {
	    $iwcmd .= " rate " . $settings->{"rate"};
	}
	else {
	    $iwcmd .= " rate auto";
	}
	if (exists($settings->{"txpower"})) {
	    $iwcmd .= " txpower " . $settings->{"txpower"};
	}
	else {
	    $iwcmd .= " txpower auto";
	}
500
	# Allow this too.
501 502 503 504 505 506 507 508 509 510
	if (exists($settings->{"sens"})) {
	    $iwcmd .= " sens " . $settings->{"sens"};
	}

	# allow rts threshold and frag size
	if (exists($settings->{'rts'})) {
	    $iwcmd .= ' rts ' . $settings->{'rts'};
	}
	if (exists($settings->{'frag'})) {
	    $iwcmd .= ' frag ' . $settings->{'frag'};
511 512 513 514
	}

	#
	# We demand to be told if we are the master or a peon.
515 516 517 518 519 520
	# We might also be in another mode.  Thus, if accesspoint is specified,
	# we assume we are in either ap/sta (Master/Managed) mode.  If not,
	# we look for a 'mode' argument and assume adhoc if we don't get one.
	# The reason to assume adhoc is because we need accesspoint set to
	# know how to configure the device for ap/sta modes, and setting a
	# device to monitor mode by default sucks.
521
	#
522 523
	# This needs to be last for some reason.
	#
524 525 526
	if (exists($settings->{'accesspoint'})) {
	    my $accesspoint = $settings->{"accesspoint"};
	    my $accesspointwdots;
527

528 529 530 531 532 533 534 535 536 537 538 539 540 541
	    # Allow either dotted or undotted notation!
	    if ($accesspoint =~ /^(\w{2})(\w{2})(\w{2})(\w{2})(\w{2})(\w{2})$/) {
		$accesspointwdots = "$1:$2:$3:$4:$5:$6";
	    }
	    elsif ($accesspoint =~
		   /^(\w{2}):(\w{2}):(\w{2}):(\w{2}):(\w{2}):(\w{2})$/) {
		$accesspointwdots = $accesspoint;
		$accesspoint      = "${1}${2}${3}${4}${5}${6}";
	    }
	    else {
		warn("*** WARNING: Improper format for MAC ($accesspoint) ".
		     "provided for $iface!\n");
		return undef;
	    }
542

543 544 545 546 547 548 549 550
	    if (libsetup::findiface($accesspoint) eq $iface) {
		$wlccmd .= " wlanmode ap";
		$iwcmd .= " mode Master";
	    }
	    else {
		$wlccmd .= " wlanmode sta";
		$iwcmd .= " mode Managed ap $accesspointwdots";
	    }
551
	}
552 553 554 555 556 557 558 559 560
	elsif (exists($settings->{'mode'})) {
	    if ($settings->{'mode'} =~ /ad[\s\-]*hoc/i) {
		$wlccmd .= " wlanmode adhoc";
		$iwcmd .= " mode Ad-Hoc";
	    }
	    elsif ($settings->{'mode'} =~ /monitor/i) {
		$wlccmd .= " wlanmode monitor";
		$iwcmd .= " mode Monitor";
	    }
561 562
	    elsif ($settings->{'mode'} =~ /ap/i
		   || $settings->{'mode'} =~ /access[\s\-]*point/i
563 564 565 566
		   || $settings->{'mode'} =~ /master/i) {
		$wlccmd .= " wlanmode ap";
		$iwcmd .= " mode Master";
	    }
567
	    elsif ($settings->{'mode'} =~ /sta/i
568 569 570 571 572 573 574 575
		   || $settings->{'mode'} =~ /managed/i) {
		$wlccmd .= " wlanmode sta";
		$iwcmd .= " mode Managed ap any";
	    }
	    else {
		warn("*** WARNING: Invalid mode provided for $iface!\n");
		return undef;
	    }
576 577
	}
	else {
578
	    warn("*** WARNING: No mode implied for $iface!\n");
579 580
	    return undef;
	}
581

582
        $uplines   = $wlccmd . "\n";
583
	$uplines  .= $privcmd . "\n";
584
	$uplines  .= $iwcmd . "\n";
Kirk Webb's avatar
Kirk Webb committed
585 586
	$uplines  .= sprintf($IFCONFIG, $athiface, $inet, $mask) . "\n";
	$downlines  = "$IFCONFIGBIN $athiface down\n";
587
	$downlines .= "$WLANCONFIG $athiface destroy\n";
Kirk Webb's avatar
Kirk Webb committed
588
	$downlines .= "$IFCONFIGBIN $iface down\n";
589 590
	return ($uplines, $downlines);
    }
591

592 593 594 595 596
    #
    # GNU Radio network interface on the flex900 daugherboard
    #
    if ($iface_type eq "flex900" && defined($settings)) {

597
        my $tuncmd =
598 599 600 601 602 603 604 605 606 607 608
            "/bin/env PYTHONPATH=/usr/local/lib/python2.4/site-packages ".
            "$BINDIR/tunnel.py";

        if (!exists($settings->{"mac"})) {
            warn("*** WARNING: No mac address provided for gnuradio ".
                 "interface!\n");
            return undef;
        }

        my $mac = $settings->{"mac"};

609
        if (!exists($settings->{"protocol"}) ||
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
            $settings->{"protocol"} ne "flex900") {
            warn("*** WARNING: Unknown gnuradio protocol specified!\n");
            return undef;
        }

        if (!exists($settings->{"frequency"})) {
            warn("*** WARNING: No frequency specified for gnuradio ".
                 "interface!\n");
            return undef;
        }

        my $frequency = $settings->{"frequency"};
        $tuncmd .= " -f $frequency";

        if (!exists($settings->{"rate"})) {
            warn("*** WARNING: No rate specified for gnuradio interface!\n");
            return undef;
        }

        my $rate = $settings->{"rate"};
        $tuncmd .= " -r $rate";

632 633 634 635 636 637 638
	if (exists($settings->{'carrierthresh'})) {
	    $tuncmd .= " -c " . $settings->{'carrierthresh'};
	}
	if (exists($settings->{'rxgain'})) {
	    $tuncmd .= " --rx-gain=" . $settings->{'rxgain'};
	}

639 640 641 642 643 644 645 646
        $uplines = $tuncmd . " > /dev/null 2>&1 &\n";
        $uplines .= "sleep 5\n";
        $uplines .= "$IFCONFIGBIN $iface hw ether $mac\n";
        $uplines .= sprintf($IFCONFIG, $iface, $inet, $mask) . "\n";
        $downlines = "$IFCONFIGBIN $iface down";
        return ($uplines, $downlines);
    }

647
    #
648
    # Only do this stuff if we have a physical interface, otherwise it doesn't
649
    # mean anything.  We need this for virtnodes whose networks must be
650
    # config'd from inside the container, vm, whatever.
651
    #
652 653 654 655
    if ($iface_type ne 'veth') {
        #
        # Need to check units on the speed. Just in case.
        #
656 657 658 659
	if (!defined($speed)) {
	    warn("*** No speed defined, default to 100Mbps\n");
	    $speed = 100;
	}
660 661 662 663 664 665 666 667 668 669 670
	if ($speed =~ /(\d*)([A-Za-z]*)/) {
	    if ($2 eq "Mbps") {
		$speed = $1;
	    }
	    elsif ($2 eq "Kbps") {
		$speed = $1 / 1000;
	    }
	    else {
		warn("*** Bad speed units $2 in ifconfig, default to 100Mbps\n");
		$speed = 100;
	    }
Mike Hibler's avatar
Mike Hibler committed
671 672 673 674
	    if ($speed == 10000) {
		$media = $IFC_10000MBS;
	    }
	    elsif ($speed == 1000) {
675 676 677 678 679 680 681 682
		$media = $IFC_1000MBS;
	    }
	    elsif ($speed == 100) {
		$media = $IFC_100MBS;
	    }
	    elsif ($speed == 10) {
		$media = $IFC_10MBS;
	    }
683 684 685 686
	    elsif ($speed == 0) {
		warn("*** Speed was 0 in ifconfig, defaulting to auto negotiation (and Gb media)\n");
		$media = $IFC_1000MBS;
	    }
687 688 689 690 691
	    else {
		warn("*** Bad Speed $speed in ifconfig, default to 100Mbps\n");
		$speed = 100;
		$media = $IFC_100MBS;
	    }
692
	}
693 694 695 696
	if (!defined($duplex)) {
	    warn("*** No duplex defined, default to full\n");
	    $duplex = "full";
	}
697 698
	if ($duplex eq "full") {
	    $media = "$media-$IFC_FDUPLEX";
699
	}
700 701
	elsif ($duplex eq "half") {
	    $media = "$media-$IFC_HDUPLEX";
702 703
	}
	else {
704 705 706
	    warn("*** Bad duplex $duplex in ifconfig, default to full\n");
	    $duplex = "full";
	    $media = "$media-$IFC_FDUPLEX";
707 708
	}

709
        #
Mike Hibler's avatar
Mike Hibler committed
710 711 712 713 714
        # Linux is apparently changing from mii-tool to ethtool but some
	# drivers don't support the new interface (3c59x), some don't support
	# the old interface (e1000), and some (eepro100) support the new
	# interface just enough that they can report success but not actually
	# do anything. Sweet!
715 716 717 718 719 720 721 722 723
        #
	my $ethtool;
	if (-e "/sbin/ethtool") {
	    $ethtool = "/sbin/ethtool";
	} elsif (-e "/usr/sbin/ethtool") {
	    $ethtool = "/usr/sbin/ethtool";
	}
	if (defined($ethtool)) {
	    # this seems to work for returning an error on eepro100
724
	    $uplines =
725
		"if $ethtool $iface >/dev/null 2>&1; then\n    ";
726 727 728 729 730 731 732 733 734 735 736 737
	    #
	    # Special cases:
	    # - '0' means autoneg
	    # - '1000', aka gigabit, we *must* turn on autoneg--
	    #   it's part of the GbE protocol.
	    # - '10000', aka 10GE, don't try to set anything
	    #
	    if ($speed eq '0' || $speed eq '1000') {
		$uplines .= "  $ethtool -s $iface autoneg on\n    ";
	    }
	    elsif ($speed eq '10000') {
		$uplines .= "  true\n    ";
738 739 740 741
	    }
	    else {
		$uplines .=
		    "  $ethtool -s $iface autoneg off speed $speed duplex $duplex\n    " .
Mike Hibler's avatar
Mike Hibler committed
742
		    "  sleep 2 # needed due to likely bug in e100 driver on pc850s\n    ";
743 744
	    }
	    $uplines .= 
745 746 747 748 749 750
		"else\n    " .
		"  /sbin/mii-tool --force=$media $iface\n    " .
		"fi\n    ";
	} else {
	    $uplines = "/sbin/mii-tool --force=$media $iface\n    ";
	}
751 752
    }

753 754 755 756
    if ($inet eq "") {
	$uplines .= "$IFCONFIGBIN $iface up";
    }
    else {
757 758 759
	$uplines  .= sprintf($IFCONFIG, $iface, $inet, $mask);
	$downlines = "$IFCONFIGBIN $iface down";
    }
760

761
    return ($uplines, $downlines);
762 763
}

764
#
765
# Specialized function for configing virtual ethernet devices:
766
#
767
#	'veth'	one end of an etun device embedded in a vserver
768 769 770 771
#	'vlan'	802.1q tagged vlan devices
#	'alias'	IP aliases on physical interfaces
#
sub os_ifconfig_veth($$$$$;$$$$%)
772
{
773 774 775 776
    my ($iface, $inet, $mask, $id, $vmac,
	$rtabid, $encap, $vtag, $itype, $cookie) = @_;
    my ($uplines, $downlines);

777 778
    if ($itype !~ /^(alias|vlan|veth)$/) {
	warn("Unknown virtual interface type $itype\n");
779 780 781
	return "";
    }

782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
    #
    # Veth.
    #
    # Veths for Linux vservers mean vtun devices.  One end is outside
    # the vserver and is bridged with other veths and peths as appropriate
    # to form the topology.  The other end goes in the vserver and is
    # configured with an IP address.  This final step is not done here
    # as the vserver must be running first.
    #
    # In the current configuration, there is configuration that takes
    # place both inside and outside the vserver.
    #
    # Inside:
    # The inside case (LINUXJAILED() == 1) just configures the IP info on
    # the interface.
    #
    # Outside:
    # The outside actions are much more involved as described above.
    # The VTAG identifies a bridge device "ebrN" to be used.
    # The RTABID identifies the namespace, but we don't care here.
    #
    # To create a etun pair you do:
    #    echo etun0,etun1 > /sys/module/etun/parameters/newif
    # To destroy do:
    #    echo etun0 > /sys/module/etun/parameters/delif
    #
    if ($itype eq "veth") {
	#
	# We are inside a Linux jail.
	# We configure the interface pretty much like normal.
	#
	if (LINUXJAILED()) {
	    if ($inet eq "") {
		$uplines .= "$IFCONFIGBIN $iface up";
	    }
	    else {
		$uplines  .= sprintf($IFCONFIG, $iface, $inet, $mask);
		$downlines = "$IFCONFIGBIN $iface down";
	    }
821

822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
	    return ($uplines, $downlines);
	}

	#
	# Outside jail.
	# Create tunnels and bridge and plumb them all together.
	#
	my $brdev = "ebr$vtag";
	my $iniface = "veth$id";
	my $outiface = "peth$id";
	my $devdir = "/sys/module/etun/parameters";

	# UP
	$uplines = "";

	# modprobe (should be done already for cnet setup, but who cares)
	$uplines .= "modprobe etun\n";

	# make sure bridge device exists and is up
	$uplines .= "    $IFCONFIGBIN $brdev >/dev/null 2>&1 || {";
	$uplines .= "        $BRCTL addbr $brdev\n";
	$uplines .= "        $IFCONFIGBIN $brdev up\n";
	$uplines .= "    }\n";

	# create the tunnel device
	$uplines .= "    echo $outiface,$iniface > $devdir/newif || exit 1\n";

	# bring up outside IF, insert into bridge device
	$uplines .= "    $IFCONFIGBIN $outiface up || exit 2\n";
	$uplines .= "    $BRCTL addif $brdev $outiface || exit 3\n";

	# configure the MAC address for the inside device
	$uplines .= "    $IFCONFIGBIN $iniface hw ether $vmac || exit 4\n";

	# DOWN
	$downlines = "";

	# remove IF from bridge device, down it (remove bridge if empty?)
	$downlines .= "$BRCTL delif $brdev $outiface || exit 13\n";
	$downlines .= "    $IFCONFIGBIN $outiface down || exit 12\n";

	# destroy tunnel devices (this will fail if inside IF in vserver still)
	$downlines .= "    echo $iniface > $devdir/delif || exit 11\n";

	return ($uplines, $downlines);
    }

869 870 871 872
    #
    # IP aliases
    #
    if ($itype eq "alias") {
873 874
	$uplines = "$IPBIN addr add $inet/$mask dev $iface";
	$downlines = "$IPBIN addr del $inet/$mask dev $iface";
875 876 877 878 879 880 881 882 883
	return ($uplines, $downlines);
    }

    #
    # VLANs
    #   insmod 8021q (once only)
    #   vconfig set_name_type VLAN_PLUS_VID_NO_PAD (once only)
    #
    #	ifconfig eth0 up (should be done before we are ever called)
884
    #	vconfig add eth0 601
885 886 887 888 889 890 891 892 893 894 895
    #   ifconfig vlan601 inet ...
    #
    #   ifconfig vlan601 down
    #	vconfig rem vlan601
    #
    if ($itype eq "vlan") {
	if (!defined($vtag)) {
	    warn("No vtag in veth config\n");
	    return "";
	}

896 897 898 899 900 901
	# XXX starting with CentOS7, vconfig is no longer
	my $useip = 0;
	if (! -x $VLANCONFIG) {
	    $useip = 1;
	}

902 903 904
	# one time stuff
	if (!exists($cookie->{"vlan"})) {
	    $uplines  = "/sbin/insmod 8021q >/dev/null 2>&1\n    ";
905 906
	    $uplines .= "$VLANCONFIG set_name_type VLAN_PLUS_VID_NO_PAD\n    "
		if (!$useip);
907 908 909 910 911
	    $cookie->{"vlan"} = 1;
	}

	my $vdev = "vlan$vtag";

912 913 914 915 916
	if ($useip) {
	    $uplines   .= "/sbin/ip link add link $iface name $vdev type vlan id $vtag\n    ";
	} else {
	    $uplines   .= "$VLANCONFIG add $iface $vtag\n    ";
	}
917
	$uplines   .= sprintf($IFCONFIG, $vdev, $inet, $mask);
918 919 920
	# configure the MAC address.
	$uplines   .= "\n    $IFCONFIGBIN $vdev hw ether $vmac"
	    if ($vmac);
921

922
	$downlines .= "$IFCONFIGBIN $vdev down\n    ";
923 924 925 926 927
	if ($useip) {
	    $downlines .= "/sbin/ip link delete $vdev";
	} else {
	    $downlines .= "$VLANCONFIG rem $vdev";
	}
928 929 930
    }

    return ($uplines, $downlines);
931 932
}

933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
#
# Compute the name of a virtual interface device based on the
# information in ifconfig hash (as returned by getifconfig).
#
sub os_viface_name($)
{
    my ($ifconfig) = @_;
    my $piface = $ifconfig->{"IFACE"};

    #
    # Physical interfaces use their own name
    #
    if (!$ifconfig->{"ISVIRT"}) {
	return $piface;
    }

    #
    # Otherwise we have a virtual interface: alias, veth, vlan.
    #
    # alias: There is an alias device, but not sure what it is good for
    #        so for now we just return the phys device.
    # vlan:  vlan<VTAG>
955
    # veth:  veth<ID>
956 957 958 959 960 961
    #
    my $itype = $ifconfig->{"ITYPE"};
    if ($itype eq "alias") {
	return $piface;
    } elsif ($itype eq "vlan") {
	return $itype . $ifconfig->{"VTAG"};
962 963
    } elsif ($itype eq "veth") {
	return $itype . $ifconfig->{"ID"};
964 965 966 967 968 969
    }

    warn("Linux does not support virtual interface type '$itype'\n");
    return undef;
}

970 971 972 973
#
# Generate and return an string that is approriate for putting
# into /etc/hosts.
#
974
sub os_etchosts_line($$$)
975
{
976
    my ($name, $ip, $aliases) = @_;
977

978
    return sprintf("%s\t%s %s", $ip, $name, $aliases);
979 980 981 982
}

#
# Add a new group
983
#
984
sub os_groupadd($$)
985
{
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    if (INVZVM()) {
	my $tries  = 10;
	my $result = 1;
	while ($tries-- > 0) {
	    $result = os_groupadd_real(@_);
	    last
		if (!$result || !$tries);

	    warn("$GROUPADD returned $result ... trying again in a bit\n");
	    sleep(10);
	}
	return $result;
    }
    else {
	return os_groupadd_real(@_);
1001 1002 1003 1004
    }
}

sub os_groupadd_real($$)
1005
{
1006
    my ($group, $gid) = @_;
1007 1008 1009 1010

    return system("$GROUPADD -g $gid $group");
}

1011 1012
#
# Delete an old group
1013
#
1014 1015 1016 1017 1018 1019 1020
sub os_groupdel($)
{
    my($group) = @_;

    return system("$GROUPDEL $group");
}

1021 1022
#
# Remove a user account.
1023
#
1024 1025 1026 1027 1028 1029 1030 1031 1032
sub os_userdel($)
{
    my($login) = @_;

    return system("$USERDEL $login");
}

#
# Modify user group membership.
1033
#
1034
sub os_usermod($$$$$$)
1035
{
1036
    my($login, $gid, $glist, $pswd, $root, $shell) = @_;
1037 1038 1039 1040 1041 1042 1043

    if ($root) {
	$glist = join(',', split(/,/, $glist), "root");
    }
    if ($glist ne "") {
	$glist = "-G $glist";
    }
1044 1045
    # Map the shell into a full path.
    $shell = MapShell($shell);
1046

1047
    return system("$USERMOD -s $shell -g $gid $glist -p '$pswd' $login");
1048 1049
}

1050 1051
#
# Modify user password.
1052
#
1053 1054 1055 1056 1057 1058 1059 1060
sub os_modpasswd($$)
{
    my($login, $pswd) = @_;

    if (system("$USERMOD -p '$pswd' $login") != 0) {
	warn "*** WARNING: resetting password for $login.\n";
	return -1;
    }
1061
    # don't try to reset 'toor' if it doesn't exist
1062
    if ($login eq "root" &&
1063
	system("grep -q toor $TMPASSWD") == 0 &&
1064 1065 1066 1067 1068 1069 1070
	system("$USERMOD -p '$pswd' toor") != 0) {
	warn "*** WARNING: resetting password for toor.\n";
	return -1;
    }
    return 0;
}

1071 1072
#
# Add a user.
1073
#
1074
sub os_useradd($$$$$$$$$)
1075
{
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    if (INVZVM()) {
	my $tries  = 10;
	my $result = 1;
	while ($tries-- > 0) {
	    $result = os_useradd_real(@_);
	    last
		if (!$result || !$tries);

	    warn("$USERADD returned $result ... trying again in a bit\n");
	    sleep(10);
	}
	return $result;
    }
    else {
	return os_useradd_real(@_);
1091 1092 1093 1094
    }
}

sub os_useradd_real($$$$$$$$$)
1095
{
1096
    my($login, $uid, $gid, $pswd, $glist, $homedir, $gcos, $root, $shell) = @_;
Mike Hibler's avatar
Mike Hibler committed
1097
    my $args = "";
1098 1099 1100 1101 1102

    if ($root) {
	$glist = join(',', split(/,/, $glist), "root");
    }
    if ($glist ne "") {
Mike Hibler's avatar
Mike Hibler committed
1103
	$args .= "-G $glist ";
1104
    }
Mike Hibler's avatar
Mike Hibler committed
1105 1106 1107
    # If remote, let it decide where to put the homedir.
    if (!REMOTE()) {
	$args .= "-d $homedir ";
1108

1109 1110
	# Locally, if directory exists and is populated, skip -m
	# and make sure no attempt is made to create.
1111
	if (! -d $homedir || ! -e "$homedir/.profile") {
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
	    $args .= "-m ";
	}
	else {
	    #
	    # -M is Redhat only option?  Overrides default CREATE_HOME.
	    # So we see if CREATE_HOME is set and if so, use -M.
	    #
	    if (!system("grep -q CREATE_HOME /etc/login.defs")) {
		$args .= "-M ";
	    }
Mike Hibler's avatar
Mike Hibler committed
1122
	}
1123
    }
Mike Hibler's avatar
Mike Hibler committed
1124 1125
    elsif (!PLAB()) {
	my $marg = "-m";
1126

Mike Hibler's avatar
Mike Hibler committed
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
	#
	# XXX DP hack
	# Only force creation of the homdir if the default homedir base
	# is on a local FS.  On the DP, all nodes share a homedir base
	# which is hosted on one of the nodes, so we create the homedir
	# only on that node.
	#
	$defhome = `$USERADD -D 2>/dev/null`;
	if ($defhome =~ /HOME=(.*)/) {
	    if (!os_islocaldir($1)) {
		$marg = "";
	    }
	}

	# populate on remote nodes. At some point will tar files over.
	$args .= $marg;
    }

    # Map the shell into a full path.
    $shell = MapShell($shell);
1147
    my $oldmask = umask(0022);
Mike Hibler's avatar
Mike Hibler committed
1148 1149 1150

    if (system("$USERADD -u $uid -g $gid $args -p '$pswd' ".
	       "-s $shell -c \"$gcos\" $login") != 0) {
1151
	warn "*** WARNING: $USERADD $login error.\n";
1152
	umask($oldmask);
1153 1154
	return -1;
    }
1155
    umask($oldmask);
1156 1157 1158
    return 0;
}

1159 1160 1161 1162 1163 1164 1165 1166
#
# Remove a homedir. Might someday archive and ship back.
#
sub os_homedirdel($$)
{
    return 0;
}

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
#
# Create a directory including all intermediate directories.
#
sub os_mkdir($$)
{
    my ($dir, $mode) = @_;

    if (system("$MKDIR -p -m $mode $dir")) {
	return 0;
    }
    return 1;
}

1180
#
1181 1182
# OS Dependent configuration.
#
1183 1184 1185 1186
sub os_setup()
{
    return 0;
}
1187

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
#
# OS dependent, routing-related commands
#
sub os_routing_enable_forward()
{
    my $cmd;

    $cmd = "sysctl -w net.ipv4.conf.all.forwarding=1";
    return $cmd;
}

1199
sub os_routing_enable_gated($)
1200
{
1201
    my ($conffile) = @_;
1202 1203
    my $cmd;

1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
    #
    # XXX hack to avoid gated dying with TCP/616 already in use.
    #
    # Apparently the port is used by something contacting ops's
    # portmapper (i.e., NFS mounts) and probably only happens when
    # there are a bazillion NFS mounts (i.e., an experiment in the
    # testbed project).
    #
    $cmd  = "for try in 1 2 3 4 5 6; do\n";
    $cmd .= "\tif `cat /proc/net/tcp | ".
	"grep -E -e '[0-9A-Z]{8}:0268 ' >/dev/null`; then\n";
    $cmd .= "\t\techo 'gated GII port in use, sleeping...';\n";
    $cmd .= "\t\tsleep 10;\n";
    $cmd .= "\telse\n";
    $cmd .= "\t\tbreak;\n";
    $cmd .= "\tfi\n";
    $cmd .= "    done\n";
    $cmd .= "    $GATED -f $conffile";
1222 1223 1224
    return $cmd;
}

1225
sub os_routing_add_manual($$$$$;$)
1226
{
1227
    my ($routetype, $destip, $destmask, $gate, $cost, $rtabid) = @_;
1228 1229 1230 1231 1232 1233
    my $cmd;

    if ($routetype eq "host") {
	$cmd = "$ROUTE add -host $destip gw $gate";
    } elsif ($routetype eq "net") {
	$cmd = "$ROUTE add -net $destip netmask $destmask gw $gate";
1234 1235
    } elsif ($routetype eq "default") {
	$cmd = "$ROUTE add default gw $gate";
1236 1237 1238 1239 1240 1241 1242 1243
    } else {
	warn "*** WARNING: bad routing entry type: $routetype\n";
	$cmd = "";
    }

    return $cmd;
}

1244
sub os_routing_del_manual($$$$$;$)
1245
{
1246
    my ($routetype, $destip, $destmask, $gate, $cost, $rtabid) = @_;
1247 1248 1249 1250 1251 1252
    my $cmd;

    if ($routetype eq "host") {
	$cmd = "$ROUTE delete -host $destip";
    } elsif ($routetype eq "net") {
	$cmd = "$ROUTE delete -net $destip netmask $destmask gw $gate";
1253 1254
    } elsif ($routetype eq "default") {
	$cmd = "$ROUTE delete default";
1255 1256 1257 1258 1259 1260 1261 1262
    } else {
	warn "*** WARNING: bad routing entry type: $routetype\n";
	$cmd = "";
    }

    return $cmd;
}

1263 1264 1265 1266 1267 1268 1269 1270 1271
# Map a shell name to a full path using /etc/shells
sub MapShell($)
{
   my ($shell) = @_;

   if ($shell eq "") {
       return $DEFSHELL;
   }

1272 1273 1274 1275 1276
   #
   # May be multiple lines (e.g., /bin/sh, /usr/bin/sh, etc.) in /etc/shells.
   # Just use the first entry.
   #
   my @paths = `grep '/${shell}\$' $SHELLS`;
1277 1278 1279
   if ($?) {
       return $DEFSHELL;
   }
1280 1281
   my $fullpath = $paths[0];
   chomp($fullpath);
1282

1283 1284
   # Sanity Checks
   if ($fullpath =~ /^([-\w\/]*)$/ && -x $fullpath) {
1285 1286 1287 1288 1289 1290 1291 1292
       $fullpath = $1;
   }
   else {
       $fullpath = $DEFSHELL;
   }
   return $fullpath;
}

1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
sub os_samefs($$)
{
    my ($d1,$d2) = @_;

    my $d1dev = `stat -c '%d' $d1`;
    chomp($d1dev) if ($? == 0);
    my $d2dev = `stat -c '%d' $d2`;
    chomp($d2dev) if ($? == 0);

    return ($d1dev && $d2dev && $d1dev == $d2dev) ? 1 : 0;
}

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
#
# Some environments do not give us a valid / mount (like Docker); thus,
# df -l does not work.  Thus we must rely on /proc/mounts to tell us if
# a dir is local or not.  Well, ok, /proc/mounts is hard (and potential
# bind mount chains would make it harder).  So instead, we assume that /
# is local, (well, we check to ensure it is not NFS in /proc/mounts),
# and use os_samefs above to ensure that $dir is on the same device as
# /.  If that is true, that is good enough to call it a local dir.
#
# We are *very* careful in this function.  If df -l / actually returns
# something, we bail out, since if df -l returns a local fs in that
# case, this function should not be used!
#
sub os_islocaldir_alt($)
{
    my ($dir,) = @_;

    my %mounttypes = ();
    my %mountdevs = ();
    open(FD,"/proc/mounts");
    if ($?) {
	warn "*** alt_os_is_localdir: could not open /proc/mounts; aborting!\n";
	return -1;
    }
    my @lines = <FD>;
    close(FD);
    foreach my $line (@lines) {
	chomp($line);
	if ($line =~ /^([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+.*$/) {
	    $mounttypes{$2} = $3;
	    $mountdevs{$2} = $1;
	}
    }

    if (exists($mounttypes{"/"}) && $mounttypes{"/"} =~ /nfs/i) {
	warn "*** os_islocaldir_alt: / appears to be NFS; not safe to use this!";
	return -1;
    }

    return os_samefs("/",$dir);
}

Mike Hibler's avatar
Mike Hibler committed
1347 1348 1349 1350
# Return non-zero if given directory is on a "local" filesystem
sub os_islocaldir($)
{
    my ($dir) = @_;
1351
    my $rv = 0;
Mike Hibler's avatar
Mike Hibler committed
1352

1353 1354 1355 1356 1357 1358 1359 1360 1361
    if (INDOCKERVM()) {
	$rv = os_islocaldir_alt($dir);
	return $rv
	    if ($rv >= 0);
	# Otherwise ($rv == -1), we fall back to the old way, which will
	# not fail us (might be wrong, but it will be a false positive,
	# so we won't remove a remote dir or anything).
    }

Mike Hibler's avatar
Mike Hibler committed
1362 1363 1364 1365
    my @dfoutput = `$DF -l $dir 2>/dev/null`;
    if (grep(!/^filesystem/i, @dfoutput) > 0) {
	$rv = 1;
    }
1366 1367 1368 1369 1370 1371 1372 1373 1374

    #
    # XXX hack for NFS-based MFS. We treat it as a local directory
    # if it is on the same FS as /.
    #
    if ($rv == 0 && libsetup::MFS() && os_samefs("/", $dir)) {
	$rv = 1;
    }

Mike Hibler's avatar
Mike Hibler committed
1375 1376 1377
    return $rv;
}

1378 1379 1380 1381 1382 1383
sub os_getnfsmounts($)
{
    my ($rptr) = @_;
    my %mounted = ();

    #
1384
    # Grab the output of the mount command and parse.
1385 1386 1387 1388 1389 1390 1391 1392 1393
    #
    if (! open(MOUNT, "/bin/mount|")) {
	print "os_getnfsmounts: Cannot run mount command\n";
	return -1;
    }
    while (<MOUNT>) {
	if ($_ =~ /^([-\w\.\/:\(\)]+) on ([-\w\.\/]+) type (\w+) .*$/) {
	    # Check type for nfs string.
	    if ($3 eq "nfs") {
1394
		# Key is the remote NFS path, value is the mount point path.
1395 1396 1397 1398 1399 1400 1401 1402 1403
		$mounted{$1} = $2;
	    }
	}
    }
    close(MOUNT);
    %$rptr = %mounted;
    return 0;
}

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
sub os_fwconfig_line($@) {
	my ($fwinfo, @fwrules) = @_;
	my ($upline, $downline);
	my $pdev;
	my $vlandev;
	my $myip;
	my $mymask;

	$myip = `cat $BOOTDIR/myip`;
	chomp($myip);
	$mymask = `cat $BOOTDIR/mynetmask`;
	chomp($mymask);

1417 1418 1419
	if ($fwinfo->{TYPE} ne "iptables" &&
	    $fwinfo->{TYPE} ne "iptables-vlan" &&
	    $fwinfo->{TYPE} ne "iptables-dom0") {
1420 1421 1422
		warn "*** WARNING: unsupported firewall type '", $fwinfo->{TYPE}, "'\n";
		return ("false", "false");
	}
1423

1424 1425 1426 1427
	# XXX debugging
	my $logaccept = defined($fwinfo->{LOGACCEPT}) ? $fwinfo->{LOGACCEPT} : 0;
	my $logreject = defined($fwinfo->{LOGREJECT}) ? $fwinfo->{LOGREJECT} : 0;
	my $dotcpdump = defined($fwinfo->{LOGTCPDUMP}) ? $fwinfo->{LOGTCPDUMP} : 0;
1428

1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
	#
	# Convert MAC info to a useable form and filter out the firewall itself
	#
	my $href = $fwinfo->{MACS};
	while (my ($node,$mac) = each(%$href)) {
		if ($mac eq $fwinfo->{OUT_IF}) {
			delete($$href{$node});
		} elsif ($mac =~ /^(\w{2})(\w{2})(\w{2})(\w{2})(\w{2})(\w{2})$/) {
			$$href{$node} = "$1:$2:$3:$4:$5:$6";
		} else {
			warn "*** WARNING: Bad MAC returned for $node in fwinfo: $mac\n";
			return ("false", "false");
		}
	}
	$href = $fwinfo->{SRVMACS};
	while (my ($node,$mac) = each(%$href)) {
		if ($mac eq $fwinfo->{OUT_IF}) {
			delete($$href{$node});
		} elsif ($mac =~ /^(\w{2})(\w{2})(\w{2})(\w{2})(\w{2})(\w{2})$/) {
			$$href{$node} = "$1:$2:$3:$4:$5:$6";
		} else {
			warn "*** WARNING: Bad MAC returned for $node in fwinfo: $mac\n";
			return ("false", "false");
		}
	}
1454

1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
	#
	# VLAN enforced layer2 firewall with Linux iptables
	#
	if ($fwinfo->{TYPE} eq "iptables-vlan") {
		if (!defined($fwinfo->{IN_VLAN})) {
			warn "*** WARNING: no VLAN for iptables-vlan firewall, NOT SETUP!\n";
			return ("false", "false");
		}
	
		$pdev    = `$BINDIR/findif $fwinfo->{IN_IF}`;
		chomp($pdev);
		my $vlanno  = $fwinfo->{IN_VLAN};
		$vlandev = $pdev . '.' . $vlanno;

		$upline  = "modprobe 8021q\n";
		$upline .= "vconfig add $pdev $vlanno > /dev/null\n";
		$upline .= "ifconfig $vlandev up\n";
		$upline .= "brctl addbr br0\n";
1473
		$upline .= "brctl stp br0 on\n";
1474
		$upline .= "ifconfig br0 up\n";
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
		#
		# This is very, very messy.  We have to save the
		# existing routes for $pdev, but in an order that they
		# can be restored without failing, before we move
		# $pdev into br0.  Then the restored routes must be
		# rewritten in terms of br0 instead of $pdev.
		#
		# Finally, we have to collect these routes prior to 1)
		# assigning $pdev's IP to br0, and 2) moving $pdev
		# into br0, and 3) prior to *deleting* any routes.
		# All these conditions seem necessary to me.
		#
		# ip route show does not necessarily display routes in
		# restoreable order.  In particular, the thing that
		# bites is that the default route is (now, as of
		# Ubuntu16, at least) displayed *prior to* the scope
		# link (broadcast route) for a device).  So, we first
		# harvest the scope link routes for $pdev (i.e., the
		# natural ones that come into being as a side affect
		# of assiging an IP address to a link); then we
		# harvest all other routes associated with $pdev; then
		# we remove all routes associated with $pdev.  Then we
		# do the mucking about with bridge membership and
		# transfer IP from $pdev to bridge, and finally,
		# restore the routes we saved (modified to br0, of
		# course).
		#
		$upline .= "ROUTECMDS=\$(ip route show scope link | while read line; do\n";
		$upline .= "    echo \$line | grep 'dev $pdev' > /dev/null || continue\n";
		$upline .= "    echo 'ip route add '`echo \$line | sed s/$pdev/br0/`\n";
		$upline .= "done)\n";
		$upline .= "ROUTECMDS=\"\$ROUTECMDS\\n\"\$(ip route show | while read line; do\n";
		$upline .= "    echo \$line | grep 'dev $pdev' > /dev/null || continue\n";
		$upline .= "    echo \$line | grep 'scope link' > /dev/null && continue\n";
		$upline .= "    echo 'ip route add '`echo \$line | sed s/$pdev/br0/`\n";
		$upline .= "done)\n";
1511 1512 1513 1514
		$upline .= "ip route show | while read line; do\n";
		$upline .= "    echo \$line | grep 'dev $pdev' > /dev/null || continue\n";
		$upline .= "    ip route del \$line\n";
		$upline .= "done\n";
1515 1516 1517 1518
		$upline .= "brctl addif br0 $pdev\n";
		$upline .= "brctl addif br0 $vlandev\n";
		$upline .= "ifconfig br0 $myip netmask $mymask\n";
		$upline .= "ip route flush dev br0\n";
1519
		$upline .= "ifconfig $pdev 0.0.0.0\n";
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
		$upline .= "/bin/echo -e \"\$ROUTECMDS\" | sh\n";

		$downline .= "ROUTECMDS=\$(ip route show scope link | while read line; do\n";
		$downline .= "    echo \$line | grep 'dev br0' > /dev/null || continue\n";
		$downline .= "    echo 'ip route add '`echo \$line | sed s/br0/$pdev/`\n";
		$downline .= "done)\n";
		$downline .= "ROUTECMDS=\"\$ROUTECMDS\\n\"\$(ip route show | while read line; do\n";
		$downline .= "    echo \$line | grep 'dev br0' > /dev/null || continue\n";
		$downline .= "    echo \$line | grep 'scope link' > /dev/null && continue\n";
		$downline .= "    echo 'ip route add '`echo \$line | sed s/br0/$pdev/`\n";
		$downline .= "done)\n";
		$downline .= "ip route show | while read line; do\n";
		$downline .= "    echo \$line | grep 'dev br0' > /dev/null || continue\n";
		$downline .= "    ip route del \$line\n";
		$downline .= "done\n";
1535 1536 1537
		$downline .= "    ifconfig $pdev $myip netmask $mymask\n";
		$downline .= "    ip route flush dev $pdev\n";
		$downline .= "    ip route flush dev br0\n";
1538
		$downline .= "/bin/echo -e \"\$ROUTECMDS\" | sh\n";
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
		$downline .= "    ifconfig br0 down\n";
		$downline .= "    ifconfig $vlandev down\n";
		$downline .= "    brctl delif br0 $vlandev\n";
		$downline .= "    brctl delif br0 $pdev\n";
		$downline .= "    brctl delbr br0\n";
		$downline .= "    vconfig rem $vlandev > /dev/null\n";

		#
		# Setup proxy ARP entries.
		#
1549
		if (defined($fwinfo->{MACS}) || defined($fwinfo->{PUBLICADDRS})) {
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
			$upline .= "ebtables -t nat -F PREROUTING\n";
			# publish servers (including GW) on inside and for us on outside
			if (defined($fwinfo->{SRVMACS})) {
				my $href = $fwinfo->{SRVMACS};
				while (my ($ip,$mac) = each %$href) {
					$upline .= "ebtables -t nat -A PREROUTING -i $vlandev " .
					  "-p ARP --arp-opcode Request " .
					    "--arp-ip-dst $ip -j arpreply " .
					      "--arpreply-mac $mac\n";
				}
			}

			# provide node MACs to outside
1563 1564 1565
			if (defined($fwinfo->{MACS})) {
			    my $href = $fwinfo->{MACS};
			    while (my ($node,$mac) = each %$href) {
1566 1567 1568 1569 1570
				my $ip = $fwinfo->{IPS}{$node};
				$upline .= "ebtables -t nat -A PREROUTING -i $pdev " .
				  "-p ARP --arp-opcode Request " .
				    "--arp-ip-dst $ip -j arpreply " .
				      "--arpreply-mac $mac\n";
1571 1572
			    }
		        }
1573 1574 1575 1576

			$upline .= "ebtables -t nat -A PREROUTING -p ARP " .
			  "--arp-ip-dst $myip -j ACCEPT\n";

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
			#
			# Enable proxy arp for PUBLICADDRS, but only
			# allow requests/replies for them.  This allows
			# the PUBLICADDRS to be used by any physical
			# node in the expt, which is what we want by
			# default.
			#
			if (defined($fwinfo->{PUBLICADDRS})) {
			    $upline .= "echo 1 > /proc/sys/net/ipv4/conf/br0/proxy_arp\n";
			    foreach my $pip (@{$fwinfo->{PUBLICADDRS}}) {
				$upline .= "ip ro add $pip/32 dev br0\n";
				$upline .= "ebtables -t nat -A PREROUTING " .
				    "-i $pdev -p ARP --arp-opcode Request " .
				    "--arp-ip-dst $pip -j ACCEPT\n";
				$upline .= "ebtables -t nat -A PREROUTING " .
				    "-i $vlandev -p ARP --arp-opcode Reply " .
				    "--arp-ip-src $pip -j ACCEPT\n";
				$downline .= "ip ro del $pip/32 dev br0\n";
			    }
			    $downline .= "echo 0 > /proc/sys/net/ipv4/conf/br0/proxy_arp\n";
			}

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
			$upline .= "ebtables -t nat -A PREROUTING -p ARP -j DROP\n";

			if ($dotcpdump) {
				$upline .= "    tcpdump -i $vlandev ".
				  "-w $LOGDIR/in.tcpdump >/dev/null 2>&1 &\n";
				$upline .= "    tcpdump -i $pdev ".
				  "-w $LOGDIR/out.tcpdump not vlan >/dev/null 2>&1 &\n";
				$downline .= "    killall tcpdump >/dev/null 2>&1\n";
			}
		
		}

		# XXX HACK ALERT
		# The rules may contain hostnames which iptables will try to resolve.
		# Normally this isn't a problem, but if we've set up a bridge device
		# it may take a bit before the bridge starts letting packets through
		# again.
		$upline .= "sleep 30\n";

	} else {
1619 1620 1621 1622
		if ($fwinfo->{TYPE} ne "iptables-dom0") {
		    $upline .= "sysctl -w net.ipv4.ip_forward=1\n";
		    $downline .= "sysctl -w net.ipv4.ip_forward=0\n";
		}
1623 1624
	}

1625 1626 1627
	# Sort the rules by provided rule number (tmcd doesn't order them).
	@fwrules = sort { $a->{RULENO} <=> $b->{RULENO}} @fwrules;

1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
	# XXX This is ugly.  Older version of iptables can't handle source or
	# destination hosts or nets in the format a,b,c,d.  Newer versions of
	# iptables automatically expand this to separate rules for each host/net,
	# so we need to do the same thing here.  Since a rule could contain
	# multiple sources and multiple dests, we expand each separately.
	my @new_rules;
	foreach my $rule (@fwrules) {
		$rulestr = $rule->{RULE};
		if ($rulestr =~ /^(.+)\s+(-s|--source)\s+([\S]+)(.+)/) {
			push @new_rules, "$1 $2 $_ $4" for split(/,/, $3);
		} else {
			push @new_rules, $rulestr;
		}
	} 

	@fwrules = ();
	foreach my $rulestr (@new_rules) {
		if ($rulestr =~ /^(.+)\s+(-d|--destination)\s+([\S]+)(.+)/) {
			push @fwrules, "$1 $2 $_ $4" for split(/,/, $3);
		} else {
			push @fwrules, $rulestr;
		}
	}

	@new_rules = ();
	foreach my $rulestr (@fwrules) {
		$rulestr =~ s/pdev/$pdev/g;
		$rulestr =~ s/vlandev/$vlandev/g;
		$rulestr =~ s/\s+me\s+/ $myip /g;

		# Ugh. iptables wants port ranges in the form a:b, but
		# our firewall variable expansion can contain a-b.  Try
		# to fix it.
		$rulestr =~ s/\s+--dport\s+(\S+)-(\S+)/ --dport $1:$2/;
		$rulestr =~ s/\s+--sport\s+(\S+)-(\S+)/ --sport $1:$2/;
		
		if ($logaccept && $rulestr =~ /-j ACCEPT$/) {
			if ($rulestr =~ /^iptables\s+/) {
				push @new_rules, $rulestr;
				$rulestr =~ s/ACCEPT$/LOG/;
			} elsif ($rulestr =~ /^ebtables\s+/) {
				$rulestr =~ s/ACCEPT$/--log -j ACCEPT/;
			}
			push @new_rules, $rulestr;
		} elsif ($logreject && $rulestr =~ /-j (DENY|DROP)$/) {
			my $action = $1;
			if ($rulestr =~ /^iptables\s+/) {
				push @new_rules, $rulestr;
				$rulestr =~ s/$action$/LOG/;
			} elsif ($rulestr =~ /^ebtables\s+/) {
				$rulestr =~ s/$action$/--log -j $action/;
			}
			push @new_rules, $rulestr;
		} else {
			push @new_rules, $rulestr;
		}
	}
	@fwrules = @new_rules;

1687 1688 1689 1690
	#
	# For now, if a rule fails to load we fail partially open.
	# We allow all access to the FW itself but nothing inside.
	#
1691 1692 1693 1694 1695
	foreach my $rulestr (@fwrules) {
		if ($rulestr =~ /^iptables\s+/) {
			$upline .= "    $rulestr || {\n";
			$upline .= "        echo 'WARNING: could not load iptables rule:'\n";
			$upline .= "        echo '  $rulestr'\n";
1696 1697
			$upline .= "        iptables -F\n"
			    if ($fwinfo->{TYPE} ne "iptables-dom0");
1698
			$upline .= "        iptables -P FORWARD DROP\n";
1699 1700
			$upline .= "        iptables -P INPUT ACCEPT\n";
			$upline .= "        iptables -P OUTPUT ACCEPT\n";
1701 1702 1703 1704 1705 1706
			$upline .= "        exit 1\n";
			$upline .= "    }\n";
		} elsif ($rulestr =~ /^ebtables\s+/) {
			$upline .= "    $rulestr || {\n";
			$upline .= "        echo 'WARNING: could not load ebtables rule:'\n";
			$upline .= "        echo '  $rulestr'\n";
1707 1708
			$upline .= "        ebtables -F\n"
			    if ($fwinfo->{TYPE} ne "iptables-dom0");
1709
			$upline .= "        ebtables -P FORWARD DROP\n";
1710 1711
			$upline .= "        ebtables -P INPUT ACCEPT\n";
			$upline .= "        ebtables -P OUTPUT ACCEPT\n";
1712 1713 1714 1715 1716 1717
			$upline .=