liblocsetup.pm 69.1 KB
Newer Older
1
#!/usr/bin/perl -wT
Leigh Stoller's avatar
Leigh Stoller committed
2
#
3
# Copyright (c) 2000-2016 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

79 80
#
# Various programs and things specific to Linux and that we want to export.
81
#
82
$CP		= "/bin/cp";
Mike Hibler's avatar
Mike Hibler committed
83
$DF		= "/bin/df";
84
$EGREP		= "/bin/egrep -q";
85 86 87
# 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!
88
$NFSMOUNT	= "/bin/mount -o nolock,udp";
89
$LOOPBACKMOUNT	= "/bin/mount -n -o bind ";
90
$UMOUNT		= "/bin/umount";
91
$MOUNT		= "/bin/mount";
92
$TMPASSWD	= "$ETCDIR/passwd";
93 94 95
$TMGROUP	= "$ETCDIR/group";
$TMSHADOW       = "$ETCDIR/shadow";
$TMGSHADOW      = "$ETCDIR/gshadow";
96 97
$SFSSD		= "/usr/local/sbin/sfssd";
$SFSCD		= "/usr/local/sbin/sfscd";
98
$RPMCMD		= "/bin/rpm";
99
$HOSTSFILE	= "/etc/hosts";
100
$WGET		= "/usr/bin/wget";
101
$CHMOD		= "/bin/chmod";
102
$ARP		= "/sbin/arp";
103 104 105 106

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

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

144 145
my $debug = 0;

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

157 158 159
    #
    # 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
160
    # files and their shadow counterparts, remove any emulab u/gids from the
161 162 163 164 165
    # 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 (!).
    #
166 167 168 169 170 171 172 173
    # 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.
    #
174 175 176
    my %PDB;
    my %GDB;

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

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

188 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
    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;
	}
    }

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

228 229
    # remove emulab groups first (save a bit of work):
    while (my ($group,$gid) = each(%GDB)) {
230 231
	print "DEBUG: $group/$gid\n"
	    if ($debug);
232 233 234 235 236
	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};
237 238
		print "DEBUG: deleted group $group from $file\n"
		    if ($debug);
239 240 241 242 243 244 245 246 247 248 249 250
	    }
	}
    }

    # 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};
251 252
		print "DEBUG: deleted user  $user from $file\n"
		    if ($debug);
253 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
	    }
	}

	# 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;
	    }
	}
286
    }
287 288 289 290 291 292 293 294 295 296

    # 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}})) {
	    # skip root and toor!
297
	    next
298 299 300 301 302 303
		if ($ent eq 'root' || $ent eq 'toor');

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

	# 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};
	}
331
    }
332

333
    # now write the masters to .new files so we can diff, do the diff for
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    # 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) {
356 357 358 359 360 361 362 363 364 365 366
		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");
367 368 369 370 371 372
	    }
	}
	else {
	    print STDERR "Running 'diff -q -u $file ${file}.new'\n";
	    $retval = system("diff -q -u $file ${file}.new");
	    if ($retval) {
373 374 375 376 377 378 379 380 381 382 383
		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");
384 385 386 387 388 389 390
	    }
	}
    }

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

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    #
    # 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;
    }

407 408 409 410 411 412 413
    return 0;
}

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

421 422 423 424 425 426 427 428 429 430 431
    #
    # 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);
    }

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

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

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

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

465 466 467 468
	#
	# At the moment, we expect just the various flavors of 80211, and
	# we treat them all the same, configuring with iwconfig and iwpriv.
	#
469 470 471
	my $iwcmd = "/usr/local/sbin/iwconfig $athiface ";
        my $wlccmd = "/usr/local/bin/wlanconfig $athiface create ".
            "wlandev $iface ";
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 500 501 502

	#
	# 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";
	}
503
	# Allow this too.
504 505 506 507 508 509 510 511 512 513
	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'};
514 515 516 517
	}

	#
	# We demand to be told if we are the master or a peon.
