github.com/TeaOSLab/EdgeNode@v1.3.8/internal/iplibrary/list_utils.go (about) 1 // Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved. 2 3 package iplibrary 4 5 import ( 6 "encoding/hex" 7 "github.com/TeaOSLab/EdgeCommon/pkg/iputils" 8 "github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs" 9 "github.com/iwind/TeaGo/Tea" 10 ) 11 12 // AllowIP 检查IP是否被允许访问 13 // 如果一个IP不在任何名单中,则允许访问 14 func AllowIP(ip string, serverId int64) (canGoNext bool, inAllowList bool, expiresAt int64) { 15 if !Tea.IsTesting() { // 如果在测试环境,我们不加入一些白名单,以便于可以在本地和局域网正常测试 16 // 放行lo 17 if ip == "127.0.0.1" || ip == "::1" { 18 return true, true, 0 19 } 20 21 // check node 22 nodeConfig, err := nodeconfigs.SharedNodeConfig() 23 if err == nil && nodeConfig.IPIsAutoAllowed(ip) { 24 return true, true, 0 25 } 26 } 27 28 var ipBytes = iputils.ToBytes(ip) 29 if IsZero(ipBytes) { 30 return false, false, 0 31 } 32 33 // check white lists 34 if GlobalWhiteIPList.Contains(ipBytes) { 35 return true, true, 0 36 } 37 38 if serverId > 0 { 39 var list = SharedServerListManager.FindWhiteList(serverId, false) 40 if list != nil && list.Contains(ipBytes) { 41 return true, true, 0 42 } 43 } 44 45 // check black lists 46 expiresAt, ok := GlobalBlackIPList.ContainsExpires(ipBytes) 47 if ok { 48 return false, false, expiresAt 49 } 50 51 if serverId > 0 { 52 var list = SharedServerListManager.FindBlackList(serverId, false) 53 if list != nil { 54 expiresAt, ok = list.ContainsExpires(ipBytes) 55 if ok { 56 return false, false, expiresAt 57 } 58 } 59 } 60 61 return true, false, 0 62 } 63 64 // IsInWhiteList 检查IP是否在白名单中 65 func IsInWhiteList(ip string) bool { 66 var ipBytes = iputils.ToBytes(ip) 67 if IsZero(ipBytes) { 68 return false 69 } 70 71 // check white lists 72 return GlobalWhiteIPList.Contains(ipBytes) 73 } 74 75 // AllowIPStrings 检查一组IP是否被允许访问 76 func AllowIPStrings(ipStrings []string, serverId int64) bool { 77 if len(ipStrings) == 0 { 78 return true 79 } 80 for _, ip := range ipStrings { 81 isAllowed, _, _ := AllowIP(ip, serverId) 82 if !isAllowed { 83 return false 84 } 85 } 86 return true 87 } 88 89 func IsZero(ipBytes []byte) bool { 90 return len(ipBytes) == 0 91 } 92 93 func ToHex(b []byte) string { 94 if len(b) == 0 { 95 return "" 96 } 97 98 return hex.EncodeToString(b) 99 }