294 lines
9.1 KiB
Go
294 lines
9.1 KiB
Go
package proxy
|
|
|
|
import (
|
|
"context"
|
|
"crypto/aes"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// IPZanProvider 接入品赞 https://service.ipzan.com/core-extract。
|
|
type IPZanProvider struct {
|
|
baseURL string
|
|
now func() time.Time
|
|
}
|
|
|
|
func NewIPZanProvider() *IPZanProvider {
|
|
return &IPZanProvider{
|
|
baseURL: "https://service.ipzan.com",
|
|
now: time.Now,
|
|
}
|
|
}
|
|
|
|
func (p *IPZanProvider) ID() string {
|
|
return "ipzan"
|
|
}
|
|
|
|
func (p *IPZanProvider) Match(u *url.URL) bool {
|
|
return u != nil &&
|
|
strings.EqualFold(u.Hostname(), "service.ipzan.com") &&
|
|
strings.TrimRight(u.Path, "/") == "/core-extract"
|
|
}
|
|
|
|
func (p *IPZanProvider) RequestURL(apiURL string, count int) (string, error) {
|
|
u, err := url.Parse(strings.TrimSpace(apiURL))
|
|
if err != nil {
|
|
return "", fmt.Errorf("品赞 API 地址无效: %w", err)
|
|
}
|
|
query := u.Query()
|
|
query.Set("num", strconv.Itoa(count))
|
|
u.RawQuery = query.Encode()
|
|
return u.String(), nil
|
|
}
|
|
|
|
func (p *IPZanProvider) Parse(apiURL string, body []byte) ([]Endpoint, error) {
|
|
text := strings.TrimSpace(string(body))
|
|
if text == "" {
|
|
return nil, &ProviderError{Provider: "品赞", Message: "API 返回内容为空", Fatal: false}
|
|
}
|
|
|
|
var payload struct {
|
|
Code *int `json:"code"`
|
|
Status int `json:"status"`
|
|
Message string `json:"message"`
|
|
Info string `json:"info"`
|
|
Msg string `json:"msg"`
|
|
Data json.RawMessage `json:"data"`
|
|
}
|
|
if json.Unmarshal(body, &payload) == nil {
|
|
if payload.Code != nil && *payload.Code != 0 {
|
|
message := firstNonEmpty(payload.Message, payload.Info, payload.Msg, "品赞返回未知错误")
|
|
return nil, &ProviderError{
|
|
Provider: "品赞",
|
|
Message: fmt.Sprintf("%s (code=%d)", message, *payload.Code),
|
|
Fatal: isIPZanFatalMessage(message),
|
|
}
|
|
}
|
|
if len(payload.Data) > 0 {
|
|
endpoints := parseEndpointJSON(payload.Data, protocolFromAPI(apiURL))
|
|
if len(endpoints) > 0 {
|
|
return endpoints, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
endpoints := parseEndpointText(text, protocolFromAPI(apiURL))
|
|
if len(endpoints) == 0 {
|
|
return nil, &ProviderError{
|
|
Provider: "品赞",
|
|
Message: "未能识别有效 IP:端口,原始返回: " + truncateText(text, 120),
|
|
Fatal: false,
|
|
}
|
|
}
|
|
return endpoints, nil
|
|
}
|
|
|
|
func (p *IPZanProvider) EnsureWhitelist(ctx context.Context, httpClient *http.Client, cfg WhitelistConfig) error {
|
|
if strings.TrimSpace(cfg.IP) == "" {
|
|
return &ProviderError{Provider: "品赞", Message: "自动白名单缺少公网 IP", Fatal: true}
|
|
}
|
|
apiURL, err := url.Parse(strings.TrimSpace(cfg.APIURL))
|
|
if err != nil {
|
|
return fmt.Errorf("品赞 API 地址无效: %w", err)
|
|
}
|
|
no := strings.TrimSpace(apiURL.Query().Get("no"))
|
|
secret := strings.TrimSpace(apiURL.Query().Get("secret"))
|
|
if no == "" || secret == "" {
|
|
return &ProviderError{Provider: "品赞", Message: "提取 API 缺少 no 或 secret,无法自动加白名单", Fatal: true}
|
|
}
|
|
if strings.TrimSpace(cfg.LoginPassword) == "" || strings.TrimSpace(cfg.SignKey) == "" {
|
|
return &ProviderError{Provider: "品赞", Message: "自动白名单需要品赞登录密码和签名密钥", Fatal: true}
|
|
}
|
|
|
|
exists, err := p.verifyWhitelist(ctx, httpClient, no, cfg.IP)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if exists {
|
|
return nil
|
|
}
|
|
return p.AddWhitelist(ctx, httpClient, cfg)
|
|
}
|
|
|
|
func (p *IPZanProvider) AddWhitelist(ctx context.Context, httpClient *http.Client, cfg WhitelistConfig) error {
|
|
if strings.TrimSpace(cfg.IP) == "" {
|
|
return &ProviderError{Provider: "品赞", Message: "自动白名单缺少公网 IP", Fatal: true}
|
|
}
|
|
apiURL, err := url.Parse(strings.TrimSpace(cfg.APIURL))
|
|
if err != nil {
|
|
return fmt.Errorf("品赞 API 地址无效: %w", err)
|
|
}
|
|
no := strings.TrimSpace(apiURL.Query().Get("no"))
|
|
secret := strings.TrimSpace(apiURL.Query().Get("secret"))
|
|
if no == "" || secret == "" {
|
|
return &ProviderError{Provider: "品赞", Message: "提取 API 缺少 no 或 secret,无法自动加白名单", Fatal: true}
|
|
}
|
|
if strings.TrimSpace(cfg.LoginPassword) == "" || strings.TrimSpace(cfg.SignKey) == "" {
|
|
return &ProviderError{Provider: "品赞", Message: "自动白名单需要品赞登录密码和签名密钥", Fatal: true}
|
|
}
|
|
sign, err := p.signWhitelist(cfg.LoginPassword, secret, cfg.SignKey)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
form := url.Values{}
|
|
form.Set("no", no)
|
|
form.Set("sign", sign)
|
|
form.Set("ip", cfg.IP)
|
|
if cfg.ReplaceOldest {
|
|
form.Set("replace", "1")
|
|
} else {
|
|
form.Set("replace", "0")
|
|
}
|
|
req, err := http.NewRequestWithContext(
|
|
ctx,
|
|
http.MethodPost,
|
|
strings.TrimRight(p.baseURL, "/")+"/whiteList-add",
|
|
strings.NewReader(form.Encode()),
|
|
)
|
|
if err != nil {
|
|
return fmt.Errorf("创建品赞白名单请求失败: %w", err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
if err := p.doWhitelistRequest(req, httpClient, "添加白名单"); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *IPZanProvider) verifyWhitelist(ctx context.Context, httpClient *http.Client, no, ip string) (bool, error) {
|
|
endpoint, err := url.Parse(strings.TrimRight(p.baseURL, "/") + "/whiteList-verify")
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
query := endpoint.Query()
|
|
query.Set("no", no)
|
|
query.Set("ip", ip)
|
|
endpoint.RawQuery = query.Encode()
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil)
|
|
if err != nil {
|
|
return false, fmt.Errorf("创建品赞白名单校验请求失败: %w", err)
|
|
}
|
|
body, err := p.doWhitelistRequestData(req, httpClient, "校验白名单")
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
var payload struct {
|
|
Code *int `json:"code"`
|
|
Data json.RawMessage `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(body, &payload); err != nil {
|
|
return false, fmt.Errorf("解析品赞白名单校验响应失败: %w", err)
|
|
}
|
|
if payload.Code == nil || *payload.Code != 0 {
|
|
return false, &ProviderError{Provider: "品赞", Message: "白名单校验失败", Fatal: true}
|
|
}
|
|
var exists bool
|
|
if json.Unmarshal(payload.Data, &exists) == nil {
|
|
return exists, nil
|
|
}
|
|
var existsText string
|
|
if json.Unmarshal(payload.Data, &existsText) == nil {
|
|
return strings.EqualFold(strings.TrimSpace(existsText), "true"), nil
|
|
}
|
|
return false, fmt.Errorf("品赞白名单校验响应格式无法识别: %s", truncateText(string(body), 120))
|
|
}
|
|
|
|
func (p *IPZanProvider) signWhitelist(loginPassword, secret, signKey string) (string, error) {
|
|
key := []byte(signKey)
|
|
switch len(key) {
|
|
case 16, 24, 32:
|
|
default:
|
|
return "", &ProviderError{
|
|
Provider: "品赞",
|
|
Message: fmt.Sprintf("签名密钥长度无效: %d,应为 16/24/32 字节", len(key)),
|
|
Fatal: true,
|
|
}
|
|
}
|
|
plain := fmt.Sprintf("%s:%s:%d", loginPassword, secret, p.now().Unix())
|
|
block, err := aes.NewCipher(key)
|
|
if err != nil {
|
|
return "", fmt.Errorf("初始化 AES 签名失败: %w", err)
|
|
}
|
|
padding := block.BlockSize() - len(plain)%block.BlockSize()
|
|
data := make([]byte, 0, len(plain)+padding)
|
|
data = append(data, []byte(plain)...)
|
|
for i := 0; i < padding; i++ {
|
|
data = append(data, byte(padding))
|
|
}
|
|
encrypted := make([]byte, len(data))
|
|
for offset := 0; offset < len(data); offset += block.BlockSize() {
|
|
block.Encrypt(encrypted[offset:offset+block.BlockSize()], data[offset:offset+block.BlockSize()])
|
|
}
|
|
return hex.EncodeToString(encrypted), nil
|
|
}
|
|
|
|
func (p *IPZanProvider) doWhitelistRequest(req *http.Request, httpClient *http.Client, action string) error {
|
|
body, err := p.doWhitelistRequestData(req, httpClient, action)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var payload struct {
|
|
Code *int `json:"code"`
|
|
Message string `json:"message"`
|
|
}
|
|
if err := json.Unmarshal(body, &payload); err != nil {
|
|
return fmt.Errorf("解析品赞%s响应失败: %w", action, err)
|
|
}
|
|
if payload.Code == nil || *payload.Code != 0 {
|
|
message := firstNonEmpty(payload.Message, "品赞返回未知错误")
|
|
return &ProviderError{
|
|
Provider: "品赞",
|
|
Message: action + "失败: " + message,
|
|
Fatal: isIPZanFatalMessage(message),
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *IPZanProvider) doWhitelistRequestData(req *http.Request, httpClient *http.Client, action string) ([]byte, error) {
|
|
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
|
|
resp, err := httpClient.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("请求品赞%s接口失败: %w", action, err)
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("读取品赞%s响应失败: %w", action, err)
|
|
}
|
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
|
return nil, fmt.Errorf("品赞%s接口 HTTP %d: %s", action, resp.StatusCode, truncateText(string(body), 120))
|
|
}
|
|
return body, nil
|
|
}
|
|
|
|
func isIPZanFatalMessage(message string) bool {
|
|
if strings.Contains(message, "提取频率过快") {
|
|
return false
|
|
}
|
|
for _, hint := range []string{
|
|
"白名单", "secret", "密匙", "密钥", "套餐", "过期", "禁用", "余额", "身份未认证", "用户被禁用",
|
|
} {
|
|
if strings.Contains(strings.ToLower(message), strings.ToLower(hint)) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func firstNonEmpty(values ...string) string {
|
|
for _, value := range values {
|
|
if strings.TrimSpace(value) != "" {
|
|
return strings.TrimSpace(value)
|
|
}
|
|
}
|
|
return ""
|
|
}
|