518 519 520 521 522 523
	# 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.
524
	#
525 526
	# This needs to be last for some reason.
	#
527 528 529
	if (exists($settings->{'accesspoint'})) {
	    my $accesspoint = $settings->{"accesspoint"};
	    my $accesspointwdots;
530

531 532 533 534 535 536 537 538 539 540 541 542 543 544
	    # 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;
	    }
545

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

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

595 596 597 598 599
    #
    # GNU Radio network interface on the flex900 daugherboard
    #
    if ($iface_type eq "flex900" && defined($settings)) {

600
        my $tuncmd =
601 602 603 604 605 606 607 608 609 610 611
            "/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"};

612
        if (!exists($settings->{"protocol"}) ||
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
            $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";

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

642 643 644 645 646 647 648 649
        $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);
    }

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

712
        #
Mike Hibler's avatar
Mike Hibler committed
713 714 715 716 717
        # 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!
718 719 720 721 722 723 724 725 726
        #
	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
727
	    $uplines =
728
		"if $ethtool $iface >/dev/null 2>&1; then\n    ";
729 730 731 732 733 734 735 736 737 738 739 740
	    #
	    # 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    ";
741 742 743 744
	    }
	    else {
		$uplines .=
		    "  $ethtool -s $iface autoneg off speed $speed duplex $duplex\n    " .
Mike Hibler's avatar
Mike Hibler committed
745
		    "  sleep 2 # needed due to likely bug in e100 driver on pc850s\n    ";
746 747
	    }
	    $uplines .= 
748 749 750 751 752 753
		"else\n    " .
		"  /sbin/mii-tool --force=$media $iface\n    " .
		"fi\n    ";
	} else {
	    $uplines = "/sbin/mii-tool --force=$media $iface\n    ";
	}
754 755
    }

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

764
    return ($uplines, $downlines);
765 766
}

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

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

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 821 822 823
    #
    # 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";
	    }
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 869 870 871
	    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);
    }

872 873 874 875
    #
    # IP aliases
    #
    if ($itype eq "alias") {
876 877
	$uplines = "$IPBIN addr add $inet/$mask dev $iface";
	$downlines = "$IPBIN addr del $inet/$mask dev $iface";
878 879 880 881 882 883 884 885 886
	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)
887
    #	vconfig add eth0 601
888 889 890 891 892 893 894 895 896 897 898
    #   ifconfig vlan601 inet ...
    #
    #   ifconfig vlan601 down
    #	vconfig rem vlan601
    #
    if ($itype eq "vlan") {
	if (!defined($vtag)) {
	    warn("No vtag in veth config\n");
	    return "";
	}

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

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

	my $vdev = "vlan$vtag";

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

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

    return ($uplines, $downlines);
934 935
}

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
#
# 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>
958
    # veth:  veth<ID>
959 960 961 962 963 964
    #
    my $itype = $ifconfig->{"ITYPE"};
    if ($itype eq "alias") {
	return $piface;
    } elsif ($itype eq "vlan") {
	return $itype . $ifconfig->{"VTAG"};
965 966
    } elsif ($itype eq "veth") {
	return $itype . $ifconfig->{"ID"};
967 968 969 970 971 972
    }

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

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

981
    return sprintf("%s\t%s %s", $ip, $name, $aliases);
982 983 984 985
}

#
# Add a new group
986
#
987
sub os_groupadd($$)
988
{
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    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(@_);
1004 1005 1006 1007
    }
}

sub os_groupadd_real($$)
1008
{
1009
    my ($group, $gid) = @_;
1010 1011 1012 1013

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

1014 1015
#
# Delete an old group
1016
#
1017 1018 1019 1020 1021 1022 1023
sub os_groupdel($)
{
    my($group) = @_;

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

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

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

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

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

1050
    return system("$USERMOD -s $shell -g $gid $glist -p '$pswd' $login");
1051 1052
}

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

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

1074 1075
#
# Add a user.
1076
#
1077
sub os_useradd($$$$$$$$$)
1078
{
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
    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(@_);
1094 1095 1096 1097
    }
}

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

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

