1045 lines
27 KiB
Go
1045 lines
27 KiB
Go
package cmnet
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/cookiejar"
|
|
"net/url"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
loginOrigin = "https://login.10086.cn"
|
|
shopOrigin = "https://shop.10086.cn"
|
|
backURL = "https://shop.10086.cn/i/?f=packremainqry"
|
|
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36 Edg/155.0.0.0"
|
|
)
|
|
|
|
var (
|
|
ErrNeedLogin = errors.New("会话已失效")
|
|
provRE = regexp.MustCompile(`dt\[(\d+)\]="([^"]*)"`)
|
|
loginChannelRE = regexp.MustCompile(`https://login\.10086\.cn/login\.html\?channelID=(\d+)`)
|
|
scriptSrcRE = regexp.MustCompile(`(?i)src=["']([^"']+)["']`)
|
|
)
|
|
|
|
type Cookie struct {
|
|
Name string `json:"name"`
|
|
Value string `json:"value"`
|
|
Domain string `json:"domain"`
|
|
Path string `json:"path"`
|
|
}
|
|
|
|
type LoginResult struct {
|
|
Phone string
|
|
ProvCode string
|
|
ProvName string
|
|
}
|
|
|
|
type Client struct {
|
|
mu sync.Mutex
|
|
http *http.Client
|
|
jar *cookiejar.Jar
|
|
crypto pageCrypto
|
|
channelID string
|
|
provinces map[string]string
|
|
qrToken string
|
|
qrChannel string
|
|
hosts []string
|
|
portal string
|
|
scanBase string
|
|
}
|
|
|
|
func New() *Client {
|
|
jar, err := cookiejar.New(nil)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return &Client{
|
|
jar: jar,
|
|
http: &http.Client{
|
|
Timeout: 30 * time.Second,
|
|
Jar: jar,
|
|
},
|
|
}
|
|
}
|
|
|
|
func (c *Client) loginPage() string {
|
|
return loginOrigin + "/login.html?channelID=" + c.channelID + "&backUrl=" + url.QueryEscape(backURL)
|
|
}
|
|
|
|
func (c *Client) ProvinceName(code string) string {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.provinceNameLocked(code)
|
|
}
|
|
|
|
func (c *Client) provinceNameLocked(code string) string {
|
|
if len(c.provinces) == 0 {
|
|
return ""
|
|
}
|
|
if name, ok := c.provinces[code]; ok {
|
|
return name
|
|
}
|
|
if code == "" {
|
|
return "中国移动"
|
|
}
|
|
return "中国移动 " + code
|
|
}
|
|
|
|
func (c *Client) Prepare(ctx context.Context) error {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.ensureKeys(ctx)
|
|
}
|
|
|
|
func (c *Client) Captcha(ctx context.Context) ([]byte, string, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if err := c.ensureKeys(ctx); err != nil {
|
|
return nil, "", err
|
|
}
|
|
if err := c.bootstrap(ctx); err != nil {
|
|
return nil, "", err
|
|
}
|
|
rawURL := loginOrigin + "/captchazh.htm?type=12×tamp=" + milli()
|
|
body, ctype, err := c.get(ctx, rawURL, c.loginPage())
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
if !strings.Contains(ctype, "image") && !(len(body) > 4 && body[0] == 0x89) && !(len(body) > 2 && body[0] == 0xff) {
|
|
return nil, "", errors.New("没有拿到图形验证码")
|
|
}
|
|
if ctype == "" {
|
|
ctype = "image/png"
|
|
}
|
|
debugf("图形验证码已获取 %d 字节", len(body))
|
|
return body, ctype, nil
|
|
}
|
|
|
|
func (c *Client) SendSMS(ctx context.Context, phone, imageCode string) (string, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if err := c.ensureKeys(ctx); err != nil {
|
|
return "", err
|
|
}
|
|
c.dropAccountSession()
|
|
debugf("发送短信 phone=%s 图形验证码=%s", phone, imageCode)
|
|
c.debugCookies("发送短信前")
|
|
encPhone, err := c.crypto.encryptLogin(phone)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
encCode, err := c.crypto.encryptLogin(imageCode)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
vbody, err := c.postForm(ctx, loginOrigin+"/verifyCaptcha.htm", url.Values{"inputCode": {imageCode}})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var captchaRes struct {
|
|
ResultCode string `json:"resultCode"`
|
|
}
|
|
_ = json.Unmarshal(vbody, &captchaRes)
|
|
debugf("图形验证码校验 phone=%s 图形验证码=%s 原文=%s", phone, imageCode, string(vbody))
|
|
if captchaRes.ResultCode != "" && captchaRes.ResultCode != "0" {
|
|
return "", errors.New("图形验证码不正确")
|
|
}
|
|
if _, err := c.postForm(ctx, loginOrigin+"/chkNumberAction.action", url.Values{
|
|
"userName": {encPhone},
|
|
"loginMode": {"01"},
|
|
"channelID": {c.channelID},
|
|
}); err != nil {
|
|
return "", err
|
|
}
|
|
tokenBody, err := c.postForm(ctx, loginOrigin+"/loadToken.action", url.Values{"userName": {encPhone}})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var tokenRes struct {
|
|
RspCode string `json:"rspCode"`
|
|
RspDesc string `json:"rspDesc"`
|
|
Result string `json:"result"`
|
|
}
|
|
_ = json.Unmarshal(tokenBody, &tokenRes)
|
|
if tokenRes.Result == "" {
|
|
if tokenRes.RspDesc != "" {
|
|
return "", errors.New(tokenRes.RspDesc)
|
|
}
|
|
return "", errors.New("没有拿到短信发送凭证")
|
|
}
|
|
body, err := c.postFormHeader(ctx, loginOrigin+"/sendRandomCodeAction.action", url.Values{
|
|
"userName": {encPhone},
|
|
"inputCode": {encCode},
|
|
"type": {"01"},
|
|
"channelID": {c.channelID},
|
|
}, map[string]string{"Xa-before": tokenRes.Result})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
msg, err := smsMessage(strings.TrimSpace(string(body)))
|
|
debugf("短信发送结果 phone=%s 原文=%s", phone, string(body))
|
|
c.debugCookies("短信发送后")
|
|
return msg, err
|
|
}
|
|
|
|
func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode, deviceID string) (LoginResult, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if err := c.ensureKeys(ctx); err != nil {
|
|
return LoginResult{}, err
|
|
}
|
|
c.dropAccountSession()
|
|
debugf("短信登录 phone=%s 图形验证码=%s 短信验证码=%s AES密钥=%s", phone, imageCode, smsCode, string(c.crypto.aesKey))
|
|
c.debugCookies("短信登录前")
|
|
encPhone, err := c.crypto.encryptLogin(phone)
|
|
if err != nil {
|
|
return LoginResult{}, err
|
|
}
|
|
encSMS, err := c.crypto.encryptLogin(smsCode)
|
|
if err != nil {
|
|
return LoginResult{}, err
|
|
}
|
|
_, _ = c.postJSON(ctx, loginOrigin+"/fkRisk.action", map[string]string{
|
|
"account": encPhone,
|
|
"const_id": deviceID,
|
|
"login_channel": c.channelID,
|
|
})
|
|
body, err := c.postForm(ctx, loginOrigin+"/login.htm", url.Values{
|
|
"accountType": {"01"},
|
|
"account": {encPhone},
|
|
"password": {encSMS},
|
|
"pwdType": {"02"},
|
|
"email_sms": {""},
|
|
"smsPwd": {"false"},
|
|
"inputCode": {imageCode},
|
|
"backUrl": {backURL},
|
|
"rememberMe": {"1"},
|
|
"channelID": {c.channelID},
|
|
"loginMode": {"01"},
|
|
"protocol": {"https:"},
|
|
"deviceId": {deviceID},
|
|
"deviceIdSource": {"fingerprint"},
|
|
"timestamp": {milli()},
|
|
})
|
|
if err != nil {
|
|
return LoginResult{}, err
|
|
}
|
|
var loginRes struct {
|
|
Code string `json:"code"`
|
|
Desc string `json:"desc"`
|
|
Artifact string `json:"artifact"`
|
|
Type string `json:"type"`
|
|
ResultCode string `json:"resultCode"`
|
|
ResultDesc string `json:"resultDesc"`
|
|
}
|
|
if err := json.Unmarshal(body, &loginRes); err != nil {
|
|
debugf("短信登录结果无法解析 phone=%s 原文=%s", phone, string(body))
|
|
return LoginResult{}, errors.New("登录结果无法解析")
|
|
}
|
|
if loginRes.Code == "" {
|
|
loginRes.Code = loginRes.ResultCode
|
|
}
|
|
if loginRes.Desc == "" {
|
|
loginRes.Desc = loginRes.ResultDesc
|
|
}
|
|
if loginRes.Code != "0000" || loginRes.Artifact == "" {
|
|
debugf("短信登录被拒绝 phone=%s code=%s desc=%s 原文=%s", phone, loginRes.Code, loginRes.Desc, string(body))
|
|
if loginRes.Desc != "" {
|
|
return LoginResult{}, errors.New(loginRes.Desc)
|
|
}
|
|
if loginRes.Code != "" {
|
|
return LoginResult{}, fmt.Errorf("登录失败 %s", loginRes.Code)
|
|
}
|
|
return LoginResult{}, errors.New("登录失败")
|
|
}
|
|
typ := loginRes.Type
|
|
if typ == "" {
|
|
typ = "00"
|
|
}
|
|
debugf("短信登录已通过 phone=%s type=%s artifact=%s", phone, typ, loginRes.Artifact)
|
|
if err := c.exchangeArtifact(ctx, loginRes.Artifact, "", typ); err != nil {
|
|
debugf("交换登录凭证失败 phone=%s %v", phone, err)
|
|
c.debugCookies("交换凭证失败")
|
|
return LoginResult{}, err
|
|
}
|
|
c.debugCookies("交换凭证后")
|
|
info, err := c.loginfo(ctx)
|
|
if err != nil {
|
|
debugf("读取登录资料失败 phone=%s %s", phone, err.Error())
|
|
c.debugCookies("读取资料失败")
|
|
return LoginResult{}, err
|
|
}
|
|
debugf("登录资料 phone=%s loginValue=%s safeCode=%s provice=%s province=%s", phone, asString(info["loginValue"]), asString(info["safeCode"]), asString(info["provice"]), asString(info["province"]))
|
|
prov := asString(info["provice"])
|
|
if prov == "" {
|
|
prov = asString(info["province"])
|
|
}
|
|
return LoginResult{Phone: phone, ProvCode: prov, ProvName: c.provinceNameLocked(prov)}, nil
|
|
}
|
|
|
|
type QRStatus struct {
|
|
Waiting bool
|
|
Expired bool
|
|
AssertURL string
|
|
Result LoginResult
|
|
}
|
|
|
|
func (c *Client) QRCode(ctx context.Context) ([]byte, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if err := c.ensureKeys(ctx); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, _, err := c.get(ctx, c.loginPage(), c.loginPage()); err != nil {
|
|
return nil, err
|
|
}
|
|
c.clearLoginCookies()
|
|
body, ctype, err := c.get(ctx, loginOrigin+"/genqr.htm?timestamp="+milli(), c.loginPage())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !strings.Contains(ctype, "image") && !(len(body) > 4 && body[0] == 0x89) {
|
|
return nil, errors.New("没有拿到登录二维码")
|
|
}
|
|
if c.qrToken == "" {
|
|
c.qrToken = c.cookieNamed("lgToken")
|
|
}
|
|
if c.qrToken == "" {
|
|
return nil, errors.New("没有拿到扫码凭证")
|
|
}
|
|
debugf("扫码凭证 lgToken=%s", c.qrToken)
|
|
c.debugCookies("二维码")
|
|
_, _ = c.postForm(ctx, loginOrigin+"/checkBackUrl", url.Values{
|
|
"backUrl": {backURL},
|
|
"channelID": {c.channelID},
|
|
})
|
|
_, _ = c.postForm(ctx, loginOrigin+"/checkUidAvailable.action", url.Values{})
|
|
return c.usableQR(ctx, body), nil
|
|
}
|
|
|
|
func (c *Client) PollQR(ctx context.Context) (QRStatus, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if c.qrToken == "" {
|
|
c.qrToken = c.cookieNamed("lgToken")
|
|
}
|
|
if c.qrToken == "" {
|
|
return QRStatus{}, errors.New("请先获取二维码")
|
|
}
|
|
if err := c.ensureKeys(ctx); err != nil {
|
|
return QRStatus{}, err
|
|
}
|
|
status, artifact, err := c.pollChannels(ctx)
|
|
if err != nil {
|
|
return QRStatus{}, err
|
|
}
|
|
if status.Expired || status.Waiting || artifact == "" {
|
|
return status, nil
|
|
}
|
|
if err := c.exchangeArtifact(ctx, artifact, status.AssertURL, ""); err != nil {
|
|
return QRStatus{}, err
|
|
}
|
|
info, err := c.loginfo(ctx)
|
|
if err != nil {
|
|
return QRStatus{}, err
|
|
}
|
|
phone, err := restorePhone(asString(info["loginValue"]), asString(info["safeCode"]))
|
|
if err != nil {
|
|
return QRStatus{}, err
|
|
}
|
|
prov := asString(info["provice"])
|
|
if prov == "" {
|
|
prov = asString(info["province"])
|
|
}
|
|
status.Result = LoginResult{Phone: phone, ProvCode: prov, ProvName: c.provinceNameLocked(prov)}
|
|
c.qrToken = ""
|
|
return status, nil
|
|
}
|
|
|
|
func (c *Client) exchangeArtifact(ctx context.Context, artifact, assertURL, typ string) error {
|
|
if assertURL == "" || !sameSite(shopOrigin, assertURL) {
|
|
assertURL = shopOrigin + "/i/v1/auth/getArtifact"
|
|
}
|
|
art, err := url.Parse(assertURL)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
q := art.Query()
|
|
q.Set("backUrl", backURL)
|
|
q.Set("artifact", artifact)
|
|
if typ != "" {
|
|
q.Set("type", typ)
|
|
}
|
|
art.RawQuery = q.Encode()
|
|
_, _, err = c.get(ctx, art.String(), c.loginPage())
|
|
return err
|
|
}
|
|
|
|
func (c *Client) pollChannels(ctx context.Context) (QRStatus, string, error) {
|
|
channels := []string{}
|
|
if c.channelID != "" {
|
|
channels = append(channels, c.channelID)
|
|
}
|
|
if c.qrChannel != "" && c.qrChannel != c.channelID {
|
|
channels = append(channels, c.qrChannel)
|
|
}
|
|
if len(channels) == 0 {
|
|
channels = []string{""}
|
|
}
|
|
sawWait := false
|
|
var lastErr error
|
|
var fallback QRStatus
|
|
fallbackArtifact := ""
|
|
for _, channel := range channels {
|
|
body, err := c.postForm(ctx, loginOrigin+"/chkqr.htm", url.Values{
|
|
"lgToken": {c.qrToken},
|
|
"targetChannelID": {channel},
|
|
"backUrl": {url.QueryEscape(backURL)},
|
|
})
|
|
debugf("扫码轮询 channel=%s lgToken=%s err=%v 原文=%s", channel, c.qrToken, err, string(body))
|
|
if err != nil {
|
|
lastErr = err
|
|
continue
|
|
}
|
|
status, artifact, err := parseQRPoll(bytes.TrimSpace(body))
|
|
if err != nil {
|
|
lastErr = err
|
|
continue
|
|
}
|
|
if artifact != "" {
|
|
if shopArtifact(status.AssertURL) {
|
|
return status, artifact, nil
|
|
}
|
|
if fallbackArtifact == "" {
|
|
fallback = status
|
|
fallbackArtifact = artifact
|
|
}
|
|
continue
|
|
}
|
|
if status.Expired {
|
|
continue
|
|
}
|
|
sawWait = true
|
|
}
|
|
if fallbackArtifact != "" && !sawWait {
|
|
return fallback, fallbackArtifact, nil
|
|
}
|
|
if sawWait {
|
|
return QRStatus{Waiting: true}, "", nil
|
|
}
|
|
if lastErr != nil {
|
|
return QRStatus{}, "", lastErr
|
|
}
|
|
return QRStatus{Expired: true}, "", nil
|
|
}
|
|
|
|
func shopArtifact(rawURL string) bool {
|
|
if rawURL == "" {
|
|
return true
|
|
}
|
|
u, err := url.Parse(rawURL)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return u.Hostname() == "shop.10086.cn"
|
|
}
|
|
|
|
func parseQRPoll(body []byte) (QRStatus, string, error) {
|
|
if len(body) == 0 {
|
|
return QRStatus{Waiting: true}, "", nil
|
|
}
|
|
var res struct {
|
|
ResultCode string `json:"resultCode"`
|
|
ResultDesc string `json:"resultDesc"`
|
|
Artifact string `json:"artifact"`
|
|
AssertURL string `json:"assertUrl"`
|
|
}
|
|
if err := json.Unmarshal(body, &res); err != nil {
|
|
return QRStatus{Waiting: true}, "", nil
|
|
}
|
|
switch res.ResultCode {
|
|
case "":
|
|
return QRStatus{Waiting: true}, "", nil
|
|
case "0000":
|
|
if res.Artifact == "" {
|
|
return QRStatus{}, "", errors.New("登录结果缺少凭证")
|
|
}
|
|
return QRStatus{AssertURL: res.AssertURL}, res.Artifact, nil
|
|
case "8020":
|
|
return QRStatus{Expired: true}, "", nil
|
|
default:
|
|
if res.ResultDesc != "" {
|
|
return QRStatus{}, "", errors.New(res.ResultDesc)
|
|
}
|
|
return QRStatus{Waiting: true}, "", nil
|
|
}
|
|
}
|
|
|
|
func restorePhone(masked, code string) (string, error) {
|
|
masked = strings.TrimSpace(masked)
|
|
code = strings.TrimSpace(code)
|
|
if strings.Contains(masked, "******") && len(code) == 6 {
|
|
phone := strings.Replace(masked, "******", code, 1)
|
|
if phoneOK(phone) {
|
|
return phone, nil
|
|
}
|
|
}
|
|
if phoneOK(masked) {
|
|
return masked, nil
|
|
}
|
|
return "", errors.New("没有拿到手机号")
|
|
}
|
|
|
|
func phoneOK(s string) bool {
|
|
if len(s) != 11 || s[0] != '1' {
|
|
return false
|
|
}
|
|
for _, c := range s {
|
|
if c < '0' || c > '9' {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (c *Client) dropAccountSession() {
|
|
hosts := []string{loginOrigin + "/", shopOrigin + "/", "https://10086.cn/", "https://www.10086.cn/"}
|
|
for _, raw := range hosts {
|
|
u, err := url.Parse(raw)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
var drop []*http.Cookie
|
|
for _, ck := range c.jar.Cookies(u) {
|
|
if !accountSessionCookie(ck.Name) {
|
|
continue
|
|
}
|
|
path := ck.Path
|
|
if path == "" {
|
|
path = "/"
|
|
}
|
|
drop = append(drop, &http.Cookie{Name: ck.Name, Path: path, MaxAge: -1})
|
|
drop = append(drop, &http.Cookie{Name: ck.Name, Domain: "10086.cn", Path: path, MaxAge: -1})
|
|
}
|
|
if len(drop) > 0 {
|
|
c.jar.SetCookies(u, drop)
|
|
}
|
|
}
|
|
}
|
|
|
|
func accountSessionCookie(name string) bool {
|
|
switch name {
|
|
case "cmccssotoken", "is_login", "ssologinprovince":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func (c *Client) clearLoginCookies() {
|
|
c.qrToken = ""
|
|
u, err := url.Parse(loginOrigin + "/")
|
|
if err != nil {
|
|
return
|
|
}
|
|
var drop []*http.Cookie
|
|
for _, ck := range c.jar.Cookies(u) {
|
|
if !loginHandshakeCookie(ck.Name) {
|
|
continue
|
|
}
|
|
drop = append(drop, &http.Cookie{Name: ck.Name, Path: ck.Path, MaxAge: -1})
|
|
}
|
|
if len(drop) > 0 {
|
|
c.jar.SetCookies(u, drop)
|
|
}
|
|
}
|
|
|
|
func loginHandshakeCookie(name string) bool {
|
|
switch name {
|
|
case "lgToken", "cvToken", "CaptchaCode", "jsessionid-cmcc", "rdmdmd5", "sendflag":
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|
|
|
|
func (c *Client) cookieNamed(name string) string {
|
|
for _, raw := range []string{loginOrigin + "/", "https://10086.cn/", shopOrigin + "/"} {
|
|
u, err := url.Parse(raw)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, ck := range c.jar.Cookies(u) {
|
|
if ck.Name == name && ck.Value != "" {
|
|
return ck.Value
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (c *Client) SessionAlive(ctx context.Context) bool {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
_, err := c.loginfo(ctx)
|
|
return err == nil
|
|
}
|
|
|
|
func (c *Client) Query(ctx context.Context, phone, prov string) (json.RawMessage, json.RawMessage, error) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if err := c.ensureKeys(ctx); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return c.queryOnce(ctx, phone, prov)
|
|
}
|
|
|
|
func (c *Client) queryOnce(ctx context.Context, phone, prov string) (json.RawMessage, json.RawMessage, error) {
|
|
token, err := c.crypto.phoneToken(phone)
|
|
if err != nil {
|
|
debugf("生成号码令牌失败 phone=%s %v", phone, err)
|
|
return nil, nil, err
|
|
}
|
|
pay, err := c.crypto.payPhoneNo(phone)
|
|
if err != nil {
|
|
debugf("生成缴费号码失败 phone=%s %v", phone, err)
|
|
return nil, nil, err
|
|
}
|
|
debugf("查询账户 phone=%s prov=%s token=%s pay=%s", phone, prov, token, pay)
|
|
headers := map[string]string{"provcode": prov, "payphoneno": pay}
|
|
real, err := c.shopGet(ctx, "/i/v1/fee/real/"+token+"?_="+milli(), headers)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
plan, err := c.shopGet(ctx, "/i/v1/fee/planbal/"+token+"?_="+milli(), headers)
|
|
if err != nil {
|
|
return real, nil, err
|
|
}
|
|
return real, plan, nil
|
|
}
|
|
|
|
func (c *Client) shopGet(ctx context.Context, path string, extra map[string]string) (json.RawMessage, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, shopOrigin+path, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
c.decorate(req, shopOrigin+"/i/?f=packremainqry")
|
|
for k, v := range extra {
|
|
req.Header.Set(k, v)
|
|
}
|
|
buf, _, err := c.do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return c.decodeShop(buf)
|
|
}
|
|
|
|
func (c *Client) loginfo(ctx context.Context) (map[string]any, error) {
|
|
raw, err := c.shopGet(ctx, "/i/v1/auth/loginfo?_="+milli(), nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var m map[string]any
|
|
if err := json.Unmarshal(raw, &m); err != nil {
|
|
return nil, errors.New("登录状态无法解析")
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
func (c *Client) decodeShop(buf []byte) (json.RawMessage, error) {
|
|
var wrap struct {
|
|
RetCode string `json:"retCode"`
|
|
RetMsg string `json:"retMsg"`
|
|
Data struct {
|
|
OutParam string `json:"outParam"`
|
|
} `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(buf, &wrap); err != nil {
|
|
return nil, errors.New("网站没有返回账户数据")
|
|
}
|
|
if wrap.RetCode == "500003" || strings.Contains(wrap.RetMsg, "not login") || strings.Contains(wrap.RetMsg, "未登录") {
|
|
debugf("个人中心判定未登录 retCode=%s retMsg=%s 原文=%s", wrap.RetCode, wrap.RetMsg, string(buf))
|
|
return nil, ErrNeedLogin
|
|
}
|
|
if wrap.RetCode != "000000" {
|
|
debugf("个人中心查询失败 retCode=%s retMsg=%s", wrap.RetCode, wrap.RetMsg)
|
|
if wrap.RetMsg != "" {
|
|
return nil, errors.New(wrap.RetMsg)
|
|
}
|
|
return nil, fmt.Errorf("查询失败 %s", wrap.RetCode)
|
|
}
|
|
if wrap.Data.OutParam == "" {
|
|
return buf, nil
|
|
}
|
|
plain, err := c.crypto.decryptOutParam(wrap.Data.OutParam)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return json.RawMessage(plain), nil
|
|
}
|
|
|
|
func (c *Client) ensureKeys(ctx context.Context) error {
|
|
if c.channelID == "" || len(c.provinces) == 0 || !c.crypto.shopReady() {
|
|
if err := c.fetchShopScript(ctx); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if c.crypto.loginReady() {
|
|
return nil
|
|
}
|
|
return c.fetchLoginScript(ctx)
|
|
}
|
|
|
|
func (c *Client) fetchLoginScript(ctx context.Context) error {
|
|
page, _, err := c.get(ctx, c.loginPage(), c.loginPage())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var lib, caller string
|
|
err = c.readScripts(ctx, string(page), loginOrigin, c.loginPage(), func(src string) bool {
|
|
if caller == "" && isLoginEncryptCaller(src) {
|
|
caller = src
|
|
}
|
|
if lib == "" && isJSEncryptLib(src) {
|
|
lib = src
|
|
}
|
|
return lib != "" && caller != ""
|
|
})
|
|
if lib == "" || caller == "" {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return errors.New("登录页没有找到加密脚本")
|
|
}
|
|
name, fn, err := extractLoginEncrypt(caller)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.crypto.jsencrypt = lib
|
|
c.crypto.loginFn = fn
|
|
c.crypto.loginName = name
|
|
c.crypto.calibrateRSA()
|
|
return nil
|
|
}
|
|
|
|
func (c *Client) fetchShopScript(ctx context.Context) error {
|
|
page, _, err := c.get(ctx, shopOrigin+"/i/?f=packremainqry", shopOrigin+"/")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.noteLinks(string(page))
|
|
var cryptoJS, bundle string
|
|
err = c.readScripts(ctx, string(page), shopOrigin, shopOrigin+"/i/?f=packremainqry", func(src string) bool {
|
|
if cryptoJS == "" && isCryptoJSLib(src) {
|
|
cryptoJS = src
|
|
}
|
|
if bundle == "" && isShopCryptoBundle(src) {
|
|
bundle = src
|
|
}
|
|
if cryptoJS == "" && isCryptoJSLib(bundle) {
|
|
cryptoJS = bundle
|
|
}
|
|
return cryptoJS != "" && bundle != ""
|
|
})
|
|
if cryptoJS == "" || bundle == "" {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return errors.New("个人中心页面没有找到加密脚本")
|
|
}
|
|
provinces, channel, err := parseShopScript(bundle)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
enc, dec, keyExpr, err := extractAES(bundle)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c.noteLinks(bundle)
|
|
c.provinces = provinces
|
|
c.channelID = channel
|
|
c.crypto.cryptoJS = cryptoJS
|
|
c.crypto.aesEnc = enc
|
|
c.crypto.aesDec = dec
|
|
c.crypto.keyExpr = keyExpr
|
|
c.crypto.calibrateAES()
|
|
return nil
|
|
}
|
|
|
|
func (c *Client) readScripts(ctx context.Context, html, origin, referer string, take func(string) bool) error {
|
|
var last error
|
|
got := false
|
|
for _, ref := range scriptSrcs(html) {
|
|
if !sameSite(origin, ref) {
|
|
continue
|
|
}
|
|
body, _, err := c.get(ctx, absURL(origin, ref), referer)
|
|
if err != nil {
|
|
last = err
|
|
continue
|
|
}
|
|
got = true
|
|
if take(string(body)) {
|
|
return nil
|
|
}
|
|
}
|
|
if !got && last != nil {
|
|
return last
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func parseShopScript(src string) (map[string]string, string, error) {
|
|
provinces := parseProvinces(src)
|
|
if len(provinces) == 0 {
|
|
return nil, "", errors.New("个人中心脚本里没有找到省份名称")
|
|
}
|
|
channel := loginChannelRE.FindStringSubmatch(src)
|
|
if channel == nil {
|
|
return nil, "", errors.New("个人中心脚本里没有找到登录渠道")
|
|
}
|
|
return provinces, channel[1], nil
|
|
}
|
|
|
|
func parseProvinces(src string) map[string]string {
|
|
const marker = `dt=[];`
|
|
i := strings.Index(src, marker)
|
|
if i < 0 {
|
|
return nil
|
|
}
|
|
rest := src[i+len(marker):]
|
|
end := strings.Index(rest, ";")
|
|
if end < 0 {
|
|
return nil
|
|
}
|
|
matches := provRE.FindAllStringSubmatch(rest[:end], -1)
|
|
if len(matches) == 0 {
|
|
return nil
|
|
}
|
|
out := make(map[string]string, len(matches))
|
|
for _, item := range matches {
|
|
out[item[1]] = item[2]
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (c *Client) postForm(ctx context.Context, rawURL string, form url.Values) ([]byte, error) {
|
|
return c.postFormHeader(ctx, rawURL, form, nil)
|
|
}
|
|
|
|
func (c *Client) postFormHeader(ctx context.Context, rawURL string, form url.Values, extra map[string]string) ([]byte, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, strings.NewReader(form.Encode()))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
c.decorate(req, c.loginPage())
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
|
|
req.Header.Set("X-Requested-With", "XMLHttpRequest")
|
|
for k, v := range extra {
|
|
req.Header.Set(k, v)
|
|
}
|
|
buf, _, err := c.do(req)
|
|
return buf, err
|
|
}
|
|
|
|
func (c *Client) postJSON(ctx context.Context, rawURL string, payload any) ([]byte, error) {
|
|
b, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, strings.NewReader(string(b)))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
c.decorate(req, c.loginPage())
|
|
req.Header.Set("Content-Type", "application/json")
|
|
buf, _, err := c.do(req)
|
|
return buf, err
|
|
}
|
|
|
|
func (c *Client) get(ctx context.Context, rawURL, referer string) ([]byte, string, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
c.decorate(req, referer)
|
|
return c.do(req)
|
|
}
|
|
|
|
func (c *Client) do(req *http.Request) ([]byte, string, error) {
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
defer resp.Body.Close()
|
|
buf, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
|
if err != nil {
|
|
return nil, "", err
|
|
}
|
|
if req.URL != nil && req.URL.Hostname() == "login.10086.cn" {
|
|
for _, ck := range resp.Cookies() {
|
|
if ck.Name == "lgToken" && ck.Value != "" {
|
|
c.qrToken = ck.Value
|
|
}
|
|
}
|
|
}
|
|
if resp.StatusCode >= 400 && !strings.Contains(resp.Header.Get("Content-Type"), "json") {
|
|
if debugRequest(req) {
|
|
debugf("%s %s -> %d 失败", req.Method, req.URL.String(), resp.StatusCode)
|
|
}
|
|
return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode)
|
|
}
|
|
if debugRequest(req) {
|
|
debugf("%s %s -> %d Set-Cookie [%s]", req.Method, req.URL.String(), resp.StatusCode, debugSetCookies(resp))
|
|
if !strings.Contains(resp.Header.Get("Content-Type"), "image") {
|
|
debugBody(req.URL.Path, buf)
|
|
}
|
|
}
|
|
return buf, resp.Header.Get("Content-Type"), nil
|
|
}
|
|
|
|
func (c *Client) decorate(req *http.Request, referer string) {
|
|
req.Header.Set("User-Agent", userAgent)
|
|
req.Header.Set("Accept", "*/*")
|
|
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
|
req.Header.Set("Referer", referer)
|
|
if req.URL != nil && strings.Contains(req.URL.Host, "login.10086.cn") {
|
|
req.Header.Set("Origin", loginOrigin)
|
|
}
|
|
}
|
|
|
|
func (c *Client) bootstrap(ctx context.Context) error {
|
|
if _, _, err := c.get(ctx, c.loginPage(), c.loginPage()); err != nil {
|
|
return err
|
|
}
|
|
if _, _, err := c.get(ctx, loginOrigin+"/loadSendflag.htm?timestamp="+milli(), c.loginPage()); err != nil {
|
|
return err
|
|
}
|
|
if _, _, err := c.get(ctx, loginOrigin+"/genqr.htm", c.loginPage()); err != nil {
|
|
return err
|
|
}
|
|
_, _, _ = c.get(ctx, shopOrigin+"/i/v1/auth/loginfo?_="+milli(), shopOrigin+"/i/?f=packremainqry")
|
|
return nil
|
|
}
|
|
|
|
func (c *Client) ExportCookies() []Cookie {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
var out []Cookie
|
|
for _, raw := range []string{loginOrigin + "/", shopOrigin + "/", "https://10086.cn/"} {
|
|
u, _ := url.Parse(raw)
|
|
for _, ck := range c.jar.Cookies(u) {
|
|
out = append(out, Cookie{Name: ck.Name, Value: ck.Value, Domain: hostOf(u), Path: "/"})
|
|
}
|
|
}
|
|
return dedupeCookies(out)
|
|
}
|
|
|
|
func (c *Client) ImportCookies(list []Cookie) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
grouped := map[string][]*http.Cookie{}
|
|
for _, item := range list {
|
|
if item.Name == "" {
|
|
continue
|
|
}
|
|
domain := item.Domain
|
|
if domain == "" {
|
|
domain = "shop.10086.cn"
|
|
}
|
|
path := item.Path
|
|
if path == "" {
|
|
path = "/"
|
|
}
|
|
grouped[domain] = append(grouped[domain], &http.Cookie{Name: item.Name, Value: item.Value, Path: path})
|
|
}
|
|
for domain, cs := range grouped {
|
|
u, err := url.Parse("https://" + strings.TrimPrefix(domain, ".") + "/")
|
|
if err != nil {
|
|
continue
|
|
}
|
|
c.jar.SetCookies(u, cs)
|
|
}
|
|
}
|
|
|
|
func (c *Client) Reset() {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
jar, err := cookiejar.New(nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
c.jar = jar
|
|
c.http.Jar = jar
|
|
c.qrToken = ""
|
|
}
|
|
|
|
func dedupeCookies(list []Cookie) []Cookie {
|
|
seen := map[string]bool{}
|
|
out := make([]Cookie, 0, len(list))
|
|
for _, item := range list {
|
|
k := item.Domain + "|" + item.Name
|
|
if seen[k] {
|
|
continue
|
|
}
|
|
seen[k] = true
|
|
out = append(out, item)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func hostOf(u *url.URL) string {
|
|
if u == nil {
|
|
return ""
|
|
}
|
|
return u.Hostname()
|
|
}
|
|
|
|
func milli() string {
|
|
return fmt.Sprintf("%d", time.Now().UnixMilli())
|
|
}
|
|
|
|
func smsMessage(body string) (string, error) {
|
|
code := strings.Trim(strings.TrimSpace(body), `"`)
|
|
switch code {
|
|
case "0":
|
|
return "短信验证码已发送", nil
|
|
case "1":
|
|
return "", errors.New("短信暂时不能发送,请一分钟后再试")
|
|
case "2":
|
|
return "", errors.New("短信验证码获取已达上限")
|
|
case "3":
|
|
return "", errors.New("短信发送过于频繁")
|
|
case "4005":
|
|
return "", errors.New("手机号码有误")
|
|
default:
|
|
if code == "" {
|
|
return "", errors.New("短信接口没有返回结果")
|
|
}
|
|
return "", fmt.Errorf("发送短信验证码失败(%s)", code)
|
|
}
|
|
}
|
|
|
|
func asString(v any) string {
|
|
switch t := v.(type) {
|
|
case string:
|
|
return t
|
|
case float64:
|
|
return strconv.FormatFloat(t, 'f', -1, 64)
|
|
case json.Number:
|
|
return t.String()
|
|
default:
|
|
return ""
|
|
}
|
|
}
|