xref: /DragonOS/tools/qemu/ifup-nat (revision fae6e9ade46a52976ad5d099643d51cc20876448)
1#!/bin/bash
2# 设置 bridge 名称
3BRIDGE=dragonos-bridge
4# 设置网络信息
5NETWORK=192.168.137.0
6NETMASK=255.255.255.0
7GATEWAY=192.168.137.1
8DHCPRANGE=192.168.137.100,192.168.137.200
9# 启用PXE支持的可选参数
10TFTPROOT=
11BOOTP=
12
13function check_bridge()
14{
15        if brctl show | grep "^$BRIDGE" &> /dev/null; then
16                return 1
17        else
18                return 0
19        fi
20}
21
22function create_bridge()
23{
24        brctl addbr "$BRIDGE"
25        brctl stp "$BRIDGE" on
26        brctl setfd "$BRIDGE" 0
27        ifconfig "$BRIDGE" "$GATEWAY" netmask "$NETMASK" up
28}
29
30function enable_ip_forward()
31{
32        echo 1 > /proc/sys/net/ipv4/ip_forward
33}
34
35function add_filter_rules()
36{
37        iptables -t nat -A POSTROUTING -s "$NETWORK"/"$NETMASK" \
38                ! -d "$NETWORK"/"$NETMASK" -j MASQUERADE
39}
40
41function start_dnsmasq()
42{
43# 禁止重复运行dnsmasq
44        ps -ef | grep "dnsmasq" | grep -v "grep" &> /dev/null
45        if [ $? -eq 0 ]; then
46                echo "dnsmasq 已经在运行"
47                return 1
48        fi
49        dnsmasq \
50                --strict-order \
51                --except-interface=lo \
52                --interface=$BRIDGE \
53                --listen-address=$GATEWAY \
54                --bind-interfaces \
55                --dhcp-range=$DHCPRANGE \
56                --conf-file="" \
57                --pid-file=/var/run/qemu-dhcp-$BRIDGE.pid \
58                --dhcp-leasefile=/var/run/qemu-dhcp-$BRIDGE.leases \
59                --dhcp-no-override \
60                ${TFTPROOT:+"--enable-tftp"} \
61                ${TFTPROOT:+"--tftp-root=$TFTPROOT"} \
62                ${BOOTP:+"--dhcp-boot=$BOOTP"}
63}
64
65function setup_bridge_nat()
66{
67        check_bridge "$BRIDGE"
68        if [ $? -eq 0 ]; then
69                create_bridge
70        fi
71        enable_ip_forward
72        add_filter_rules "$BRIDGE"
73        start_dnsmasq "$BRIDGE"
74}
75
76# 安装前需要检查$1参数
77if [ -n "$1" ]; then
78        setup_bridge_nat
79        brctl addif "$BRIDGE" "$1"
80        ifconfig "$1" 0.0.0.0 up
81        exit 0
82else
83        echo "发现错误:没有指定接口"
84        exit 1
85fi
86