修复 modprobe 报错

This commit is contained in:
bjdgyc
2023-12-25 14:31:35 +08:00
parent 64404ea94b
commit d3f16eb2ad
8 changed files with 130 additions and 55 deletions

View File

@@ -3,5 +3,5 @@ package base
const (
APP_NAME = "AnyLink"
// app版本号
APP_VER = "0.9.4"
APP_VER = "0.10.1"
)

65
server/base/mod.go Normal file
View File

@@ -0,0 +1,65 @@
package base
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"strings"
)
const (
procModulesPath = "/proc/modules"
inContainerKey = "ANYLINK_IN_CONTAINER"
)
var (
inContainer = false
modMap = map[string]struct{}{}
)
func initMod() {
container := os.Getenv(inContainerKey)
if container == "true" {
inContainer = true
}
log.Println("inContainer", inContainer)
file, err := os.Open(procModulesPath)
if err != nil {
err = fmt.Errorf("[ERROR] Problem with open file: %s", err)
panic(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
splited := strings.Split(scanner.Text(), " ")
if len(splited[0]) > 0 {
modMap[splited[0]] = struct{}{}
}
}
}
func CheckModOrLoad(mod string) {
log.Println("CheckModOrLoad", mod)
if _, ok := modMap[mod]; ok {
return
}
if inContainer {
err := fmt.Errorf("Linux modules %s is not loaded, please run `modprobe %s`", mod, mod)
panic(err)
}
cmdstr := fmt.Sprintln("modprobe", mod)
cmd := exec.Command("sh", "-c", cmdstr)
b, err := cmd.CombinedOutput()
if err != nil {
log.Println(string(b))
panic(err)
}
}

View File

@@ -4,6 +4,7 @@ func Start() {
execute()
initCfg()
initLog()
initMod()
}
func Test() {

View File

@@ -22,9 +22,10 @@ func checkTun() {
defer ifce.Close()
// 测试ip命令
cmdstr0 := fmt.Sprintln("modprobe -i tun")
base.CheckModOrLoad("tun")
cmdstr1 := fmt.Sprintf("ip link set dev %s up mtu %s multicast off", ifce.Name(), "1399")
err = execCmd([]string{cmdstr0, cmdstr1})
err = execCmd([]string{cmdstr1})
if err != nil {
base.Fatal("testTun err: ", err)
}
@@ -41,12 +42,8 @@ func checkTun() {
}
// 修复 rockyos nat 不生效
cmdstr0 := fmt.Sprintln("modprobe -i iptable_filter")
cmdstr1 := fmt.Sprintf("modprobe -i iptable_nat")
err = execCmd([]string{cmdstr0, cmdstr1})
if err != nil {
base.Fatal("testTun err: ", err)
}
base.CheckModOrLoad("iptable_filter")
base.CheckModOrLoad("iptable_nat")
natRule := []string{"-s", base.Cfg.Ipv4CIDR, "-o", base.Cfg.Ipv4Master, "-j", "MASQUERADE"}
forwardRule := []string{"-j", "ACCEPT"}

View File

@@ -33,13 +33,14 @@ func checkMacvtap() {
ifName := "anylinkMacvtap"
// 加载 macvtap
cmdstr0 := fmt.Sprintln("modprobe -i macvtap")
base.CheckModOrLoad("macvtap")
// 开启主网卡混杂模式
cmdstr1 := fmt.Sprintf("ip link set dev %s promisc on", base.Cfg.Ipv4Master)
// 测试 macvtap 功能
cmdstr2 := fmt.Sprintf("ip link add link %s name %s type macvtap mode bridge", base.Cfg.Ipv4Master, ifName)
cmdstr3 := fmt.Sprintf("ip link del %s", ifName)
err := execCmd([]string{cmdstr0, cmdstr1, cmdstr2, cmdstr3})
err := execCmd([]string{cmdstr1, cmdstr2, cmdstr3})
if err != nil {
base.Fatal(err)
}