Files
EdgeNode/internal/iplibrary/list_utils.go

131 lines
2.5 KiB
Go
Raw Normal View History

// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package iplibrary
import (
"bytes"
"encoding/hex"
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
2022-06-22 19:05:01 +08:00
"github.com/iwind/TeaGo/Tea"
"net"
)
// 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
}
}
var ipBytes = IPBytes(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 {
var ipBytes = IPBytes(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 CompareBytes(b1 []byte, b2 []byte) int {
var l1 = len(b1)
var l2 = len(b2)
if l1 < l2 {
return -1
}
if l1 > l2 {
return 1
}
return bytes.Compare(b1, b2)
}
func IPBytes(ip string) []byte {
if len(ip) == 0 {
return nil
}
var i = net.ParseIP(ip)
if i == nil {
return nil
}
var i4 = i.To4()
if i4 != nil {
return i4
}
return i.To16()
}
func ToHex(b []byte) string {
if len(b) == 0 {
return ""
}
return hex.EncodeToString(b)
}