| 1 | package exitpolicy |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "net" |
| 10 | "net/http" |
| 11 | "strings" |
| 12 | "time" |
| 13 | _ "time/tzdata" |
| 14 | ) |
| 15 | |
| 16 | |
| 17 | |
| 18 | func Lookup(ctx context.Context, client *http.Client, address net.IP) (Location, error) { |
| 19 | providers := []struct{ name, url string }{ |
| 20 | {"ipwho.is", "https://ipwho.is/" + address.String() + "?fields=success,ip,country,country_code,region,region_code,city,timezone.id"}, |
| 21 | {"IP.SB", "https://api.ip.sb/geoip/" + address.String()}, |
| 22 | } |
| 23 | failures := make([]string, 0, len(providers)) |
| 24 | for _, provider := range providers { |
| 25 | if err := ctx.Err(); err != nil { |
| 26 | return Location{}, err |
| 27 | } |
| 28 | loc, err := queryLocation(ctx, client, provider.url, provider.name == "ipwho.is", address) |
| 29 | if err == nil { |
| 30 | return loc, nil |
| 31 | } |
| 32 | |
| 33 | |
| 34 | failures = append(failures, provider.name+":"+err.Error()) |
| 35 | } |
| 36 | if err := ctx.Err(); err != nil { |
| 37 | return Location{}, err |
| 38 | } |
| 39 | return Location{}, fmt.Errorf("已测得出口 IP,但位置查询均失败(%s);请重试或切换节点。未使用直连回退", strings.Join(failures, ";")) |
| 40 | } |
| 41 | |
| 42 | func queryLocation(ctx context.Context, client *http.Client, endpoint string, requireSuccess bool, address net.IP) (Location, error) { |
| 43 | ctx, cancel := context.WithTimeout(ctx, 8*time.Second) |
| 44 | defer cancel() |
| 45 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) |
| 46 | if err != nil { |
| 47 | return Location{}, errors.New("查询地址无效") |
| 48 | } |
| 49 | req.Header.Set("User-Agent", "Cage-network-check/1") |
| 50 | r, err := client.Do(req) |
| 51 | if err != nil { |
| 52 | return Location{}, errors.New("连接失败或超时") |
| 53 | } |
| 54 | defer r.Body.Close() |
| 55 | if r.StatusCode != http.StatusOK { |
| 56 | return Location{}, fmt.Errorf("HTTP %d", r.StatusCode) |
| 57 | } |
| 58 | var v struct { |
| 59 | Success *bool `json:"success"` |
| 60 | IP string `json:"ip"` |
| 61 | Country string `json:"country"` |
| 62 | CountryCode string `json:"country_code"` |
| 63 | Region string `json:"region"` |
| 64 | RegionCode string `json:"region_code"` |
| 65 | City string `json:"city"` |
| 66 | Timezone json.RawMessage `json:"timezone"` |
| 67 | } |
| 68 | if json.NewDecoder(io.LimitReader(r.Body, 128<<10)).Decode(&v) != nil || |
| 69 | (requireSuccess && (v.Success == nil || !*v.Success)) || |
| 70 | net.ParseIP(v.IP) == nil || !net.ParseIP(v.IP).Equal(address) { |
| 71 | return Location{}, errors.New("响应无效或 IP 不匹配") |
| 72 | } |
| 73 | country := strings.ToUpper(strings.TrimSpace(v.CountryCode)) |
| 74 | if len(country) != 2 || country[0] < 'A' || country[0] > 'Z' || country[1] < 'A' || country[1] > 'Z' { |
| 75 | return Location{}, errors.New("缺少有效国家或地区") |
| 76 | } |
| 77 | var timezone string |
| 78 | if requireSuccess { |
| 79 | var zone struct { |
| 80 | ID string `json:"id"` |
| 81 | } |
| 82 | if json.Unmarshal(v.Timezone, &zone) == nil { |
| 83 | timezone = zone.ID |
| 84 | } |
| 85 | } else { |
| 86 | _ = json.Unmarshal(v.Timezone, &timezone) |
| 87 | } |
| 88 | if timezone == "" || timezone == "Local" { |
| 89 | return Location{}, errors.New("缺少有效时区") |
| 90 | } |
| 91 | if _, err = time.LoadLocation(timezone); err != nil { |
| 92 | return Location{}, errors.New("缺少有效时区") |
| 93 | } |
| 94 | return Location{IP: address.String(), Country: v.Country, CountryCode: country, Region: v.Region, RegionCode: v.RegionCode, City: v.City, Timezone: timezone, CheckedAt: time.Now()}, nil |
| 95 | } |