Skip to content

Commit

Permalink
init project
Browse files Browse the repository at this point in the history
  • Loading branch information
faceair committed May 2, 2023
0 parents commit 583eb69
Show file tree
Hide file tree
Showing 6 changed files with 374 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vscode
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023, faceair

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Clash-SpeedTest

快速测试你的 Clash 节点速度。

Features:
1. 无需额外的配置,直接将 Clash 配置文件地址作为参数传入即可
2. 支持 Proxy 和 Proxy Provider 中定义的全部类型代理节点,兼容性跟 Clash 一致
3. 不依赖额外的 Clash 实例,单一进程即可完成测试
4. 代码简单而且开源,不发布构建好的二进制文件,保证你的节点安全

## 使用方法

安装
```bash
> go install github.com/faceair/clash-speedtest
```

运行参数
```bash
> clash-speedtest -h
Usage of clash-speedtest:
-c string
specify configuration file
-f string
filter proxies by name, use regexp (default ".*")
-s int
download size for testing proxies (default 104857600)
-t duration
timeout for testing proxies (default 5s)
```

```bash
# 测试全部节点
> clash-speedtest -c ~/.config/clash/config.yaml
ProxyName Bandwidth ResponseTime
[GroupName] US 01 26.13MB/s 1173.00ms
[GroupName] US 02 51.30MB/s 3051.00ms
[GroupName] US 03 26.49MB/s 1226.00ms

# 测试香港节点,使用正则表达式过滤即可
> clash-speedtest -c ~/.config/clash/config.yaml -f 'HK|港'
```

## 速度测试原理

通过 HTTP GET 请求下载指定大小的文件,默认使用 https://speed.cloudflare.com/__down?bytes=104857600 (100MB) 进行测试,计算下载时间得到下载速度。

测试结果:
1. Bandwidth 是指下载指定大小文件的速度,即一般理解中的下载速度。当这个数值越高时表明节点的出口带宽越大。
2. ResponseTime 是指 HTTP GET 请求拿到第一个字节的的响应时间,即一般理解中的 TTFB。当这个数值越低时表明你本地到达节点的延迟越低,可能意味着节点机房离你更近、节点第一跳有 BGP 部署、节点出海线路是 IEPL、IPLC 等。

请注意 Bandwidth 跟 ResponseTime 是两个不同的指标,不能混为一谈:
1. 有可能 Bandwidth 很高但是 ResponseTime 也很高,这种情况下你下载速度很快但是打开网页的时候却很慢,可能是节点第一跳没有 BGP 加速但出海线路带宽很充足。
2. 有可能 Bandwidth 很低但是 Bandwidth 也很低,这种情况下你打开网页的时候很快但是下载速度很慢,可能是节点第一跳有 BGP 加速但出海的 IEPL、IPLC 线路带宽很小。

## License

[MIT](LICENSE)

