shithub: riscv

ref: 036cff108ae5ae82a1d378493df631bb35876803
dir: /rc/bin/ethermultilink/

View raw version
#!/bin/rc

# ethermultilink outpus bridge(3) commands to switch
# between multiple ethernet (or wifi) interfaces
# depending on their link status.

rfork e

fn usage {
	echo 'Usage: ' $0 'primaryether secondaryether1 [secondaryether2 ....] > /net/bridgeX/ctl' >[1=2]
	exit 'usage'
}
fn missing {
	echo 'missing: ' $1 >[1=2]
	exit 'missing'
}


~ $#* 0 1 && usage

# make sure arguments are ethernets
for(i){
	test -r $i/stats || missing $i/stats
}

# first interface is the primary
primary=$1

net=`{echo $primary | sed 's!/*[^/]*$!!g'}
test -r $net/arp || missing $net/arp

# now select secondary from the list depending on link status
@{
old=/dev/null
new=$old
while(){
	# interfaces are in increasing priority order
	for(i){
		if(grep -s 'link: 1' $i/stats)
			new=$i
	}
	if(! ~ $new $old){
		if(! ~ $old /dev/null){
			if(! ~ $old $primary) {
				echo unbind bypass primary 0
				echo unbind ether secondary 0
			}
		}
		if(! ~ $new $primary){
			echo bind bypass primary 0 $primary
			echo bind ether secondary 0 $new
		}
		# make switches aware of the new path
		echo flush > $net/arp

		old=$new
	}
	sleep 1
}
} </dev/null &

exit ''