| 1 | package exitpolicy |
| 2 | |
| 3 | import ( |
| 4 | _ "embed" |
| 5 | "fmt" |
| 6 | "net/netip" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | var mainlandIPv4 string |
| 15 | |
| 16 | var mainlandPrefixes, mainlandListError = parseMainlandPrefixes(mainlandIPv4) |
| 17 | |
| 18 | func parseMainlandPrefixes(data string) ([]netip.Prefix, error) { |
| 19 | var prefixes []netip.Prefix |
| 20 | for _, line := range strings.Fields(data) { |
| 21 | prefix, err := netip.ParsePrefix(line) |
| 22 | if err != nil || !prefix.Addr().Is4() || prefix.Bits() < 8 || prefix != prefix.Masked() { |
| 23 | return nil, fmt.Errorf("invalid bundled mainland prefix %q", line) |
| 24 | } |
| 25 | prefixes = append(prefixes, prefix) |
| 26 | } |
| 27 | if len(prefixes) == 0 { |
| 28 | return nil, fmt.Errorf("bundled mainland prefix list is empty") |
| 29 | } |
| 30 | return prefixes, nil |
| 31 | } |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | func CheckExitCountry(ip string, location *Location) (State, string) { |
| 37 | address, err := netip.ParseAddr(ip) |
| 38 | if err != nil || !address.Is4() || !address.IsGlobalUnicast() || address.IsPrivate() { |
| 39 | return Unknown, "尚未取得有效的检测出口" |
| 40 | } |
| 41 | if mainlandListError != nil { |
| 42 | return Unknown, "大陆出口网段库不可用,外网保持关闭" |
| 43 | } |
| 44 | for _, prefix := range mainlandPrefixes { |
| 45 | if prefix.Contains(address) { |
| 46 | return Failed, "检测出口命中中国大陆 IP 网段,Cage 禁止使用大陆出口,外网保持关闭" |
| 47 | } |
| 48 | } |
| 49 | if location == nil || location.IP != address.String() { |
| 50 | return Unknown, "无法确认出口国家或地区,外网保持关闭" |
| 51 | } |
| 52 | country := strings.ToUpper(strings.TrimSpace(location.CountryCode)) |
| 53 | if len(country) != 2 || country[0] < 'A' || country[0] > 'Z' || country[1] < 'A' || country[1] > 'Z' || country == "ZZ" || country == "XX" { |
| 54 | return Unknown, "无法确认出口国家或地区,外网保持关闭" |
| 55 | } |
| 56 | if country == "CN" { |
| 57 | return Failed, "检测出口位于中国大陆,Cage 禁止使用大陆出口,外网保持关闭" |
| 58 | } |
| 59 | return Passed, "检测出口未命中大陆网段,国家或地区信息符合非大陆出口要求" |
| 60 | } |