[
26 changes: 26 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
module github.com/faceair/clash-speedtest

go 1.20

require (
github.com/Dreamacro/clash v1.15.1
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/gofrs/uuid/v5 v5.0.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/miekg/dns v1.1.53 // indirect
github.com/samber/lo v1.38.1 // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
go.uber.org/atomic v1.10.0 // indirect
golang.org/x/crypto v0.8.0 // indirect
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/net v0.9.0 // indirect
golang.org/x/sys v0.7.0 // indirect
golang.org/x/text v0.9.0 // indirect
golang.org/x/tools v0.6.0 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
)
49 changes: 49 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
github.com/Dreamacro/clash v1.15.1 h1:AwwtrVYbeXg9ZCxpPxAurGXwaR3FxDdHv3rB/vAGXj4=
github.com/Dreamacro/clash v1.15.1/go.mod h1:WNH69bN11LiAdgdSr4hpkEuXVMfBbWyhEKMCTx9BtNE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gofrs/uuid/v5 v5.0.0 h1:p544++a97kEL+svbcFbCQVM9KFu0Yo25UoISXGNNH9M=
github.com/gofrs/uuid/v5 v5.0.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/miekg/dns v1.1.53 h1:ZBkuHr5dxHtB1caEOlZTLPo7D3L3TWckgUUs/RHfDxw=
github.com/miekg/dns v1.1.53/go.mod h1:uInx36IzPl7FYnDcMeVWxj9byh7DutNykX4G9Sj60FY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/samber/lo v1.38.1 h1:j2XEAqXKb09Am4ebOg31SpvzUTTs6EN3VfgeLUhPdXM=
github.com/samber/lo v1.38.1/go.mod h1:+m/ZKRl6ClXCE2Lgf3MsQlWfh4bn1bz6CXEOxnEXnEA=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ=
go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ=
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 h1:3MTrJm4PyNL9NBqvYDSj3DHl46qQakyfqfWo4jgfaEM=
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
217 changes: 217 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
package main

import (
"context"
"flag"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"

"github.com/Dreamacro/clash/adapter"
"github.com/Dreamacro/clash/adapter/provider"
C "github.com/Dreamacro/clash/constant"
providerTypes "github.com/Dreamacro/clash/constant/provider"
"github.com/Dreamacro/clash/log"
"gopkg.in/yaml.v3"
)

var (
configPathConfig = flag.String("c", "", "specify configuration file")
filterRegexConfig = flag.String("f", ".*", "filter proxies by name, use regexp")
downloadSizeConfig = flag.Int("s", 1024*1024*100, "download size for testing proxies")
timeoutConfig = flag.Duration("t", time.Second*5, "timeout for testing proxies")
)

func main() {
flag.Parse()

if *configPathConfig == "" {
log.Fatalln("Please specify the configuration file")
}
if !filepath.IsAbs(*configPathConfig) {
currentDir, _ := os.Getwd()
*configPathConfig = filepath.Join(currentDir, *configPathConfig)
}
filterRe := regexp.MustCompile(*filterRegexConfig)

C.SetHomeDir(os.TempDir())

C.SetConfig(*configPathConfig)

cfg, err := LoadConfig()
if err != nil {
log.Fatalln("Failed to load config: %s", err)
}

fmt.Printf("%-30s\t%-10s\t%-12s\n", "ProxyName", "Bandwidth", "ResponseTime")

for _, proxy := range cfg.Proxies {
switch proxy.Type() {
case C.Shadowsocks, C.ShadowsocksR, C.Snell, C.Socks5, C.Http, C.Vmess, C.Trojan:
if filterRe.MatchString(proxy.Name()) {
name := formatName(proxy.Name())
result := TestProxy(proxy, *downloadSizeConfig, *timeoutConfig)
fmt.Printf("%-30s\t%-10s\t%-12s\n", name, formatBandwidth(result.Bandwidth), formatMillseconds(result.ResponseTime))
}
case C.Direct, C.Reject, C.Relay, C.Selector, C.Fallback, C.URLTest, C.LoadBalance:
continue
default:
log.Fatalln("Unsupported proxy type: %s", proxy.Type())
}
}
for _, provider := range cfg.Providers {
for _, proxy := range provider.Proxies() {
switch proxy.Type() {
case C.Shadowsocks, C.ShadowsocksR, C.Snell, C.Socks5, C.Http, C.Vmess, C.Trojan:
if filterRe.MatchString(proxy.Name()) {
name := fmt.Sprintf("[%s] %s", provider.Name(), formatName(proxy.Name()))
result := TestProxy(proxy, *downloadSizeConfig, *timeoutConfig)
fmt.Printf("%-30s\t%-10s\t%-12s\n", name, formatBandwidth(result.Bandwidth), formatMillseconds(result.ResponseTime))
}
case C.Direct, C.Reject, C.Relay, C.Selector, C.Fallback, C.URLTest, C.LoadBalance:
continue
default:
log.Fatalln("Unsupported proxy type: %s", proxy.Type())
}
}
}
}

type Config struct {
Proxies map[string]C.Proxy
Providers map[string]providerTypes.ProxyProvider
}

type RawConfig struct {
Providers map[string]map[string]any `yaml:"proxy-providers"`
Proxies []map[string]any `yaml:"proxies"`
}

func LoadConfig() (*Config, error) {
buf, err := os.ReadFile(C.Path.Config())
if err != nil {
return nil, err
}
rawCfg := &RawConfig{
Proxies: []map[string]any{},
}
if err := yaml.Unmarshal(buf, rawCfg); err != nil {
return nil, err
}
proxies := make(map[string]C.Proxy)
providers := make(map[string]providerTypes.ProxyProvider)
proxiesConfig := rawCfg.Proxies
providersConfig := rawCfg.Providers

for i, config := range proxiesConfig {
proxy, err := adapter.ParseProxy(config)
if err != nil {
return nil, fmt.Errorf("proxy %d: %w", i, err)
}

if _, exist := proxies[proxy.Name()]; exist {
return nil, fmt.Errorf("proxy %s is the duplicate name", proxy.Name())
}
proxies[proxy.Name()] = proxy
}
for name, config := range providersConfig {
if name == provider.ReservedName {
return nil, fmt.Errorf("can not defined a provider called `%s`", provider.ReservedName)
}
pd, err := provider.ParseProxyProvider(name, config)
if err != nil {
return nil, fmt.Errorf("parse proxy provider %s error: %w", name, err)
}
if err := pd.Initial(); err != nil {
return nil, fmt.Errorf("initial proxy provider %s error: %w", pd.Name(), err)
}
providers[name] = pd
}
return &Config{proxies, providers}, nil
}

type Result struct {
Bandwidth float64
ResponseTime time.Duration
}

func TestProxy(proxy C.Proxy, downloadSize int, timeout time.Duration) *Result {
client := http.Client{
Timeout: timeout,
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
return proxy.DialContext(ctx, &C.Metadata{
Host: host,
DstPort: port,
})
},
},
}

