virtual-dsm/run/network.sh

405 lines
13 KiB
Bash
Raw Normal View History

2023-04-02 17:55:25 +02:00
#!/usr/bin/env bash
set -eu
2023-04-18 17:49:41 +02:00
# Docker environment variabeles
2023-04-18 17:47:41 +02:00
2023-04-15 12:50:48 +02:00
: ${VM_NET_HOST:='VirtualDSM'}
2023-04-14 01:23:09 +02:00
: ${VM_NET_MAC:='02:11:32:AA:BB:CC'}
2023-04-02 17:55:25 +02:00
2023-04-11 05:58:31 +02:00
: ${DNS_SERVERS:=''}
2023-04-02 21:37:31 +02:00
: ${DNSMASQ_OPTS:=''}
2023-04-19 21:50:35 +02:00
: ${DNSMASQ:='/usr/sbin/dnsmasq'}
2023-04-02 21:37:31 +02:00
: ${DNSMASQ_CONF_DIR:='/etc/dnsmasq.d'}
2023-04-02 17:55:25 +02:00
2023-04-02 21:37:31 +02:00
# ######################################
# Functions
# ######################################
2023-04-20 00:42:51 +02:00
log () {
case "$1" in
INFO | WARNING | ERROR )
echo "$1: ${@:2}"
;;
DEBUG)
echo "$1: ${@:2}"
;;
*)
echo "-- $@"
;;
esac
}
# ContainsElement: checks if first parameter is among the array given as second parameter
# returns 0 if the element is found in the list and 1 if not
# usage: containsElement $item $list
containsElement () {
local e
for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
return 1
}
# Generate random MAC address
genMAC () {
hexchars="0123456789ABCDEF"
end=$( for i in {1..8} ; do echo -n ${hexchars:$(( $RANDOM % 16 )):1} ; done | sed -e 's/\(..\)/:\1/g' )
echo "FE:05$end"
}
# atoi: Returns the integer representation of an IP arg, passed in ascii
# dotted-decimal notation (x.x.x.x)
atoi() {
IP=$1
IPnum=0
for (( i=0 ; i<4 ; ++i ))
do
((IPnum+=${IP%%.*}*$((256**$((3-${i}))))))
IP=${IP#*.}
done
echo $IPnum
}
# itoa: returns the dotted-decimal ascii form of an IP arg passed in integer
# format
itoa() {
echo -n $(($(($(($((${1}/256))/256))/256))%256)).
echo -n $(($(($((${1}/256))/256))%256)).
echo -n $(($((${1}/256))%256)).
echo $((${1}%256))
}
cidr2mask() {
local i mask=""
local full_octets=$(($1/8))
local partial_octet=$(($1%8))
for ((i=0;i<4;i+=1)); do
if [ $i -lt $full_octets ]; then
mask+=255
elif [ $i -eq $full_octets ]; then
mask+=$((256 - 2**(8-$partial_octet)))
else
mask+=0
fi
test $i -lt 3 && mask+=.
done
echo $mask
}
# Generates and returns a new IP and MASK in a superset (inmediate wider range)
# of the given IP/MASK
# usage: getNonConflictingIP IP MASK
# returns NEWIP MASK
getNonConflictingIP () {
local IP="$1"
local CIDR="$2"
let "newCIDR=$CIDR-1"
local i=$(atoi $IP)
let "j=$i^(1<<(32-$CIDR))"
local newIP=$(itoa j)
echo $newIP $newCIDR
}
# generates unused, random names for macvlan or bridge devices
# usage: generateNetDevNames DEVICETYPE
# DEVICETYPE must be either 'macvlan' or 'bridge'
# returns:
# - bridgeXXXXXX if DEVICETYPE is 'bridge'
# - macvlanXXXXXX, macvtapXXXXXX if DEVICETYPE is 'macvlan'
generateNetdevNames () {
devicetype=$1
local netdevinterfaces=($(ip link show | awk "/$devicetype/ { print \$2 }" | cut -d '@' -f 1 | tr -d :))
local randomID=$(cat /dev/urandom | tr -dc 'a-f0-9' | fold -w 6 | head -n 1)
# check if the device already exists and regenerate the name if so
while containsElement "$devicetype$randomID" "${netdevinterfaces[@]}"; do randomID=$(cat /dev/urandom | tr -dc 'a-f0-9' | fold -w 6 | head -n 1); done
echo "$randomID"
}
setupBridge () {
set -x
local iface="$1"
local mode="$2"
local deviceID=$(generateNetdevNames $mode)
local bridgeName="$mode$deviceID"
if [[ $mode == "bridge" ]]; then
brctl addbr "$bridgeName"
brctl addif "$bridgeName" "$iface"
else # use macvlan devices by default
vtapdev="macvtap${deviceID}"
until $(ip link add link $iface name $vtapdev type macvtap mode bridge); do
sleep 1
done
ip link set $vtapdev address "$MAC"
ip link set $vtapdev up
# create a macvlan device for the host
ip link add link $iface name $bridgeName type macvlan mode bridge
ip link set $bridgeName up
# create dev file (there is no udev in container: need to be done manually)
IFS=: read major minor < <(cat /sys/devices/virtual/net/$vtapdev/tap*/dev)
mknod "/dev/$vtapdev" c $major $minor
fi
set +x
# get a new IP for the guest machine in a broader network broadcast domain
if ! [[ -z $IP ]]; then
newIP=($(getNonConflictingIP $IP $CIDR))
ip address del "$IP/$CIDR" dev "$iface"
ip address add "${newIP[0]}/${newIP[1]}" dev "$bridgeName"
fi
ip link set dev "$bridgeName" up
echo $deviceID
}
# Setup macvtap device to connect later the VM and setup a new macvlan devide
# to connect the host machine to the network
configureNetworks () {
local IP
local i=0
local GATEWAY=$(ip r | grep default | awk '{print $3}')
for iface in "${local_ifaces[@]}"; do
IPs=$(ip address show dev $iface | grep inet | awk '/inet / { print $2 }' | cut -f1 -d/)
IPs=($IPs)
MAC=$(ip link show $iface | awk '/ether/ { print $2 }')
log "DEBUG" "Container original MAC address: $MAC"
# If the container has more than one IP configured in a given interface,
# the user can select which one to use.
# The SELECTED_NETWORK environment variable is used to select that IP.
# This env variable must be in the form IP/MASK (e.g. 1.2.3.4/24).
#
# If this env variable is not set, the IP to be given to the VM is
# the first in the list for that interface (default behaviour).
if ! [[ -z "$SELECTED_NETWORK" ]]; then
local given_ip given_mask
IFS=/ read given_ip given_mask <<< $SELECTED_NETWORK
local given_addr=$(atoi $given_ip)
local given_mask=$((0xffffffff << (32 - $given_mask) & 0xffffffff))
local given_broadcast=$((given_addr | ~given_mask & 0xffffffff))
local given_network=$((given_addr & given_mask))
for configured_ip in "${IPs[@]}"; do
local configured_ip=$(atoi $configured_ip)
if [[ $configured_ip -gt $given_network && $configured_ip -lt $given_broadcast ]]; then
IP=$(itoa $configured_ip)
log "INFO" "SELECTED_NETWORK ($SELECTED_NETWORK) found with ip $IP in $iface interface."
fi
done
[[ -z "$IP" ]] && log "WARNING" "SELECTED_NETWORK ($SELECTED_NETWORK) not found in $iface interface."
else
IP=${IPs[0]}
fi
local CIDR=$(ip address show dev $iface | awk "/inet $IP/ { print \$2 }" | cut -f2 -d/)
# use container MAC address ($MAC) for tap device
# and generate a new one for the local interface
ip link set $iface down
ip link set $iface address $(genMAC)
ip link set $iface up
# setup the macvtap devices for bridging the VM
deviceID=($(setupBridge $iface "macvlan"))
bridgeName="macvlan$deviceID"
# kvm configuration:
let fd=$i+3
NET_OPTS="$KVM_NET_OPTS -netdev tap,id=net$i,vhost=on,fd=$fd ${fd}<>/dev/macvtap$deviceID"
setupDhcp
log "DEBUG" "bridgeName: $bridgeName"
NET_OPTS=" -device virtio-net-pci,netdev=net$i,mac=$MAC $NET_OPTS"
let i++
done
}
2023-04-20 00:16:13 +02:00
configureDHCP() {
2023-04-19 21:50:35 +02:00
VM_NET_TAP="_VmMacvtap"
2023-04-19 22:11:39 +02:00
echo "Info: Retrieving IP via DHCP using MAC ${VM_NET_MAC}..."
2023-04-19 22:34:38 +02:00
2023-04-19 21:50:35 +02:00
ip l add link eth0 name ${VM_NET_TAP} address ${VM_NET_MAC} type macvtap mode bridge || true
ip l set ${VM_NET_TAP} up
2023-04-19 22:34:38 +02:00
2023-04-19 21:50:35 +02:00
ip a flush eth0
ip a flush ${VM_NET_TAP}
2023-04-19 22:11:39 +02:00
2023-04-19 22:34:38 +02:00
_DhcpIP=$( dhclient -v ${VM_NET_TAP} 2>&1 | grep ^bound | cut -d' ' -f3 )
2023-04-19 21:50:35 +02:00
[[ "${_DhcpIP}" == [0-9.]* ]] \
2023-04-19 23:11:23 +02:00
&& echo "Info: Retrieved IP ${_DhcpIP} from DHCP using MAC ${VM_NET_MAC}" \
|| ( echo "ERROR: Cannot retrieve IP from DHCP using MAC ${VM_NET_MAC}" && exit 16 )
2023-04-19 21:50:35 +02:00
ip a flush ${VM_NET_TAP}
2023-04-19 22:34:38 +02:00
2023-04-19 21:50:35 +02:00
_tmpTapPath="/dev/tap$(</sys/class/net/${VM_NET_TAP}/ifindex)"
2023-04-19 23:07:38 +02:00
2023-04-20 00:09:26 +02:00
# get MAJOR MINOR DEVNAME
2023-04-19 21:50:35 +02:00
MAJOR=""
eval "$(</sys/class/net/${VM_NET_TAP}/macvtap/${_tmpTapPath##*/}/uevent) _tmp=0"
2023-04-19 22:34:38 +02:00
2023-04-19 21:50:35 +02:00
[[ "x${MAJOR}" != "x" ]] \
2023-04-19 23:35:59 +02:00
&& echo "Info: Please make sure that the following docker setting is used: --device-cgroup-rule='c ${MAJOR}:* rwm'" \
2023-04-19 23:07:38 +02:00
|| ( echo "Info: Macvtap creation issue: Cannot find: /sys/class/net/${VM_NET_TAP}/" && exit 18 )
2023-04-19 22:34:38 +02:00
2023-04-19 21:50:35 +02:00
[[ ! -e ${_tmpTapPath} ]] && [[ -e /dev0/${_tmpTapPath##*/} ]] && ln -s /dev0/${_tmpTapPath##*/} ${_tmpTapPath}
2023-04-19 22:34:38 +02:00
2023-04-19 21:50:35 +02:00
if [[ ! -e ${_tmpTapPath} ]]; then
2023-04-19 23:46:24 +02:00
mknod ${_tmpTapPath} c $MAJOR $MINOR && : || ("ERROR: Cannot mknod: ${_tmpTapPath}" && exit 20)
2023-04-19 21:50:35 +02:00
fi
2023-04-20 00:20:35 +02:00
NET_OPTS="-netdev tap,id=hostnet0,ifname=tap2,script=no,downscript=no"
#NET_OPTS="-netdev tap,id=hostnet0,vhost=on,vhostfd=40,fd=30 30<>${_tmpTapPath} 40<>/dev/vhost-net"
2023-04-19 21:50:35 +02:00
}
2023-04-20 00:16:13 +02:00
configureNAT () {
2023-04-19 21:50:35 +02:00
VM_NET_IP='20.20.20.21'
VM_NET_TAP="_VmNatTap"
2023-04-02 21:37:31 +02:00
2023-04-10 20:14:16 +02:00
#Create bridge with static IP for the VM guest
2023-04-02 21:37:31 +02:00
brctl addbr dockerbridge
ip addr add ${VM_NET_IP%.*}.1/24 broadcast ${VM_NET_IP%.*}.255 dev dockerbridge
ip link set dockerbridge up
#QEMU Works with taps, set tap to the bridge created
ip tuntap add dev ${VM_NET_TAP} mode tap
ip link set ${VM_NET_TAP} up promisc on
brctl addif dockerbridge ${VM_NET_TAP}
#Add internet connection to the VM
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -t nat -A PREROUTING -i eth0 -p tcp -j DNAT --to $VM_NET_IP
iptables -t nat -A PREROUTING -i eth0 -p udp -j DNAT --to $VM_NET_IP
#Enable port forwarding flag
[[ $(< /proc/sys/net/ipv4/ip_forward) -eq 0 ]] && sysctl -w net.ipv4.ip_forward=1
2023-04-14 01:23:09 +02:00
# dnsmasq configuration:
2023-04-15 12:50:48 +02:00
DNSMASQ_OPTS="$DNSMASQ_OPTS --dhcp-range=$VM_NET_IP,$VM_NET_IP --dhcp-host=$VM_NET_MAC,,$VM_NET_IP,$VM_NET_HOST,infinite --dhcp-option=option:netmask,255.255.255.0"
2023-04-14 01:23:09 +02:00
# Create lease file for faster resolve
2023-04-15 12:50:48 +02:00
echo "0 $VM_NET_MAC $VM_NET_IP $VM_NET_HOST 01:${VM_NET_MAC}" > /var/lib/misc/dnsmasq.leases
2023-04-14 01:23:09 +02:00
chmod 644 /var/lib/misc/dnsmasq.leases
2023-04-19 21:50:35 +02:00
2023-04-20 00:16:13 +02:00
NET_OPTS="-netdev tap,ifname=${VM_NET_TAP},script=no,downscript=no,id=hostnet0"
2023-04-19 21:50:35 +02:00
# Build DNS options from container /etc/resolv.conf
nameservers=($(grep '^nameserver' /etc/resolv.conf | sed 's/nameserver //'))
searchdomains=$(grep '^search' /etc/resolv.conf | sed 's/search //' | sed 's/ /,/g')
domainname=$(echo $searchdomains | awk -F"," '{print $1}')
for nameserver in "${nameservers[@]}"; do
if ! [[ $nameserver =~ .*:.* ]]; then
[[ -z $DNS_SERVERS ]] && DNS_SERVERS=$nameserver || DNS_SERVERS="$DNS_SERVERS,$nameserver"
fi
done
[[ -z $DNS_SERVERS ]] && DNS_SERVERS="1.1.1.1"
DNSMASQ_OPTS="$DNSMASQ_OPTS --dhcp-option=option:dns-server,$DNS_SERVERS --dhcp-option=option:router,${VM_NET_IP%.*}.1"
if [ -n "$searchdomains" -a "$searchdomains" != "." ]; then
DNSMASQ_OPTS="$DNSMASQ_OPTS --dhcp-option=option:domain-search,$searchdomains --dhcp-option=option:domain-name,$domainname"
else
[[ -z $(hostname -d) ]] || DNSMASQ_OPTS="$DNSMASQ_OPTS --dhcp-option=option:domain-name,$(hostname -d)"
fi
[ "$DEBUG" = "Y" ] && echo && echo "$DNSMASQ $DNSMASQ_OPTS"
$DNSMASQ $DNSMASQ_OPTS
2023-04-02 17:55:25 +02:00
}
2023-04-02 21:37:31 +02:00
# ######################################
# Configure Network
# ######################################
2023-04-03 22:21:14 +02:00
# Create the necessary file structure for /dev/net/tun
if [ ! -c /dev/net/tun ]; then
[ ! -d /dev/net ] && mkdir -m 755 /dev/net
2023-04-03 22:08:47 +02:00
mknod /dev/net/tun c 10 200
2023-04-03 22:15:24 +02:00
chmod 666 /dev/net/tun
2023-04-03 22:08:47 +02:00
fi
[ ! -c /dev/net/tun ] && echo "Error: TUN network interface not available..." && exit 85
2023-04-19 19:50:47 +02:00
if [ "$DEBUG" = "Y" ]; then
2023-04-19 22:19:08 +02:00
IP=$(ip address show dev eth0 | grep inet | awk '/inet / { print $2 }' | cut -f1 -d/)
2023-04-19 21:50:35 +02:00
echo && ifconfig
2023-04-19 22:10:26 +02:00
echo && ip route && echo
2023-04-19 22:58:17 +02:00
echo "Container IP: ${IP}" && echo
2023-04-19 22:19:08 +02:00
2023-04-19 18:51:24 +02:00
fi
2023-04-02 21:37:31 +02:00
update-alternatives --set iptables /usr/sbin/iptables-legacy > /dev/null
update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy > /dev/null
2023-04-19 22:58:17 +02:00
GATEWAY=$(ip r | grep default | awk '{print $3}')
if [[ "$GATEWAY" == "172."* ]]; then
2023-04-20 00:16:13 +02:00
# Configuration for static IP
2023-04-20 00:42:51 +02:00
#configureNAT
2023-04-19 22:58:17 +02:00
else
2023-04-20 00:16:13 +02:00
# Configuration for DHCP IP
2023-04-20 00:42:51 +02:00
#configureDHCP
2023-04-19 22:58:17 +02:00
fi
2023-04-02 17:55:25 +02:00
2023-04-20 00:42:51 +02:00
# Get all interfaces:
local_ifaces=($(ip link show | grep -v noop | grep state | grep -v LOOPBACK | awk '{print $2}' | tr -d : | sed 's/@.*$//'))
local_bridges=($(brctl show | tail -n +2 | awk '{print $1}'))
# Get non-bridge interfaces:
for i in "${local_bridges[@]}"
do
local_ifaces=(${local_ifaces[@]//*$i*})
done
DEFAULT_ROUTE=$(ip route | grep default | awk '{print $3}')
configureNetworks
# Hack for guest VMs complaining about "bad udp checksums in 5 packets"
/usr/sbin/iptables -A POSTROUTING -t mangle -p udp --dport bootpc -j CHECKSUM --checksum-fill
# Build DNS options from container /etc/resolv.conf
nameservers=($(grep nameserver /etc/resolv.conf | sed 's/nameserver //'))
searchdomains=$(grep search /etc/resolv.conf | sed 's/search //' | sed 's/ /,/g')
domainname=$(echo $searchdomains | awk -F"," '{print $1}')
for nameserver in "${nameservers[@]}"; do
[[ -z $DNS_SERVERS ]] && DNS_SERVERS=$nameserver || DNS_SERVERS="$DNS_SERVERS,$nameserver"
done
DNSMASQ_OPTS="$DNSMASQ_OPTS \
--dhcp-option=option:dns-server,$DNS_SERVERS \
--dhcp-option=option:router,$DEFAULT_ROUTE \
--dhcp-option=option:domain-search,$searchdomains \
--dhcp-option=option:domain-name,$domainname \
"
[[ -z $(hostname -d) ]] || DNSMASQ_OPTS="$DNSMASQ_OPTS --dhcp-option=option:domain-name,$(hostname -d)"
log "INFO" "Lauching dnsmasq"
log "DEBUG" "dnsmasq options: $DNSMASQ_OPTS"
$DNSMASQ $DNSMASQ_OPTS
2023-04-20 00:16:13 +02:00
NET_OPTS="${NET_OPTS} -device virtio-net-pci,romfile=,netdev=hostnet0,mac=${VM_NET_MAC},id=net0"
2023-04-02 21:37:31 +02:00
# Hack for guest VMs complaining about "bad udp checksums in 5 packets"
2023-04-20 00:42:51 +02:00
# iptables -A POSTROUTING -t mangle -p udp --dport bootpc -j CHECKSUM --checksum-fill