github.com/TeaOSLab/EdgeNode@v1.3.8/internal/firewalls/firewall.go (about) 1 // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. 2 3 package firewalls 4 5 import ( 6 teaconst "github.com/TeaOSLab/EdgeNode/internal/const" 7 "github.com/TeaOSLab/EdgeNode/internal/events" 8 "github.com/TeaOSLab/EdgeNode/internal/remotelogs" 9 "os" 10 "runtime" 11 "sync" 12 "time" 13 ) 14 15 var currentFirewall FirewallInterface 16 var firewallLocker = &sync.Mutex{} 17 18 // 初始化 19 func init() { 20 if !teaconst.IsMain { 21 return 22 } 23 24 events.On(events.EventLoaded, func() { 25 var firewall = Firewall() 26 if firewall.Name() != "mock" { 27 remotelogs.Println("FIREWALL", "found local firewall '"+firewall.Name()+"'") 28 } 29 }) 30 } 31 32 // Firewall 查找当前系统中最适合的防火墙 33 func Firewall() FirewallInterface { 34 firewallLocker.Lock() 35 defer firewallLocker.Unlock() 36 if currentFirewall != nil { 37 return currentFirewall 38 } 39 40 // http firewall 41 { 42 endpoint, _ := os.LookupEnv("EDGE_HTTP_FIREWALL_ENDPOINT") 43 if len(endpoint) > 0 { 44 var httpFirewall = NewHTTPFirewall(endpoint) 45 for i := 0; i < 10; i++ { 46 if httpFirewall.IsReady() { 47 currentFirewall = httpFirewall 48 remotelogs.Println("FIREWALL", "using http firewall '"+endpoint+"'") 49 break 50 } 51 time.Sleep(1 * time.Second) 52 } 53 return httpFirewall 54 } 55 } 56 57 // nftables 58 if runtime.GOOS == "linux" { 59 nftables, err := NewNFTablesFirewall() 60 if err != nil { 61 remotelogs.Warn("FIREWALL", "'nftables' should be installed on the system to enhance security (init failed: "+err.Error()+")") 62 } else { 63 if nftables.IsReady() { 64 currentFirewall = nftables 65 events.Notify(events.EventNFTablesReady) 66 return nftables 67 } else { 68 remotelogs.Warn("FIREWALL", "'nftables' should be enabled on the system to enhance security") 69 } 70 } 71 } 72 73 // firewalld 74 if runtime.GOOS == "linux" { 75 var firewalld = NewFirewalld() 76 if firewalld.IsReady() { 77 currentFirewall = firewalld 78 return currentFirewall 79 } 80 } 81 82 // 至少返回一个 83 currentFirewall = NewMockFirewall() 84 return currentFirewall 85 }