commit aadfaba7a60b10aeedda299c0c3dc623fd5f1f55 Author: zzy <2450266535@qq.com> Date: Fri Nov 27 18:11:12 2026 +0800 init diff --git a/README.md b/README.md new file mode 100644 index 0000000..b46bdb1 --- /dev/null +++ b/README.md @@ -0,0 +1,19 @@ + +## 构建 + +阅读golang标准构建方式以更好构建到其他平台架构 + +```shell +go build +./xray-stats +``` + +## 开发 + +> 前置条件 安装对应平台的xray可执行文件并将其放到项目根目录 + +```shell +./xray +go run +``` +打开 127.0.0.1:8080 网站即可查看控制界面 diff --git a/config.json b/config.json new file mode 100644 index 0000000..c014a29 --- /dev/null +++ b/config.json @@ -0,0 +1,48 @@ +{ + "log": { + "access": "./access.log", + "error": "./error.log", + "loglevel": "debug" + }, + "stats": {}, + "api": { "tag": "api", "services": ["StatsService", "ReflectionService"] }, + "policy": { + "levels": { "0": { "statsUserUplink": true, "statsUserDownlink": true } }, + "system": { + "statsInboundUplink": true, "statsInboundDownlink": true, + "statsOutboundUplink": true, "statsOutboundDownlink": true + } + }, + "inbounds": [ + { + "listen": "127.0.0.1", + "tag": "tunnel-in", + "port": 4431, + "protocol": "tunnel", + "settings": { + "address": "speed.cloudflare.com", + "port": 443, + "network": "tcp" + }, + "sniffing": { "enabled": true, "destOverride": ["tls"], "routeOnly": true } + }, + { + "listen": "127.0.0.1", + "port": 10085, + "protocol": "dokodemo-door", + "settings": { "address": "127.0.0.1" }, + "tag": "api" + } + ], + "outbounds": [ + { "protocol": "freedom", "tag": "direct" }, + { "protocol": "blackhole", "tag": "block" } + ], + "routing": { + "rules": [ + { "inboundTag": ["tunnel-in"], "domain": ["speed.cloudflare.com"], "outboundTag": "direct" }, + { "inboundTag": ["tunnel-in"], "outboundTag": "block" }, + { "inboundTag": ["api"], "outboundTag": "api", "type": "field" } + ] + } +} \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..49851e6 --- /dev/null +++ b/go.mod @@ -0,0 +1,15 @@ +module xray-stats + +go 1.26.3 + +require ( + github.com/pires/go-proxyproto v0.11.0 // indirect + github.com/sagernet/sing v0.5.1 // indirect + github.com/xtls/xray-core v1.260327.0 // indirect + golang.org/x/net v0.57.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.40.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // indirect + google.golang.org/grpc v1.84.0 // indirect + google.golang.org/protobuf v1.36.11 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..d47efc9 --- /dev/null +++ b/go.sum @@ -0,0 +1,28 @@ +github.com/pires/go-proxyproto v0.11.0 h1:gUQpS85X/VJMdUsYyEgyn59uLJvGqPhJV5YvG68wXH4= +github.com/pires/go-proxyproto v0.11.0/go.mod h1:ZKAAyp3cgy5Y5Mo4n9AlScrkCZwUy0g3Jf+slqQVcuU= +github.com/sagernet/sing v0.5.1 h1:mhL/MZVq0TjuvHcpYcFtmSD1BFOxZ/+8ofbNZcg1k1Y= +github.com/sagernet/sing v0.5.1/go.mod h1:ARkL0gM13/Iv5VCZmci/NuoOlePoIsW0m7BWfln/Hak= +github.com/xtls/xray-core v1.260327.0 h1:g4TzxMwyPrxslZh6uD+FiG3lXKTrnNO+b4ky2OhogHE= +github.com/xtls/xray-core v1.260327.0/go.mod h1:OXMlhBloFry8mw0KwWLWLd3RQyXJzEYsCGlgsX36h60= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= +golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 h1:qEHAMpSaUhtD0p3NbEEI83HwNGFxEwaSJ1G9PLnCBZE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= +google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= +google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0= +google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= diff --git a/main.go b/main.go new file mode 100644 index 0000000..a66744d --- /dev/null +++ b/main.go @@ -0,0 +1,148 @@ +package main + +import ( + "context" + "crypto/subtle" + "embed" + "encoding/json" + "flag" + "io/fs" + "log" + "net/http" + "time" + + statsService "github.com/xtls/xray-core/app/stats/command" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +//go:embed web +var webFS embed.FS + +// ===== 对应 examples/structures.go ===== + +type BaseConfig struct { + APIAddress string + APIPort uint16 +} + +type XrayController struct { + SsClient statsService.StatsServiceClient + CmdConn *grpc.ClientConn +} + +// 对应 examples/init.go 的 Init,改用 NewClient +func (x *XrayController) Init(cfg *BaseConfig) error { + addr := cfg.APIAddress + ":" + itoa(uint32(cfg.APIPort)) + conn, err := grpc.NewClient( + "passthrough:///"+addr, + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + if err != nil { + return err + } + x.CmdConn = conn + x.SsClient = statsService.NewStatsServiceClient(conn) + return nil +} + +func itoa(n uint32) string { + if n == 0 { + return "0" + } + var b [10]byte + i := len(b) + for n > 0 { + i-- + b[i] = byte('0' + n%10) + n /= 10 + } + return string(b[i:]) +} + +// HTTP + +type Stat struct { + Name string `json:"name"` + Value int64 `json:"value"` +} + +type Server struct { + ctl *XrayController + token string +} + +func (s *Server) checkAuth(r *http.Request) bool { + if s.token == "" { + return true + } + want := "Bearer " + s.token + return subtle.ConstantTimeCompare( + []byte(r.Header.Get("Authorization")), []byte(want), + ) == 1 +} + +func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + if !s.checkAuth(r) { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + + resp, err := s.ctl.SsClient.QueryStats(ctx, &statsService.QueryStatsRequest{}) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + out := make([]Stat, 0, len(resp.Stat)) + for _, st := range resp.Stat { + out = append(out, Stat{Name: st.Name, Value: st.Value}) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{"stat": out}) +} + +func main() { + var ( + listen = flag.String("listen", "127.0.0.1:8080", "HTTP listen address") + apiAddr = flag.String("api-address", "127.0.0.1", "Xray API address") + apiPort = flag.Uint("api-port", 10085, "Xray API port") + token = flag.String("token", "", "Bearer token, empty disables auth") + ) + flag.Parse() + + cfg := &BaseConfig{ + APIAddress: *apiAddr, + APIPort: uint16(*apiPort), + } + + ctl := new(XrayController) + if err := ctl.Init(cfg); err != nil { + log.Fatalf("init: %v", err) + } + defer ctl.CmdConn.Close() + + srv := &Server{ctl: ctl, token: *token} + + mux := http.NewServeMux() + mux.HandleFunc("/stats", srv.handleStats) + + sub, err := fs.Sub(webFS, "web") + if err != nil { + log.Fatalf("embed fs: %v", err) + } + mux.Handle("/", http.FileServer(http.FS(sub))) + + log.Printf("listening %s | xray %s:%d | auth=%v", + *listen, *apiAddr, *apiPort, *token != "") + + log.Fatal(http.ListenAndServe(*listen, mux)) +} diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..ef4efea --- /dev/null +++ b/web/index.html @@ -0,0 +1,382 @@ + + + + + +Xray 流量统计 + + + + +
+
+
+

Xray 流量统计

+
未加载
+
+
+ + +
+
+ + + +
+ +
+
+ + + +
+
暂无数据
+
+
+ + + + \ No newline at end of file