2024-04-05 02:09:16 +00:00
|
|
|
package network
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-04-05 02:18:42 +00:00
|
|
|
"fmt"
|
2024-04-05 02:09:16 +00:00
|
|
|
"github.com/songquanpeng/one-api/common/logger"
|
|
|
|
"net"
|
2024-04-05 09:25:28 +00:00
|
|
|
"strings"
|
2024-04-05 02:09:16 +00:00
|
|
|
)
|
|
|
|
|
2024-04-05 09:25:28 +00:00
|
|
|
func splitSubnets(subnets string) []string {
|
|
|
|
res := strings.Split(subnets, ",")
|
|
|
|
for i := 0; i < len(res); i++ {
|
|
|
|
res[i] = strings.TrimSpace(res[i])
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
|
|
|
func isValidSubnet(subnet string) error {
|
2024-04-05 02:18:42 +00:00
|
|
|
_, _, err := net.ParseCIDR(subnet)
|
2024-04-05 04:40:03 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to parse subnet: %w", err)
|
|
|
|
}
|
|
|
|
return nil
|
2024-04-05 02:18:42 +00:00
|
|
|
}
|
|
|
|
|
2024-04-05 09:25:28 +00:00
|
|
|
func isIpInSubnet(ctx context.Context, ip string, subnet string) bool {
|
2024-04-05 02:09:16 +00:00
|
|
|
_, ipNet, err := net.ParseCIDR(subnet)
|
|
|
|
if err != nil {
|
2024-04-05 02:18:42 +00:00
|
|
|
logger.Errorf(ctx, "failed to parse subnet: %s", err.Error())
|
2024-04-05 02:09:16 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return ipNet.Contains(net.ParseIP(ip))
|
|
|
|
}
|
2024-04-05 09:25:28 +00:00
|
|
|
|
|
|
|
func IsValidSubnets(subnets string) error {
|
|
|
|
for _, subnet := range splitSubnets(subnets) {
|
|
|
|
if err := isValidSubnet(subnet); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func IsIpInSubnets(ctx context.Context, ip string, subnets string) bool {
|
|
|
|
for _, subnet := range splitSubnets(subnets) {
|
|
|
|
if isIpInSubnet(ctx, ip, subnet) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|