Files

573 lines
14 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cbn
import (
"bytes"
"context"
"crypto/rsa"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"sync"
"time"
)
const (
origin = "https://www.10099.com.cn"
basePath = "/contact-web"
loginReferer = origin + "/login.html"
homeReferer = origin + "/personal-center-number-order.html"
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"
siteCachePath = "data/site.json"
PathBalance = "/api/busi/qryBalanceFee"
PathBill = "/api/busi/qryBillInfo"
PathResource = "/api/busi/qryUserRes"
PathSubscribe = "/api/busi/qrySubscribeBusiness"
)
var ErrNeedLogin = errors.New("会话已失效")
type APIError struct {
Status string
Message string
}
func (e *APIError) Error() string {
if e.Message != "" {
return e.Message
}
if e.Status != "" {
return e.Status
}
return "请求失败"
}
type Result struct {
Status string
Message string
Data json.RawMessage
}
type Cookie struct {
Name string `json:"name"`
Value string `json:"value"`
}
type LoginResult struct {
SessionID string
Phone string
Prov string
City string
}
type Client struct {
mu sync.Mutex
http *http.Client
jar *cookiejar.Jar
profile *siteProfile
}
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) ExportCookies() []Cookie {
c.mu.Lock()
defer c.mu.Unlock()
return c.exportLocked()
}
func (c *Client) ImportCookies(list []Cookie) {
c.mu.Lock()
defer c.mu.Unlock()
u, _ := url.Parse(origin + "/")
cs := make([]*http.Cookie, 0, len(list))
for _, item := range list {
if item.Name == "" {
continue
}
cs = append(cs, &http.Cookie{Name: item.Name, Value: item.Value, Path: "/"})
}
c.jar.SetCookies(u, cs)
}
func (c *Client) Reset() {
c.mu.Lock()
defer c.mu.Unlock()
c.resetLocked()
}
func (c *Client) Prepare(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.ensureProfile(ctx, false)
}
func (c *Client) Captcha(ctx context.Context) ([]byte, string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.ensureProfile(ctx, false); err != nil {
return nil, "", err
}
body, ctype, err := c.get(ctx, "/api/login/getImageCheckCode", loginReferer, "*/*")
if err != nil {
return nil, "", err
}
if !strings.Contains(strings.ToLower(ctype), "image/") && !isImage(body) {
snippet := strings.TrimSpace(string(body))
if len(snippet) > 160 {
snippet = snippet[:160]
}
if ctype == "" {
ctype = "unknown"
}
return nil, "", fmt.Errorf("没有拿到图形验证码(%s)%s", ctype, snippet)
}
if ctype == "" || !strings.Contains(strings.ToLower(ctype), "image/") {
ctype = sniffImage(body)
}
return body, ctype, nil
}
func isImage(body []byte) bool {
if len(body) >= 3 && body[0] == 0xff && body[1] == 0xd8 && body[2] == 0xff {
return true
}
if len(body) >= 8 && string(body[:8]) == "\x89PNG\r\n\x1a\n" {
return true
}
if len(body) >= 6 && (string(body[:6]) == "GIF87a" || string(body[:6]) == "GIF89a") {
return true
}
return false
}
func sniffImage(body []byte) string {
if len(body) >= 8 && string(body[:8]) == "\x89PNG\r\n\x1a\n" {
return "image/png"
}
if len(body) >= 6 && (string(body[:6]) == "GIF87a" || string(body[:6]) == "GIF89a") {
return "image/gif"
}
return "image/jpeg"
}
func (c *Client) SendSMS(ctx context.Context, phone string) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.ensureProfile(ctx, false); err != nil {
return "", err
}
res, err := c.post(ctx, "/api/login/getVerifyCode", map[string]any{
"recieveNum": phone,
"channelId": c.channelID(),
"type": 5,
}, loginReferer)
if err != nil {
return "", err
}
ok, desc := innerOK(res.Data)
if !ok {
return "", errors.New(desc)
}
if desc == "" {
desc = "短信验证码已发送"
}
return desc, nil
}
func (c *Client) Login(ctx context.Context, phone, imageCode, smsCode string) (LoginResult, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.ensureProfile(ctx, false); err != nil {
return LoginResult{}, err
}
res, err := c.post(ctx, "/api/login/gwLogin", map[string]any{
"channelId": c.channelID(),
"loginPhone": phone,
"loginPassWord": smsCode,
"loginType": "5",
"channelType": "1",
"imageCheckCode": imageCode,
}, loginReferer)
if err != nil {
return LoginResult{}, err
}
var data struct {
SessionID string `json:"sessionId"`
LoginPhone string `json:"loginPhone"`
PhoneInfo struct {
MgmtProvName string `json:"mgmtProvName"`
MgmtDistrictName string `json:"mgmtDistrictName"`
AccessNumber string `json:"accessNumber"`
} `json:"phoneInfo"`
}
if err := json.Unmarshal(res.Data, &data); err != nil {
return LoginResult{}, errors.New("登录结果无法解析")
}
if data.SessionID == "" {
return LoginResult{}, errors.New("登录未返回会话")
}
gotPhone := data.LoginPhone
if gotPhone == "" {
gotPhone = data.PhoneInfo.AccessNumber
}
if gotPhone == "" {
gotPhone = phone
}
return LoginResult{
SessionID: data.SessionID,
Phone: gotPhone,
Prov: data.PhoneInfo.MgmtProvName,
City: data.PhoneInfo.MgmtDistrictName,
}, nil
}
func (c *Client) Logout(ctx context.Context, sessionID string) {
c.mu.Lock()
defer c.mu.Unlock()
if sessionID != "" {
u := origin + basePath + "/api/login/logOut?sessionId=" + url.QueryEscape(sessionID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err == nil {
c.decorate(req, loginReferer, "")
_, _, _ = c.send(req, nil)
}
}
c.resetLocked()
}
func (c *Client) Query(ctx context.Context, path, phone, sessionID string) (json.RawMessage, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.ensureProfile(ctx, false); err != nil {
return nil, err
}
res, err := c.post(ctx, path, map[string]any{
"sessionId": sessionID,
"channelId": c.profile.ChannelID,
"accessNum": phone,
}, homeReferer)
if err != nil {
return nil, err
}
return res.Data, nil
}
func (c *Client) channelID() string {
if c.profile == nil {
return ""
}
return c.profile.ChannelID
}
func (c *Client) post(ctx context.Context, path string, payload map[string]any, referer string) (*Result, error) {
if err := c.ensureProfile(ctx, false); err != nil {
return nil, err
}
res, err := c.postOnce(ctx, path, payload, referer)
if errors.Is(err, errDecrypt) {
if err2 := c.ensureProfile(ctx, true); err2 != nil {
return nil, err
}
return c.postOnce(ctx, path, payload, referer)
}
return res, err
}
func (c *Client) postOnce(ctx context.Context, path string, payload map[string]any, referer string) (*Result, error) {
body := make(map[string]any, len(payload)+2)
for k, v := range payload {
body[k] = v
}
body["v"] = c.profile.Version
body["timestamp"] = time.Now().UnixMilli()
access := accessSign(body)
plain, err := marshalCompact(body)
if err != nil {
return nil, err
}
enc, err := encryptLong(c.profile.Public, encodeURIComponent(string(plain)))
if err != nil {
return nil, err
}
envelope, err := json.Marshal(struct {
Data string `json:"data"`
}{Data: enc})
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+basePath+path, nil)
if err != nil {
return nil, err
}
c.decorate(req, referer, "application/json, text/javascript, */*; q=0.01")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Requested-With", "XMLHttpRequest")
req.Header.Set("Access", access)
buf, _, err := c.send(req, envelope)
if err != nil {
return nil, err
}
return parseBody(buf, c.profile.Private)
}
func (c *Client) get(ctx context.Context, path, referer, accept string) ([]byte, string, error) {
return c.getURL(ctx, origin+basePath+path, referer, accept)
}
func (c *Client) getURL(ctx context.Context, rawURL, referer, accept string) ([]byte, string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, "", err
}
c.decorate(req, referer, accept)
return c.send(req, nil)
}
func (c *Client) send(req *http.Request, body []byte) ([]byte, string, error) {
var last []byte
var lastType string
for attempt := 0; attempt < 2; attempt++ {
r := req.Clone(req.Context())
if body != nil {
r.Body = io.NopCloser(bytes.NewReader(body))
r.ContentLength = int64(len(body))
}
resp, err := c.http.Do(r)
if err != nil {
return nil, "", err
}
buf, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
resp.Body.Close()
if err != nil {
return nil, "", err
}
last, lastType = buf, resp.Header.Get("Content-Type")
if attempt == 0 && isWAF(buf) {
token, err := solveACW(string(buf))
if err != nil {
return nil, "", err
}
c.setCookie("acw_sc__v2", token)
continue
}
if resp.StatusCode >= 400 && !bytes.Contains(buf, []byte(`"status"`)) && !isImage(buf) {
return nil, "", fmt.Errorf("网站返回 %d", resp.StatusCode)
}
return buf, lastType, nil
}
if isWAF(last) {
return nil, "", errors.New("网站校验没有通过")
}
return last, lastType, nil
}
func (c *Client) ensureProfile(ctx context.Context, force bool) error {
if !force && c.profile != nil && time.Since(c.profile.FetchedAt) < siteCacheTTL {
return nil
}
p, err := c.fetchProfile(ctx)
if err != nil {
if c.profile != nil && !force {
return nil
}
if cached, err2 := loadSiteCache(siteCachePath); err2 == nil {
c.profile = cached
log.Printf("网页参数暂时拉不下来,继续用 %s 的缓存", cached.FetchedAt.Format("2006-01-02 15:04"))
return nil
}
return err
}
changed := c.profile == nil || c.profile.PublicB64 != p.PublicB64 || c.profile.Version != p.Version || c.profile.ChannelID != p.ChannelID
c.profile = p
if err := saveSiteCache(siteCachePath, p); err != nil {
log.Printf("页面参数已读取,但缓存没写成: %v", err)
}
if changed {
log.Printf("已同步页面参数 %s %s", p.ChannelID, p.Version)
}
return nil
}
func (c *Client) fetchProfile(ctx context.Context) (*siteProfile, error) {
page, _, err := c.getURL(ctx, loginReferer, loginReferer, "text/html,application/xhtml+xml")
if err != nil {
return nil, err
}
if isWAF(page) {
return nil, errors.New("登录页被校验拦住了")
}
urls := scriptURLs(string(page))
if len(urls) == 0 {
return nil, errors.New("登录页里没有脚本地址")
}
var last error
for _, ref := range urls {
body, _, err := c.getURL(ctx, resolveURL(ref), loginReferer, "*/*")
if err != nil {
last = err
continue
}
if isWAF(body) {
continue
}
src := string(body)
if !strings.Contains(src, "encryptLong") || !strings.Contains(src, "setPublicKey") {
continue
}
p, err := parseSiteJS(src)
if err == nil {
return p, nil
}
last = err
}
if last != nil {
return nil, last
}
return nil, errors.New("没有在页面脚本里找到加密参数")
}
func (c *Client) setCookie(name, value string) {
u, _ := url.Parse(origin + "/")
c.jar.SetCookies(u, []*http.Cookie{{Name: name, Value: value, Path: "/"}})
}
func isWAF(body []byte) bool {
return bytes.Contains(body, []byte("renderData")) && bytes.Contains(body, []byte("acw_sc__v2"))
}
func (c *Client) decorate(req *http.Request, referer, accept string) {
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Referer", referer)
if accept != "" {
req.Header.Set("Accept", accept)
}
req.Header.Set("Sec-Fetch-Site", "same-origin")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Dest", "empty")
}
func (c *Client) exportLocked() []Cookie {
u, _ := url.Parse(origin + "/")
got := c.jar.Cookies(u)
out := make([]Cookie, 0, len(got))
for _, ck := range got {
out = append(out, Cookie{Name: ck.Name, Value: ck.Value})
}
return out
}
func (c *Client) resetLocked() {
jar, err := cookiejar.New(nil)
if err != nil {
return
}
c.jar = jar
c.http.Jar = jar
}
func parseBody(buf []byte, priv *rsa.PrivateKey) (*Result, error) {
buf = bytes.TrimSpace(buf)
if len(buf) == 0 {
return nil, errors.New("网站返回空内容")
}
if buf[0] != '{' {
return nil, errors.New("网站没有返回账户数据")
}
var probe map[string]json.RawMessage
if err := json.Unmarshal(buf, &probe); err != nil {
return nil, errors.New("无法解析网站响应")
}
if len(probe) == 1 {
if raw, ok := probe["data"]; ok {
var s string
if json.Unmarshal(raw, &s) == nil && s != "" {
plain, err := decryptLong(priv, s)
if err != nil {
return nil, errDecrypt
}
decoded, err := decodeURIComponent(plain)
if err != nil {
return nil, err
}
buf = bytes.TrimSpace([]byte(decoded))
}
}
}
var wrap struct {
Status string `json:"status"`
Message string `json:"message"`
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(buf, &wrap); err != nil {
return nil, errors.New("无法解析网站响应")
}
res := &Result{Status: wrap.Status, Message: wrap.Message, Data: wrap.Data}
if needLogin(wrap.Status, wrap.Message) {
if res.Message == "" {
res.Message = ErrNeedLogin.Error()
}
return res, ErrNeedLogin
}
if wrap.Status != "000000" {
return res, &APIError{Status: wrap.Status, Message: wrap.Message}
}
return res, nil
}
func needLogin(status, message string) bool {
if status == "701" {
return true
}
for _, part := range []string{"未登录", "请重新登录", "请重新登陆", "会话失效", "登录超时", "登陆超时"} {
if strings.Contains(message, part) {
return true
}
}
return false
}
func innerOK(data json.RawMessage) (bool, string) {
var m map[string]any
if err := json.Unmarshal(data, &m); err != nil {
return true, ""
}
code := asString(m["respCode"])
desc := asString(m["respDesc"])
if code == "" || code == "0000" || code == "000000" {
return true, desc
}
if desc == "" {
desc = "请求失败"
}
return false, desc
}
func marshalCompact(v any) ([]byte, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return nil, err
}
return bytes.TrimRight(buf.Bytes(), "\n"), nil
}