1112 1113
	# Locally, if directory exists and is populated, skip -m
	# and make sure no attempt is made to create.
1114
	if (! -d $homedir || ! -e "$homedir/.profile") {
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
	    $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
1125
	}
1126
    }
Mike Hibler's avatar
Mike Hibler committed
1127 1128
    elsif (!PLAB()) {
	my $marg = "-m";
1129

Mike Hibler's avatar
Mike Hibler committed
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
	#
	# 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);
1150
    my $oldmask = umask(0022);
Mike Hibler's avatar
Mike Hibler committed
1151 1152 1153

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

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

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

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

1183
#
1184 1185
# OS Dependent configuration.
#
1186 1187 1188 1189
sub os_setup()
{
    return 0;
}
1190

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

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

1202
sub os_routing_enable_gated($)
1203
{
1204
    my ($conffile) = @_;
1205 1206
    my $cmd;

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
    #
    # 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";
1225 1226 1227
    return $cmd;
}

1228
sub os_routing_add_manual($$$$$;$)
1229
{
1230
    my ($routetype, $destip, $destmask, $gate, $cost, $rtabid) = @_;
1231 1232 1233 1234 1235 1236
    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";
1237 1238
    } elsif ($routetype eq "default") {
	$cmd = "$ROUTE add default gw $gate";
1239 1240 1241 1242 1243 1244 1245 1246
    } else {
	warn "*** WARNING: bad routing entry type: $routetype\n";
	$cmd = "";
    }

    return $cmd;
}

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

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

    return $cmd;
}

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

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

1275 1276 1277 1278 1279
   #
   # 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`;
1280 1281 1282
   if ($?) {
       return $DEFSHELL;
   }
1283 1284
   my $fullpath = $paths[0];
   chomp($fullpath);
1285

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

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
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;
}

Mike Hibler's avatar
Mike Hibler committed
1308 1309 1310 1311
# Return non-zero if given directory is on a "local" filesystem
sub os_islocaldir($)
{
    my ($dir) = @_;
1312
    my $rv = 0;
Mike Hibler's avatar
Mike Hibler committed
1313 1314 1315 1316 1317

    my @dfoutput = `$DF -l $dir 2>/dev/null`;
    if (grep(!/^filesystem/i, @dfoutput) > 0) {
	$rv = 1;
    }
1318 1319 1320 1321 1322 1323 1324 1325 1326

    #
    # 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
1327 1328 1329
    return $rv;
}

1330 1331 1332 1333 1334 1335
sub os_getnfsmounts($)
{
    my ($rptr) = @_;
    my %mounted = ();

    #
1336
    # Grab the output of the mount command and parse.
1337 1338 1339 1340 1341 1342 1343 1344 1345
    #
    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") {
1346
		# Key is the remote NFS path, value is the mount point path.
1347 1348 1349 1350 1351 1352 1353 1354 1355
		$mounted{$1} = $2;
	    }
	}
    }
    close(MOUNT);
    %$rptr = %mounted;
    return 0;
}

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
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);

1369 1370 1371
	if ($fwinfo->{TYPE} ne "iptables" &&
	    $fwinfo->{TYPE} ne "iptables-vlan" &&
	    $fwinfo->{TYPE} ne "iptables-dom0") {
1372 1373 1374
		warn "*** WARNING: unsupported firewall type '", $fwinfo->{TYPE}, "'\n";
		return ("false", "false");
	}
1375

1376 1377 1378 1379
	# 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;
1380

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
	#
	# 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");
		}
	}
1406

1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
	#
	# 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";
1425
		$upline .= "brctl stp br0 on\n";
