290 lines
7.9 KiB
Go
290 lines
7.9 KiB
Go
package proxy
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
var whitelistIPRegex = regexp.MustCompile(`\b(?:\d{1,3}\.){3}\d{1,3}\b`)
|
|
|
|
// Endpoint 是代理提供商返回的一条可连接代理。
|
|
type Endpoint struct {
|
|
URL string
|
|
IP string
|
|
Port string
|
|
Region string
|
|
Protocol string
|
|
Username string
|
|
Password string
|
|
Provider string
|
|
ExpiresAt time.Time
|
|
}
|
|
|
|
// Provider 把不同代理平台的参数规则与响应格式隔离在各自实现中。
|
|
type Provider interface {
|
|
ID() string
|
|
Match(*url.URL) bool
|
|
RequestURL(apiURL string, count int) (string, error)
|
|
Parse(apiURL string, body []byte) ([]Endpoint, error)
|
|
}
|
|
|
|
// WhitelistConfig 是代理平台自动白名单所需参数。
|
|
type WhitelistConfig struct {
|
|
APIURL string
|
|
IP string
|
|
LoginPassword string
|
|
SignKey string
|
|
ReplaceOldest bool
|
|
AutoWhitelist bool
|
|
}
|
|
|
|
// WhitelistProvider 由支持自动白名单的代理平台实现。
|
|
type WhitelistProvider interface {
|
|
Provider
|
|
EnsureWhitelist(context.Context, *http.Client, WhitelistConfig) error
|
|
AddWhitelist(context.Context, *http.Client, WhitelistConfig) error
|
|
}
|
|
|
|
// ProviderError 是代理平台返回的业务错误。
|
|
type ProviderError struct {
|
|
Provider string
|
|
Message string
|
|
Fatal bool
|
|
}
|
|
|
|
func (e *ProviderError) Error() string {
|
|
if e == nil {
|
|
return ""
|
|
}
|
|
if e.Provider == "" {
|
|
return e.Message
|
|
}
|
|
return e.Provider + ": " + e.Message
|
|
}
|
|
|
|
// IsFatal 判断错误是否重试也不会恢复,例如密钥错误、白名单缺失或套餐过期。
|
|
func IsFatal(err error) bool {
|
|
var providerErr *ProviderError
|
|
return errors.As(err, &providerErr) && providerErr.Fatal
|
|
}
|
|
|
|
// Service 负责通用 HTTP 请求、provider 选择和结果去重。
|
|
type Service struct {
|
|
client *http.Client
|
|
providers []Provider
|
|
}
|
|
|
|
func NewService() *Service {
|
|
return NewServiceWithProviders(
|
|
&http.Client{Timeout: 10 * time.Second},
|
|
NewIPZanProvider(),
|
|
NewGenericProvider(),
|
|
)
|
|
}
|
|
|
|
func NewServiceWithProviders(client *http.Client, providers ...Provider) *Service {
|
|
if client == nil {
|
|
client = &http.Client{Timeout: 10 * time.Second}
|
|
}
|
|
return &Service{client: client, providers: providers}
|
|
}
|
|
|
|
// Extract 自动识别代理平台并请求所需数量;调用方可用剩余数量再次提取补足。
|
|
func (s *Service) Extract(ctx context.Context, apiURL string, count int) ([]Endpoint, error) {
|
|
if count <= 0 {
|
|
count = 1
|
|
}
|
|
u, err := url.Parse(strings.TrimSpace(apiURL))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("代理 API 地址无效: %w", err)
|
|
}
|
|
if u.Scheme != "http" && u.Scheme != "https" {
|
|
return nil, errors.New("代理 API 地址必须以 http:// 或 https:// 开头")
|
|
}
|
|
provider := s.providerFor(u)
|
|
if provider == nil {
|
|
return nil, errors.New("没有匹配的代理提供商")
|
|
}
|
|
|
|
requestURL, err := provider.RequestURL(apiURL, count)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
body, err := s.fetch(ctx, requestURL)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
endpoints, err := provider.Parse(apiURL, body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for i := range endpoints {
|
|
if endpoints[i].Provider == "" {
|
|
endpoints[i].Provider = provider.ID()
|
|
}
|
|
}
|
|
endpoints = dedupeEndpoints(endpoints, count)
|
|
if len(endpoints) == 0 {
|
|
return nil, errors.New("代理 API 返回的代理均已过期或无效")
|
|
}
|
|
return endpoints, nil
|
|
}
|
|
|
|
func (s *Service) ExtractOne(ctx context.Context, apiURL string) (Endpoint, error) {
|
|
endpoints, err := s.Extract(ctx, apiURL, 1)
|
|
if err != nil {
|
|
return Endpoint{}, err
|
|
}
|
|
if len(endpoints) == 0 {
|
|
return Endpoint{}, errors.New("代理 API 未返回有效地址")
|
|
}
|
|
return endpoints[0], nil
|
|
}
|
|
|
|
// EnsureWhitelist 自动把指定公网 IP 加入当前 API 套餐白名单;已存在时直接跳过。
|
|
func (s *Service) EnsureWhitelist(ctx context.Context, cfg WhitelistConfig) error {
|
|
u, err := url.Parse(strings.TrimSpace(cfg.APIURL))
|
|
if err != nil {
|
|
return fmt.Errorf("代理 API 地址无效: %w", err)
|
|
}
|
|
provider := s.providerFor(u)
|
|
manager, ok := provider.(WhitelistProvider)
|
|
if !ok {
|
|
return errors.New("当前代理提供商不支持自动白名单")
|
|
}
|
|
return manager.EnsureWhitelist(ctx, s.client, cfg)
|
|
}
|
|
|
|
// AddWhitelist 直接添加白名单,不再调用独立的 verify 接口。
|
|
func (s *Service) AddWhitelist(ctx context.Context, cfg WhitelistConfig) error {
|
|
u, err := url.Parse(strings.TrimSpace(cfg.APIURL))
|
|
if err != nil {
|
|
return fmt.Errorf("代理 API 地址无效: %w", err)
|
|
}
|
|
provider := s.providerFor(u)
|
|
manager, ok := provider.(WhitelistProvider)
|
|
if !ok {
|
|
return errors.New("当前代理提供商不支持自动白名单")
|
|
}
|
|
return manager.AddWhitelist(ctx, s.client, cfg)
|
|
}
|
|
|
|
// ExtractWithWhitelist 先探测提取;若平台提示当前 IP 不在白名单,则直接使用错误中
|
|
// 平台实际看到的来源 IP,添加后重试,避免第三方公网 IP 探测与实际出口不一致。
|
|
func (s *Service) ExtractWithWhitelist(ctx context.Context, apiURL string, count int, cfg WhitelistConfig) ([]Endpoint, error) {
|
|
endpoints, err := s.Extract(ctx, apiURL, count)
|
|
if err == nil || !cfg.AutoWhitelist {
|
|
return endpoints, err
|
|
}
|
|
ip, ok := whitelistIPFromError(err)
|
|
if !ok {
|
|
return nil, err
|
|
}
|
|
cfg.APIURL = apiURL
|
|
cfg.IP = ip
|
|
if addErr := s.AddWhitelist(ctx, cfg); addErr != nil {
|
|
return nil, fmt.Errorf("品赞要求添加白名单 IP %s,自动添加失败: %w", ip, addErr)
|
|
}
|
|
return s.Extract(ctx, apiURL, count)
|
|
}
|
|
|
|
func whitelistIPFromError(err error) (string, bool) {
|
|
if err == nil || !strings.Contains(err.Error(), "白名单") {
|
|
return "", false
|
|
}
|
|
ip := whitelistIPRegex.FindString(err.Error())
|
|
return ip, ip != ""
|
|
}
|
|
|
|
func (s *Service) providerFor(u *url.URL) Provider {
|
|
for _, provider := range s.providers {
|
|
if provider != nil && provider.Match(u) {
|
|
return provider
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Service) fetch(ctx context.Context, rawURL string) ([]byte, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("创建代理 API 请求失败: %w", err)
|
|
}
|
|
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
|
|
resp, err := s.client.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("请求代理 API 失败: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 128*1024))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("读取代理 API 响应失败: %w", err)
|
|
}
|
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
|
return nil, fmt.Errorf("代理 API HTTP %d: %s", resp.StatusCode, truncateText(string(body), 160))
|
|
}
|
|
return body, nil
|
|
}
|
|
|
|
func dedupeEndpoints(endpoints []Endpoint, limit int) []Endpoint {
|
|
out := make([]Endpoint, 0, min(len(endpoints), limit))
|
|
seen := make(map[string]struct{}, len(endpoints))
|
|
for _, endpoint := range endpoints {
|
|
endpoint.URL = strings.TrimSpace(endpoint.URL)
|
|
if endpoint.URL == "" {
|
|
continue
|
|
}
|
|
if !endpoint.ExpiresAt.IsZero() && !time.Now().Before(endpoint.ExpiresAt) {
|
|
continue
|
|
}
|
|
if _, ok := seen[endpoint.URL]; ok {
|
|
continue
|
|
}
|
|
seen[endpoint.URL] = struct{}{}
|
|
out = append(out, endpoint)
|
|
if len(out) >= limit {
|
|
break
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func buildProxyURL(protocol, ip, port, username, password string) string {
|
|
scheme := "http"
|
|
if protocol == "3" || strings.EqualFold(protocol, "socks5") || strings.EqualFold(protocol, "socket5") {
|
|
scheme = "socks5"
|
|
}
|
|
auth := ""
|
|
if username != "" || password != "" {
|
|
auth = url.UserPassword(username, password).String() + "@"
|
|
}
|
|
return fmt.Sprintf("%s://%s%s:%s", scheme, auth, strings.TrimSpace(ip), strings.TrimSpace(port))
|
|
}
|
|
|
|
func protocolFromAPI(apiURL string) string {
|
|
u, err := url.Parse(apiURL)
|
|
if err != nil {
|
|
return "1"
|
|
}
|
|
if value := strings.TrimSpace(u.Query().Get("protocol")); value != "" {
|
|
return value
|
|
}
|
|
return "1"
|
|
}
|
|
|
|
func truncateText(value string, maxLen int) string {
|
|
runes := []rune(strings.TrimSpace(value))
|
|
if len(runes) <= maxLen {
|
|
return string(runes)
|
|
}
|
|
return string(runes[:maxLen]) + "..."
|
|
}
|