httping.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package task
  2. import (
  3. //"crypto/tls"
  4. "io"
  5. "log"
  6. "net"
  7. "net/http"
  8. "regexp"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/XIU2/CloudflareSpeedTest/utils"
  13. )
  14. var (
  15. Httping bool
  16. HttpingStatusCode int
  17. HttpingCFColo string
  18. HttpingCFColomap *sync.Map
  19. RegexpColoIATACode = regexp.MustCompile(`[A-Z]{3}`) // 匹配 IATA 机场地区码(俗称 机场三字码)的正则表达式
  20. RegexpColoCountryCode = regexp.MustCompile(`[A-Z]{2}`) // 匹配国家地区码的正则表达式(如 US、CN、UK 等)
  21. RegexpColoGcore = regexp.MustCompile(`^[a-z]{2}`) // 匹配城市地区码的正则表达式(小写,如 us、cn、uk 等)
  22. )
  23. // pingReceived pingTotalTime
  24. func (p *Ping) httping(ip *net.IPAddr) (int, time.Duration, string) {
  25. hc := http.Client{
  26. Timeout: time.Second * 2,
  27. Transport: &http.Transport{
  28. DialContext: getDialContext(ip),
  29. //TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // 跳过证书验证
  30. },
  31. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  32. return http.ErrUseLastResponse // 阻止重定向
  33. },
  34. }
  35. // 先访问一次获得 HTTP 状态码 及 地区码
  36. var colo string
  37. {
  38. request, err := http.NewRequest(http.MethodHead, URL, nil)
  39. if err != nil {
  40. if utils.Debug { // 调试模式下,输出更多信息
  41. utils.Red.Printf("[调试] IP: %s, 延迟测速请求创建失败,错误信息: %v, 测速地址: %s\n", ip.String(), err, URL)
  42. }
  43. return 0, 0, ""
  44. }
  45. request.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36")
  46. response, err := hc.Do(request)
  47. if err != nil {
  48. if utils.Debug { // 调试模式下,输出更多信息
  49. utils.Red.Printf("[调试] IP: %s, 延迟测速失败,错误信息: %v, 测速地址: %s\n", ip.String(), err, URL)
  50. }
  51. return 0, 0, ""
  52. }
  53. defer response.Body.Close()
  54. //fmt.Println("IP:", ip, "StatusCode:", response.StatusCode, response.Request.URL)
  55. // 如果未指定的 HTTP 状态码,或指定的状态码不合规,则默认只认为 200、301、302 才算 HTTPing 通过
  56. if HttpingStatusCode == 0 || HttpingStatusCode < 100 && HttpingStatusCode > 599 {
  57. if response.StatusCode != 200 && response.StatusCode != 301 && response.StatusCode != 302 {
  58. if utils.Debug { // 调试模式下,输出更多信息
  59. utils.Red.Printf("[调试] IP: %s, 延迟测速终止,HTTP 状态码: %d, 测速地址: %s\n", ip.String(), response.StatusCode, URL)
  60. }
  61. return 0, 0, ""
  62. }
  63. } else {
  64. if response.StatusCode != HttpingStatusCode {
  65. if utils.Debug { // 调试模式下,输出更多信息
  66. utils.Red.Printf("[调试] IP: %s, 延迟测速终止,HTTP 状态码: %d, 指定的 HTTP 状态码 %d, 测速地址: %s\n", ip.String(), response.StatusCode, HttpingStatusCode, URL)
  67. }
  68. return 0, 0, ""
  69. }
  70. }
  71. io.Copy(io.Discard, response.Body)
  72. // 通过头部参数获取地区码
  73. colo = getHeaderColo(response.Header)
  74. // 只有指定了地区才匹配机场地区码
  75. if HttpingCFColo != "" {
  76. // 判断是否匹配指定的地区码
  77. colo = p.filterColo(colo)
  78. if colo == "" { // 没有匹配到地区码或不符合指定地区则直接结束该 IP 测试
  79. if utils.Debug { // 调试模式下,输出更多信息
  80. utils.Red.Printf("[调试] IP: %s, 地区码不匹配: %s\n", ip.String(), colo)
  81. }
  82. return 0, 0, ""
  83. }
  84. }
  85. }
  86. // 循环测速计算延迟
  87. success := 0
  88. var delay time.Duration
  89. for i := 0; i < PingTimes; i++ {
  90. request, err := http.NewRequest(http.MethodHead, URL, nil)
  91. if err != nil {
  92. log.Fatal("意外的错误,情报告:", err)
  93. return 0, 0, ""
  94. }
  95. request.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36")
  96. if i == PingTimes-1 {
  97. request.Header.Set("Connection", "close")
  98. }
  99. startTime := time.Now()
  100. response, err := hc.Do(request)
  101. if err != nil {
  102. continue
  103. }
  104. success++
  105. io.Copy(io.Discard, response.Body)
  106. _ = response.Body.Close()
  107. duration := time.Since(startTime)
  108. delay += duration
  109. }
  110. return success, delay, colo
  111. }
  112. func MapColoMap() *sync.Map {
  113. if HttpingCFColo == "" {
  114. return nil
  115. }
  116. // 将 -cfcolo 参数指定的地区地区码转为大写并格式化
  117. colos := strings.Split(strings.ToUpper(HttpingCFColo), ",")
  118. colomap := &sync.Map{}
  119. for _, colo := range colos {
  120. colomap.Store(colo, colo)
  121. }
  122. return colomap
  123. }
  124. // 从响应头中获取 地区码 值
  125. func getHeaderColo(header http.Header) (colo string) {
  126. if header.Get("server") != "" {
  127. // 如果是 Cloudflare CDN
  128. // server: cloudflare
  129. // cf-ray: 7bd32409eda7b020-SJC
  130. if header.Get("server") == "cloudflare" {
  131. if colo = header.Get("cf-ray"); colo != "" {
  132. return RegexpColoIATACode.FindString(colo)
  133. }
  134. }
  135. // 如果是 CDN77 CDN(测试地址 https://www.cdn77.com
  136. // server: CDN77-Turbo
  137. // x-77-pop: losangelesUSCA // 美国的会显示为 USCA 不知道什么情况,暂时没做兼容,只提取 US
  138. // x-77-pop: frankfurtDE
  139. // x-77-pop: amsterdamNL
  140. // x-77-pop: singaporeSG
  141. if header.Get("server") == "CDN77-Turbo" {
  142. if colo = header.Get("x-77-pop"); colo != "" {
  143. return RegexpColoCountryCode.FindString(colo)
  144. }
  145. }
  146. // 如果是 Bunny CDN(测试地址 https://bunny.net
  147. // server: BunnyCDN-TW1-1121
  148. if colo = header.Get("server"); strings.Contains(colo, "BunnyCDN-") {
  149. return RegexpColoCountryCode.FindString(strings.TrimPrefix(colo, "BunnyCDN-")) // 去掉 BunnyCDN- 前缀再去匹配
  150. }
  151. }
  152. // 如果是 AWS CloudFront CDN(测试地址 https://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips
  153. // x-amz-cf-pop: SIN52-P1
  154. if colo = header.Get("x-amz-cf-pop"); colo != "" {
  155. return RegexpColoIATACode.FindString(colo)
  156. }
  157. // 如果是 Fastly CDN(测试地址 https://fastly.jsdelivr.net/gh/XIU2/CloudflareSpeedTest@master/go.mod
  158. // x-served-by: cache-qpg1275-QPG
  159. // x-served-by: cache-fra-etou8220141-FRA, cache-hhr-khhr2060043-HHR(最后一个为实际位置)
  160. if colo = header.Get("x-served-by"); colo != "" {
  161. if matches := RegexpColoIATACode.FindAllString(colo, -1); len(matches) > 0 {
  162. return matches[len(matches)-1] // 因为 Fastly 的 x-served-by 可能包含多个地区码,所以只取最后一个
  163. }
  164. }
  165. // Gcore CDN 的头部信息(注意均为城市代码而非国家代码),测试地址 https://assets.gcore.pro/assets/icons/shield-lock.svg
  166. // x-id-fe: fr5-hw-edge-gc17
  167. // x-shard: fr5-shard0-default
  168. // x-id: fr5-hw-edge-gc28
  169. if colo = header.Get("x-id-fe"); colo != "" {
  170. if colo = RegexpColoGcore.FindString(colo); colo != "" {
  171. return strings.ToUpper(colo) // 将小写的地区码转换为大写
  172. }
  173. }
  174. // 如果没有获取到头部信息,说明不是支持的 CDN,则直接返回空字符串
  175. return ""
  176. }
  177. // 处理地区码
  178. func (p *Ping) filterColo(colo string) string {
  179. if colo == "" {
  180. return ""
  181. }
  182. // 如果没有指定 -cfcolo 参数,则直接返回
  183. if HttpingCFColomap == nil {
  184. return colo
  185. }
  186. // 匹配 机场地区码 是否为指定的地区
  187. _, ok := HttpingCFColomap.Load(colo)
  188. if ok {
  189. return colo
  190. }
  191. return ""
  192. }