1#!/bin/bash 2# 3# QEMU network interface configuration script. This utility needs to 4# be run as root, and will use the ip utility 5# 6# If you find yourself calling this script a lot, you can add the 7# the following to your /etc/sudoers file to be able to run this 8# command without entering your password each time: 9# 10# <my-username> ALL=NOPASSWD: /path/to/runqemu-ifup 11# <my-username> ALL=NOPASSWD: /path/to/runqemu-ifdown 12# 13# If you'd like to create a bank of tap devices at once, you should use 14# the runqemu-gen-tapdevs script instead. If tap devices are set up using 15# that script, the runqemu script will never end up calling this 16# script. 17# 18# Copyright (c) 2006-2011 Linux Foundation 19# 20# SPDX-License-Identifier: GPL-2.0-only 21# 22 23usage() { 24 echo "sudo $(basename $0) <gid>" 25} 26 27if [ $EUID -ne 0 ]; then 28 echo "Error: This script (runqemu-ifup) must be run with root privileges" 29 exit 1 30fi 31 32if [ $# -eq 2 ]; then 33 echo "Warning: uid parameter is ignored. It is no longer needed." >&2 34 GROUP="$2" 35elif [ $# -eq 1 ]; then 36 GROUP="$1" 37else 38 usage 39 exit 1 40fi 41 42 43if [ -z "$OE_TAP_NAME" ]; then 44 OE_TAP_NAME=tap 45fi 46 47if taps=$(ip tuntap list 2>/dev/null); then 48 tap_no_last=$(echo "$taps" |cut -f 1 -d ":" |grep -E "^$OE_TAP_NAME.*" |sed "s/$OE_TAP_NAME//g" | sort -rn | head -n 1) 49 if [ -z "$tap_no_last" ]; then 50 tap_no=0 51 else 52 tap_no=$(("$tap_no_last" + 1)) 53 fi 54 ip tuntap add "$OE_TAP_NAME$tap_no" mode tap group "$GROUP" && TAP=$OE_TAP_NAME$tap_no 55fi 56 57if [ -z "$TAP" ]; then 58 echo "Error: Unable to find a tap device to use" 59 exit 1 60fi 61 62IPTOOL=`which ip 2> /dev/null` 63if [ "x$IPTOOL" = "x" ]; then 64 # better than nothing... 65 IPTOOL=/sbin/ip 66fi 67if [ ! -x "$IPTOOL" ]; then 68 echo "$IPTOOL cannot be executed" 69 exit 1 70fi 71 72IPTABLES=`which iptables 2> /dev/null` 73if [ "x$IPTABLES" = "x" ]; then 74 IPTABLES=/sbin/iptables 75fi 76if [ ! -x "$IPTABLES" ]; then 77 echo "$IPTABLES cannot be executed" 78 exit 1 79fi 80 81n=$[ (`echo $TAP | sed "s/$OE_TAP_NAME//"` * 2) + 1 ] 82$IPTOOL addr add 192.168.7.$n/32 broadcast 192.168.7.255 dev $TAP 83STATUS=$? 84if [ $STATUS -ne 0 ]; then 85 echo "Failed to set up IP addressing on $TAP" 86 exit 1 87fi 88$IPTOOL link set dev $TAP up 89STATUS=$? 90if [ $STATUS -ne 0 ]; then 91 echo "Failed to bring up $TAP" 92 exit 1 93fi 94 95dest=$[ (`echo $TAP | sed "s/$OE_TAP_NAME//"` * 2) + 2 ] 96$IPTOOL route add to 192.168.7.$dest dev $TAP 97STATUS=$? 98if [ $STATUS -ne 0 ]; then 99 echo "Failed to add route to 192.168.7.$dest using $TAP" 100 exit 1 101fi 102 103# setup NAT for tap0 interface to have internet access in QEMU 104$IPTABLES -A POSTROUTING -t nat -j MASQUERADE -s 192.168.7.$n/32 105$IPTABLES -A POSTROUTING -t nat -j MASQUERADE -s 192.168.7.$dest/32 106echo 1 > /proc/sys/net/ipv4/ip_forward 107echo 1 > /proc/sys/net/ipv4/conf/$TAP/proxy_arp 108$IPTABLES -P FORWARD ACCEPT 109 110echo $TAP 111