start := time.Now()
resp, err := client.Get(fmt.Sprintf("https://speed.cloudflare.com/__down?bytes=%d", downloadSize))
if err != nil {
return &Result{-1, 0}
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return &Result{-1, 0}
}
responseTime := time.Since(start)

io.Copy(io.Discard, resp.Body)
downloadTime := time.Since(start) - responseTime
bandwidth := float64(downloadSize) / downloadTime.Seconds()

return &Result{bandwidth, responseTime}
}

var (
emojiRegex = regexp.MustCompile(`[\x{1F600}-\x{1F64F}\x{1F300}-\x{1F5FF}\x{1F680}-\x{1F6FF}\x{2600}-\x{26FF}\x{1F1E0}-\x{1F1FF}]`)
pipeRegex = regexp.MustCompile(`\|.*`)
spaceRegex = regexp.MustCompile(`\s{2,}`)
)

func formatName(name string) string {
noEmoji := emojiRegex.ReplaceAllString(name, "")
noPipe := pipeRegex.ReplaceAllString(noEmoji, "")
mergedSpaces := spaceRegex.ReplaceAllString(noPipe, " ")
return strings.TrimSpace(mergedSpaces)
}

func formatBandwidth(v float64) string {
if v <= 0 {
return "N/A"
}
if v < 1024 {
return fmt.Sprintf("%.02fB/s", v)
}
v /= 1024
if v < 1024 {
return fmt.Sprintf("%.02fKB/s", v)
}
v /= 1024
if v < 1024 {
return fmt.Sprintf("%.02fMB/s", v)
}
v /= 1024
if v < 1024 {
return fmt.Sprintf("%.02fGB/s", v)
}
v /= 1024
return fmt.Sprintf("%.02fTB/s", v)
}

func formatMillseconds(v time.Duration) string {
return fmt.Sprintf("%.02fms", float64(v.Milliseconds()))
}

0 comments on commit 583eb69

Please sign in to comment.