1426 1427 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 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 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
		$upline .= "ifconfig br0 up\n";
		$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";
		$upline .= "ip route show | while read line; do\n";
		$upline .= "    echo \$line | grep 'dev $pdev' > /dev/null || continue\n";
		$upline .= "    new_route=`echo \$line | sed s/$pdev/br0/`\n";
		$upline .= "    ip route del \$line\n";
		$upline .= "    ip route add \$new_route\n";
		$upline .= "done\n";
		$upline .= "ifconfig $pdev 0.0.0.0\n";

		$downline .= "    ifconfig $pdev $myip netmask $mymask\n";
		$downline .= "    ip route flush dev $pdev\n";
		$downline .= "    ip route show | while read line; do\n";
		$downline .= "        echo \$line | grep 'dev br0' > /dev/null || continue\n";
		$downline .= "        new_route=`echo \$line | sed s/br0/$pdev/`\n";
		$downline .= "        ip route del \$line\n";
		$downline .= "        ip route add \$new_route\n";
		$downline .= "    done\n";
		$downline .= "    ip route flush dev br0\n";
		$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.
		#
		if (defined($fwinfo->{MACS})) {
			$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
			my $href = $fwinfo->{MACS};
			while (my ($node,$mac) = each %$href) {
				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";
			}

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

			$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 {
1505 1506 1507 1508
		if ($fwinfo->{TYPE} ne "iptables-dom0") {
		    $upline .= "sysctl -w net.ipv4.ip_forward=1\n";
		    $downline .= "sysctl -w net.ipv4.ip_forward=0\n";
		}
1509 1510
	}

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

1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
	# 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;

1573 1574 1575 1576
	#
	# For now, if a rule fails to load we fail partially open.
	# We allow all access to the FW itself but nothing inside.
	#
1577 1578 1579 1580 1581
	foreach my $rulestr (@fwrules) {
		if ($rulestr =~ /^iptables\s+/) {
			$upline .= "    $rulestr || {\n";
			$upline .= "        echo 'WARNING: could not load iptables rule:'\n";
			$upline .= "        echo '  $rulestr'\n";
1582 1583
			$upline .= "        iptables -F\n"
			    if ($fwinfo->{TYPE} ne "iptables-dom0");
1584
			$upline .= "        iptables -P FORWARD DROP\n";
1585 1586
			$upline .= "        iptables -P INPUT ACCEPT\n";
			$upline .= "        iptables -P OUTPUT ACCEPT\n";
1587 1588 1589 1590 1591 1592
			$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";
1593 1594
			$upline .= "        ebtables -F\n"
			    if ($fwinfo->{TYPE} ne "iptables-dom0");
1595
			$upline .= "        ebtables -P FORWARD DROP\n";
1596 1597
			$upline .= "        ebtables -P INPUT ACCEPT\n";
			$upline .= "        ebtables -P OUTPUT ACCEPT\n";
1598 1599 1600 1601 1602 1603
			$upline .= "        exit 1\n";
			$upline .= "    }\n";
		}

	}

1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
	#
	# In dom0, we cannot just flush the entire rule set, as below.
	#
	if ($fwinfo->{TYPE} eq "iptables-dom0") {
	        $downline .= "   iptables -P INPUT ACCEPT\n";
		$downline .= "   iptables -P OUTPUT ACCEPT\n";
	        $downline .=
		    "   iptables -F INPUT > /dev/null 2>&1 || true\n";
	        $downline .=
		    "   iptables -F OUTPUT > /dev/null 2>&1 || true\n";
	}

1616 1617 1618 1619 1620 1621
	# This is a brute-force way to flush all ebtables and iptables
	# rules, delete all custom chains, and restore all built-in
	# chains to their default policies.  This will produce errors
	# since not all tables exist for both tools, and not every
	# chain exists for all tables, so all output is sent to /dev/null.
	for my $table (qw/filter nat mangle raw broute/) {
1622 1623 1624 1625 1626 1627
		if ($fwinfo->{TYPE} ne "iptables-dom0") {
		    $downline .=
			"   iptables -t $table -F > /dev/null 2>&1 || true\n";
		    $downline .=
			"   iptables -t $table -X > /dev/null 2>&1 || true\n";
		}
1628 1629 1630 1631 1632
		$downline .=
		  "   ebtables -t $table -F > /dev/null 2>&1 || true\n";
		$downline .=
		  "   ebtables -t $table -X > /dev/null 2>&1 || true\n";
		for my $chain (qw/INPUT OUTPUT FORWARD PREROUTING POSTROUTING BROUTING/) {
1633 1634 1635 1636
		        if ($fwinfo->{TYPE} ne "iptables-dom0") {
			    $downline .=
				"   iptables -t $table -P $chain ACCEPT > /dev/null 2>&1 || true\n";
			}
1637 1638 1639 1640 1641 1642
			$downline .=
			  "   ebtables -t $table -P $chain ACCEPT > /dev/null 2>&1 || true\n";
		}
	}
	
	return ($upline, $downline);
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
}

