1#!/bin/bash
2#
3# Create a "bank" of tap network devices that can be used by the
4# runqemu script. This script needs to be run as root
5#
6# Copyright (C) 2010 Intel Corp.
7#
8# SPDX-License-Identifier: GPL-2.0-only
9#
10
11gid=`id -g`
12if [ -n "$SUDO_GID" ]; then
13    gid=$SUDO_GID
14fi
15
16usage() {
17	echo "Usage: sudo $0 <gid> <num>"
18	echo "Where <gid> is the numeric group id the tap devices will be owned by"
19	echo "<num> is the number of tap devices to create (0 to remove all)"
20	echo "For example:"
21	echo "$ bitbake qemu-helper-native"
22	echo "$ sudo $0 $gid 4"
23	echo ""
24	exit 1
25}
26
27# Allow passing 4 arguments for backward compatibility with warning
28if [ $# -gt 4 ]; then
29	echo "Error: Incorrect number of arguments"
30	usage
31fi
32if [ $# -gt 3 ]; then
33	echo "Warning: Ignoring the <native-sysroot-basedir> parameter. It is no longer needed."
34fi
35if [ $# -gt 2 ]; then
36	echo "Warning: Ignoring the <uid> parameter. It is no longer needed."
37	GID=$2
38	COUNT=$3
39elif [ $# -eq 2 ]; then
40	GID=$1
41	COUNT=$2
42else
43	echo "Error: Incorrect number of arguments"
44	usage
45fi
46
47
48if [ -z "$OE_TAP_NAME" ]; then
49	OE_TAP_NAME=tap
50fi
51
52# check if COUNT is a number and >= 0
53if ! [ $COUNT -ge 0 ]; then
54	echo "Error: Incorrect count: $COUNT"
55	exit 1
56fi
57
58if [ $EUID -ne 0 ]; then
59	echo "Error: This script must be run with root privileges"
60	exit
61fi
62
63SCRIPT_DIR=`dirname $0`
64RUNQEMU_IFUP="$SCRIPT_DIR/runqemu-ifup"
65if [ ! -x "$RUNQEMU_IFUP" ]; then
66	echo "Error: Unable to find the runqemu-ifup script in $SCRIPT_DIR"
67	exit 1
68fi
69
70if interfaces=`ip tuntap list` 2>/dev/null; then
71	interfaces=`echo "$interfaces" |cut -f1 -d: |grep -E "^$OE_TAP_NAME.*"`
72else
73	echo "Failed to call 'ip tuntap list'" >&2
74	exit 1
75fi
76
77# Ensure we start with a clean slate
78for tap in $interfaces; do
79	echo "Note: Destroying pre-existing tap interface $tap..."
80	ip tuntap del $tap mode tap
81done
82rm -f /etc/runqemu-nosudo
83
84if [ $COUNT -eq 0 ]; then
85	exit 0
86fi
87
88echo "Creating $COUNT tap devices for GID: $GID..."
89for ((index=0; index < $COUNT; index++)); do
90	echo "Creating $OE_TAP_NAME$index"
91	if ! ifup=`$RUNQEMU_IFUP $GID 2>&1`; then
92		echo "Error bringing up interface: $ifup"
93		exit 1
94	fi
95done
96
97echo "Note: For systems running NetworkManager, it's recommended"
98echo "Note: that the tap devices be set as unmanaged in the"
99echo "Note: NetworkManager.conf file. Add the following lines to"
100echo "Note: /etc/NetworkManager/NetworkManager.conf"
101echo "[keyfile]"
102echo "unmanaged-devices=interface-name:$OE_TAP_NAME*"
103
104# The runqemu script will check for this file, and if it exists,
105# will use the existing bank of tap devices without creating
106# additional ones via sudo.
107touch /etc/runqemu-nosudo
108