diff --git a/internal/nodes/admin_node.go b/internal/nodes/admin_node.go index 8443e365..15f4f26b 100644 --- a/internal/nodes/admin_node.go +++ b/internal/nodes/admin_node.go @@ -13,9 +13,12 @@ import ( "github.com/iwind/TeaGo/maps" "github.com/iwind/TeaGo/rands" "github.com/iwind/TeaGo/sessions" + "github.com/iwind/TeaGo/types" "github.com/iwind/gosock/pkg/gosock" + "gopkg.in/yaml.v3" "io/ioutil" "log" + "net" "os" "os/exec" "os/signal" @@ -58,6 +61,9 @@ func (this *AdminNode) Run() { return } + // 添加端口到防火墙 + this.addPortsToFirewall() + // 监听信号 sigQueue := make(chan os.Signal) signal.Notify(sigQueue, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGQUIT) @@ -201,6 +207,44 @@ https: return nil } +// 添加端口到防火墙 +func (this *AdminNode) addPortsToFirewall() { + var configFile = Tea.ConfigFile("server.yaml") + data, err := ioutil.ReadFile(configFile) + if err != nil { + return + } + + var config = &TeaGo.ServerConfig{} + err = yaml.Unmarshal(data, config) + if err != nil { + return + } + + var ports = []int{} + if config.Http.On { + for _, listen := range config.Http.Listen { + _, portString, _ := net.SplitHostPort(listen) + var port = types.Int(portString) + if port > 0 && !lists.ContainsInt(ports, port) { + ports = append(ports, port) + } + } + } + + if config.Https.On { + for _, listen := range config.Https.Listen { + _, portString, _ := net.SplitHostPort(listen) + var port = types.Int(portString) + if port > 0 && !lists.ContainsInt(ports, port) { + ports = append(ports, port) + } + } + } + + utils.AddPortsToFirewall(ports) +} + // 启动API节点 func (this *AdminNode) startAPINode() { configPath := Tea.Root + "/edge-api/configs/api.yaml" diff --git a/internal/utils/firewall.go b/internal/utils/firewall.go new file mode 100644 index 00000000..583032a9 --- /dev/null +++ b/internal/utils/firewall.go @@ -0,0 +1,28 @@ +// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn . + +package utils + +import ( + "github.com/iwind/TeaGo/logs" + "github.com/iwind/TeaGo/types" + "os/exec" + "runtime" +) + +func AddPortsToFirewall(ports []int) { + for _, port := range ports { + // Linux + if runtime.GOOS == "linux" { + // firewalld + firewallCmd, _ := exec.LookPath("firewall-cmd") + if len(firewallCmd) > 0 { + err := exec.Command(firewallCmd, "--add-port="+types.String(port)+"/tcp").Run() + if err == nil { + logs.Println("API_NODE", "add port '"+types.String(port)+"' to firewalld") + + _ = exec.Command(firewallCmd, "--add-port="+types.String(port)+"/tcp", "--permanent").Run() + } + } + } + } +}