sub os_fwrouteconfig_line($$$)
{
    my ($orouter, $fwrouter, $routestr) = @_;
    my ($upline, $downline);

    #
    # XXX assume the original default route should be used to reach servers.
    #
    # For setting up the firewall, this means we create explicit routes for
    # each host via the original default route.
    #
    # For tearing down the firewall, we just remove the explicit routes
    # and let them fall back on the now re-established original default route.
    #
    $upline  = "for vir in $routestr; do\n";
    $upline .= "        $ROUTE delete \$vir >/dev/null 2>&1\n";
    $upline .= "        $ROUTE add -host \$vir gw $orouter || {\n";
    $upline .= "            echo \"Could not establish route for \$vir\"\n";
    $upline .= "            exit 1\n";
    $upline .= "        }\n";
    $upline .= "    done";

    $downline  = "for vir in $routestr; do\n";
    $downline .= "        $ROUTE delete \$vir >/dev/null 2>&1\n";
    $downline .= "    done";

    return ($upline, $downline);
}

1674 1675 1676 1677
# proto for a function used in os_ifdynconfig_cmds
sub getCurrentIwconfig($;$);

#
1678
# Returns a list of commands needed to change the current device state to
1679 1680
# something matching the given configuration options.
#
1681
sub os_ifdynconfig_cmds($$$$$)
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
{
    my ($ret_aref,$iface,$action,$optref,$ifcfg) = @_;
    my %opts = %$optref;
    my %flags = ();
    # this is the hash returned from getifconfig, but only for this interface
    my %emifc = %$ifcfg;

    my @cmds = ();

    # only handle the atheros case for now, since it's the only one
    # that can be significantly parameterized
    if (exists($emifc{'TYPE'}) && $emifc{'TYPE'} eq 'ath') {
	my ($ifnum) = $iface =~ /wifi(\d+)/;
        my $ath = "ath${ifnum}";
	my $wifi = $iface;

	# check flags
	my ($reset_wlan,$reset_kmod,$remember) = (0,0,0);
	if (exists($opts{'resetkmod'}) && $opts{'resetkmod'} == 1) {
	    $reset_kmod = 1;
	    # note that this forces a wlan reset too!
	    $reset_wlan = 1;
	    delete $opts{'resetkmod'};
	}
	if (exists($flags{'resetwlan'}) && $opts{'resetwlan'} == 1) {
	    $reset_wlan = 1;
	    delete $opts{'resetwlan'};
	}
	# we only want to try to keep similar config options
	# if the user tells us to...
	if (exists($flags{'usecurrent'}) && $opts{'usecurrent'} == 1) {
	    $remember = 1;
	    delete $opts{'usecurrent'};
	}

	# handle the up/down case right away.
1718
	if (($action eq 'up' || $action eq 'down')
1719 1720 1721 1722 1723 1724 1725 1726
	    && scalar(keys(%opts)) == 0) {
	    push @cmds,"$IFCONFIGBIN $ath $action";
	    @$ret_aref = @cmds;
	    return 0;
	}

	# first grab as much current state as we can, so we don't destroy
	# previous state if we have to destroy the VAP (i.e., athX) interface
1727
	#