Files
EdgeNode/internal/iplibrary/list_utils.go

100 lines
2.1 KiB
Go
Raw Normal View History

2024-05-17 18:30:33 +08:00
// Copyright 2021 GoEdge goedge.cdn@gmail.com. All rights reserved.
package iplibrary
import (
"encoding/hex"
2024-04-06 15:37:14 +08:00
"github.com/TeaOSLab/EdgeCommon/pkg/iputils"
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
2022-06-22 19:05:01 +08:00
"github.com/iwind/TeaGo/Tea"
)
// AllowIP 检查IP是否被允许访问
2022-01-10 19:54:10 +08:00
// 如果一个IP不在任何名单中则允许访问
2023-03-31 21:37:15 +08:00
func AllowIP(ip string, serverId int64) (canGoNext bool, inAllowList bool, expiresAt int64) {
2022-06-22 19:05:01 +08:00
if !Tea.IsTesting() { // 如果在测试环境,我们不加入一些白名单,以便于可以在本地和局域网正常测试
// 放行lo
2022-07-05 20:37:00 +08:00
if ip == "127.0.0.1" || ip == "::1" {
2023-03-31 21:37:15 +08:00
return true, true, 0
2022-06-22 19:05:01 +08:00
}
// check node
nodeConfig, err := nodeconfigs.SharedNodeConfig()
if err == nil && nodeConfig.IPIsAutoAllowed(ip) {
2023-03-31 21:37:15 +08:00
return true, true, 0
2022-06-22 19:05:01 +08:00
}
}
2024-04-06 15:37:14 +08:00
var ipBytes = iputils.ToBytes(ip)
if IsZero(ipBytes) {
2023-03-31 21:37:15 +08:00
return false, false, 0
}
// check white lists
if GlobalWhiteIPList.Contains(ipBytes) {
2023-03-31 21:37:15 +08:00
return true, true, 0
}
if serverId > 0 {
var list = SharedServerListManager.FindWhiteList(serverId, false)
if list != nil && list.Contains(ipBytes) {
2023-03-31 21:37:15 +08:00
return true, true, 0
}
}
// check black lists
expiresAt, ok := GlobalBlackIPList.ContainsExpires(ipBytes)
2023-03-31 21:37:15 +08:00
if ok {
return false, false, expiresAt
}
if serverId > 0 {
var list = SharedServerListManager.FindBlackList(serverId, false)
2023-03-31 21:37:15 +08:00
if list != nil {
expiresAt, ok = list.ContainsExpires(ipBytes)
2023-03-31 21:37:15 +08:00
if ok {
return false, false, expiresAt
}
}
}
2023-03-31 21:37:15 +08:00
return true, false, 0
}
2022-01-10 19:54:10 +08:00
// IsInWhiteList 检查IP是否在白名单中
func IsInWhiteList(ip string) bool {
2024-04-06 15:37:14 +08:00
var ipBytes = iputils.ToBytes(ip)
if IsZero(ipBytes) {
2022-01-10 19:54:10 +08:00
return false
}
// check white lists
return GlobalWhiteIPList.Contains(ipBytes)
2022-01-10 19:54:10 +08:00
}
// AllowIPStrings 检查一组IP是否被允许访问
func AllowIPStrings(ipStrings []string, serverId int64) bool {
if len(ipStrings) == 0 {
return true
}
for _, ip := range ipStrings {
2023-03-31 21:37:15 +08:00
isAllowed, _, _ := AllowIP(ip, serverId)
if !isAllowed {
return false
}
}
return true
}
func IsZero(ipBytes []byte) bool {
return len(ipBytes) == 0
}
func ToHex(b []byte) string {
if len(b) == 0 {
return ""
}
return hex.EncodeToString(b)
}