Files

384 lines
8.5 KiB
Go

package cmnet
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"time"
skipqr "github.com/skip2/go-qrcode"
tqr "github.com/tuotoo/qrcode"
)
const scanProbeTimeout = 8 * time.Second
var (
httpURLRE = regexp.MustCompile(`https?://[a-zA-Z0-9.-]+(?::\d+)?(?:/[^\s"'<>\\]*)?`)
provCodeRE = regexp.MustCompile(`\{"code":(\d+),"name":"[^"]*"(?:,"[A-Za-z]+":"[^"]*")*,"abbr":"([a-z]+)"\}`)
indexExprRE = regexp.MustCompile(`["'](\./index_)["']\s*\+\s*[A-Za-z0-9_]+\s*\+\s*["'](_)["']\s*\+\s*[A-Za-z0-9_]+\s*\+\s*["'](\.html)["']`)
indexLinkRE = regexp.MustCompile(`https?://[a-zA-Z0-9.-]+/index/[a-z]{2,3}`)
submitChannelRE = regexp.MustCompile(`submitqr\.htm[\s\S]{0,400}?channelID['"]\s*:\s*['"](\d+)['"]`)
)
func (c *Client) noteLinks(text string) {
for _, host := range carrierHosts(text) {
if !hasString(c.hosts, host) {
c.hosts = append(c.hosts, host)
}
}
if c.portal == "" {
c.portal = portalRoot(text)
}
}
func (c *Client) usableQR(ctx context.Context, png []byte) []byte {
token := c.qrToken
defer func() { c.qrToken = token }()
text, err := decodeQRText(png)
if err != nil || text == "" {
return png
}
target, err := url.Parse(text)
if err != nil || target.Scheme == "" || target.Host == "" {
return png
}
if c.scanBase != "" {
return redrawQR(applyBase(c.scanBase, target), png)
}
if c.isScanPage(ctx, target.String()) {
c.scanBase = baseOf(target)
return png
}
base := c.findScanBase(ctx, target)
if base == "" {
return png
}
c.scanBase = base
return redrawQR(applyBase(base, target), png)
}
func (c *Client) findScanBase(ctx context.Context, orig *url.URL) string {
if base := c.probeHosts(ctx, orig, c.hosts, true); base != "" {
return base
}
if c.portal == "" {
return ""
}
body, err := fetchPublic(ctx, c.portal)
if err != nil {
return ""
}
text := string(body)
pageURL := c.portal
for i := 0; i < 3; i++ {
if base := c.probeHosts(ctx, orig, carrierHosts(text), true); base != "" {
return base
}
next := nextPortalPage(pageURL, text)
if next == "" || samePage(next, pageURL) {
return c.probeHosts(ctx, orig, carrierHosts(text), false)
}
body, err = fetchPublic(ctx, next)
if err != nil {
return ""
}
text = string(body)
pageURL = next
}
return c.probeHosts(ctx, orig, carrierHosts(text), false)
}
func (c *Client) probeHosts(ctx context.Context, orig *url.URL, hosts []string, appOnly bool) string {
list := orderedHosts(hosts, orig.Hostname())
if appOnly {
var kept []string
for _, host := range list {
if strings.Contains(host, "app") {
kept = append(kept, host)
}
}
list = kept
} else if len(list) > 8 {
list = list[:8]
}
for _, host := range list {
cand := cloneURL(orig, host)
if !c.isScanPage(ctx, cand) {
continue
}
u, err := url.Parse(cand)
if err != nil {
continue
}
return baseOf(u)
}
return ""
}
func (c *Client) isScanPage(ctx context.Context, rawURL string) bool {
body, err := fetchPublic(ctx, rawURL)
if err != nil || !isScanLoginPage(body) {
return false
}
c.learnScanChannel(ctx, rawURL, body)
return true
}
func (c *Client) learnScanChannel(ctx context.Context, pageURL string, html []byte) {
if c.qrChannel != "" {
return
}
for _, ref := range scriptSrcs(string(html)) {
low := strings.ToLower(ref)
if !strings.Contains(low, "scancode") && !strings.Contains(low, "/transit/js/") {
continue
}
body, err := fetchPublic(ctx, absURL(pageURL, ref))
if err != nil {
continue
}
if channel := submitChannel(string(body)); channel != "" {
c.qrChannel = channel
return
}
}
}
func submitChannel(src string) string {
item := submitChannelRE.FindStringSubmatch(src)
if item == nil {
return ""
}
return item[1]
}
var publicHTTP = &http.Client{Timeout: scanProbeTimeout}
func fetchPublic(ctx context.Context, rawURL string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept", "*/*")
resp, err := publicHTTP.Do(req)
if err != nil {
debugHTTP(req, nil, nil, err)
return nil, err
}
defer resp.Body.Close()
buf, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
debugHTTP(req, resp, nil, err)
return nil, err
}
debugHTTP(req, resp, buf, nil)
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("网站返回 %d", resp.StatusCode)
}
return buf, nil
}
func isScanLoginPage(body []byte) bool {
return bytes.Contains(body, []byte("scancode")) && bytes.Contains(body, []byte("扫码登录"))
}
func redrawQR(text string, fallback []byte) []byte {
png, err := encodeQR(text)
if err != nil || len(png) == 0 {
return fallback
}
return png
}
func encodeQR(text string) ([]byte, error) {
return skipqr.Encode(text, skipqr.Medium, 336)
}
func decodeQRText(png []byte) (string, error) {
mx, err := tqr.Decode(bytes.NewReader(png))
if err != nil {
return "", err
}
return strings.TrimSpace(mx.Content), nil
}
func chooseScanTarget(original string, hosts []string, page func(string) []byte) string {
if isScanLoginPage(page(original)) {
return original
}
target, err := url.Parse(original)
if err != nil || target.Host == "" {
return ""
}
for _, host := range orderedHosts(hosts, target.Hostname()) {
cand := cloneURL(target, host)
if isScanLoginPage(page(cand)) {
return cand
}
}
return ""
}
func nextPortalPage(pageURL, body string) string {
u, err := url.Parse(pageURL)
if err != nil {
return ""
}
if abbr := pathAbbr(u.Path); abbr != "" {
if code := codeForAbbr(body, abbr); code != "" {
if file := buildIndexFile(body, code); file != "" {
ref, err := url.Parse(file)
if err == nil {
if !strings.HasSuffix(u.Path, "/") {
u.Path += "/"
}
return u.ResolveReference(ref).String()
}
}
}
}
link := indexLinkRE.FindString(body)
if link == "" || samePage(link, pageURL) {
return ""
}
return link
}
func codeForAbbr(body, abbr string) string {
for _, item := range provCodeRE.FindAllStringSubmatch(body, -1) {
if item[2] == abbr {
return item[1]
}
}
return ""
}
func buildIndexFile(body, code string) string {
item := indexExprRE.FindStringSubmatch(body)
if item == nil || code == "" {
return ""
}
return item[1] + code + item[2] + code + item[3]
}
func portalRoot(text string) string {
for _, raw := range httpURLs(text) {
u, err := url.Parse(raw)
if err != nil || u.Hostname() != "www.10086.cn" {
continue
}
if u.Path != "" && u.Path != "/" {
continue
}
return "https://www.10086.cn/"
}
return ""
}
func carrierHosts(text string) []string {
var out []string
seen := map[string]bool{}
for _, raw := range httpURLs(text) {
u, err := url.Parse(raw)
if err != nil {
continue
}
host := u.Hostname()
if host == "" || seen[host] || !strings.HasSuffix(host, "10086.cn") {
continue
}
seen[host] = true
out = append(out, host)
}
return out
}
func httpURLs(text string) []string {
found := httpURLRE.FindAllString(text, -1)
out := make([]string, 0, len(found))
for _, raw := range found {
out = append(out, strings.TrimRight(raw, ".,);"))
}
return out
}
func orderedHosts(hosts []string, skip string) []string {
var app, rest []string
seen := map[string]bool{}
for _, host := range hosts {
host = strings.TrimSpace(host)
if host == "" || host == skip || seen[host] {
continue
}
seen[host] = true
if strings.Contains(host, "app") {
app = append(app, host)
} else {
rest = append(rest, host)
}
}
return append(app, rest...)
}
func cloneURL(orig *url.URL, host string) string {
u := *orig
u.Scheme = "https"
u.Host = host
return u.String()
}
func baseOf(u *url.URL) string {
return u.Scheme + "://" + u.Host + u.EscapedPath()
}
func applyBase(base string, orig *url.URL) string {
u, err := url.Parse(base)
if err != nil {
return orig.String()
}
u.RawQuery = orig.RawQuery
return u.String()
}
func pathAbbr(path string) string {
path = strings.Trim(path, "/")
if path == "" {
return ""
}
parts := strings.Split(path, "/")
last := parts[len(parts)-1]
if len(last) < 2 || len(last) > 3 {
return ""
}
for _, r := range last {
if r < 'a' || r > 'z' {
return ""
}
}
return last
}
func samePage(a, b string) bool {
ua, errA := url.Parse(a)
ub, errB := url.Parse(b)
if errA != nil || errB != nil {
return a == b
}
return strings.EqualFold(ua.Hostname(), ub.Hostname()) && strings.TrimRight(ua.Path, "/") == strings.TrimRight(ub.Path, "/")
}
func hasString(list []string, item string) bool {
for _, cur := range list {
if cur == item {
return true
}
}
return false
}