feat(core): mix-up v2ray and xray and anytls and juicity

This commit is contained in:
Markson Hon committed 2026-05-03 15:55:13 +08:00
1 parent 155091610d
commit 0baefc4530
68 files changed
+1836 -3899

No files matched your search

+2 -4
View File
@@ -13,9 +13,7 @@ else
fi
# https://github.com/webpack/webpack/issues/14532#issuecomment-947012063
cd "$CurrentDir"/gui && yarn --ignore-engines && OUTPUT_DIR="$CurrentDir"/service/server/router/web yarn --ignore-engines build
cd "$CurrentDir"/service && CGO_ENABLED=0 go build -tags "tinytun" -ldflags "-X github.com/v2rayA/v2rayA/conf.Version=$version -s -w" -o "$CurrentDir"/v2raya
# Build v2raya-core (merged xray-core + MultiObservatory)
cd "$CurrentDir"/core && CGO_ENABLED=0 go build -ldflags "-s -w" -o "$CurrentDir"/v2raya_core ./main
# Build v2raya-core (merged xray-core + custom protocols)
cd "$CurrentDir"/core && CGO_ENABLED=0 go build -ldflags "-X main.Version=$version -s -w" -o "$CurrentDir"/v2raya_core ./main
cd "$CurrentDir"/service && CGO_ENABLED=0 go build -tags "with_gvisor" -ldflags "-X github.com/v2rayA/v2rayA/conf.Version=$version -s -w" -o "$CurrentDir"/v2raya
+65
View File
@@ -0,0 +1,65 @@
{
"_comment": "Example config for v2raya hybrid core with anytls outbound.",
"log": {
"loglevel": "info"
},
"inbounds": [
{
"tag": "socks-in",
"protocol": "socks",
"listen": "127.0.0.1",
"port": 20170,
"settings": {
"udp": true
}
},
{
"tag": "http-in",
"protocol": "http",
"listen": "127.0.0.1",
"port": 20171
}
],
"outbounds": [
{
"tag": "proxy",
"protocol": "anytls",
"settings": {
"address": "1.2.3.4",
"port": 443,
"password": "your-password-here",
"sni": "example.com",
"allow_insecure": false,
"min_idle_sessions": 5
}
},
{
"tag": "direct",
"protocol": "freedom"
},
{
"tag": "block",
"protocol": "blackhole"
}
],
"routing": {
"domainStrategy": "IPIfNonMatch",
"rules": [
{
"type": "field",
"ip": ["geoip:private"],
"outboundTag": "direct"
},
{
"type": "field",
"domain": ["geosite:cn"],
"outboundTag": "direct"
},
{
"type": "field",
"port": "0-65535",
"outboundTag": "proxy"
}
]
}
}
+66
View File
@@ -0,0 +1,66 @@
{
"_comment": "Example config for v2raya hybrid core with juicity outbound.",
"log": {
"loglevel": "info"
},
"inbounds": [
{
"tag": "socks-in",
"protocol": "socks",
"listen": "127.0.0.1",
"port": 20170,
"settings": {
"udp": true
}
},
{
"tag": "http-in",
"protocol": "http",
"listen": "127.0.0.1",
"port": 20171
}
],
"outbounds": [
{
"tag": "proxy",
"protocol": "juicity",
"settings": {
"address": "1.2.3.4:443",
"uuid": "00000000-0000-0000-0000-000000000000",
"password": "your-password-here",
"sni": "example.com",
"allow_insecure": false,
"congestion_control": "bbr",
"pinned_certchain_sha256": ""
}
},
{
"tag": "direct",
"protocol": "freedom"
},
{
"tag": "block",
"protocol": "blackhole"
}
],
"routing": {
"domainStrategy": "IPIfNonMatch",
"rules": [
{
"type": "field",
"ip": ["geoip:private"],
"outboundTag": "direct"
},
{
"type": "field",
"domain": ["geosite:cn"],
"outboundTag": "direct"
},
{
"type": "field",
"port": "0-65535",
"outboundTag": "proxy"
}
]
}
}
+21 -1
View File
@@ -8,6 +8,10 @@ module github.com/v2rayA/v2raya-core
go 1.26
require (
anytls v0.0.12
github.com/daeuniverse/softwind v0.0.0-20231230065827-eed67f20d2c1
github.com/juicity/juicity v0.4.0
github.com/sagernet/sing v0.5.1
github.com/xtls/xray-core v0.0.0-local
google.golang.org/grpc v1.79.3
google.golang.org/protobuf v1.36.11
@@ -16,23 +20,37 @@ require (
require (
github.com/andybalholm/brotli v1.0.6 // indirect
github.com/apernet/quic-go v0.59.1-0.20260217092621-db4786c77a22 // indirect
github.com/chen3feng/stl4go v0.1.1 // indirect
github.com/cloudflare/circl v1.6.3 // indirect
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d // indirect
github.com/dgryski/go-idea v0.0.0-20170306091226-d2fb45a411fb // indirect
github.com/dgryski/go-rc2 v0.0.0-20150621095337-8a9021637152 // indirect
github.com/eknkc/basex v1.0.1 // indirect
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 // indirect
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect
github.com/google/btree v1.1.2 // indirect
github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/juju/ratelimit v1.0.2 // indirect
github.com/klauspost/compress v1.17.4 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/miekg/dns v1.1.72 // indirect
github.com/mzz2017/disk-bloom v1.0.1 // indirect
github.com/mzz2017/quic-go v0.0.0-20231230054300-5221ce9164a3 // indirect
github.com/onsi/ginkgo/v2 v2.11.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pires/go-proxyproto v0.11.0 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/qtls-go1-20 v0.4.1 // indirect
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af // indirect
github.com/sagernet/sing v0.5.1 // indirect
github.com/sagernet/sing-shadowsocks v0.2.7 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/vishvananda/netlink v1.3.1 // indirect
github.com/vishvananda/netns v0.0.5 // indirect
github.com/xtls/reality v0.0.0-20260322125925-9234c772ba8f // indirect
gitlab.com/yawning/chacha20.git v0.0.0-20230427033715-7877545b1b37 // indirect
go.uber.org/mock v0.5.2 // indirect
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
golang.org/x/crypto v0.49.0 // indirect
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
@@ -52,3 +70,5 @@ require (
)
replace github.com/xtls/xray-core => ./xray
replace anytls v0.0.12 => github.com/anytls/anytls-go v0.0.12
+44
View File
@@ -1,19 +1,38 @@
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/anytls/anytls-go v0.0.12 h1:8suDc6MJ7/OznxXYOnB2EVcXX/hAtPwOTsZyD8yD/Xc=
github.com/anytls/anytls-go v0.0.12/go.mod h1:8vNBmLZiH8Cyb4/pPnlVzCIr/9JRADAHqlw4TZaY0Ag=
github.com/apernet/quic-go v0.59.1-0.20260217092621-db4786c77a22 h1:00ziBGnLWQEcR9LThDwvxOznJJquJ9bYUdmBFnawLMU=
github.com/apernet/quic-go v0.59.1-0.20260217092621-db4786c77a22/go.mod h1:Npbg8qBtAZlsAB3FWmqwlVh5jtVG6a4DlYsOylUpvzA=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chen3feng/stl4go v0.1.1 h1:0L1+mDw7pomftKDruM23f1mA7miavOj6C6MZeadzN2Q=
github.com/chen3feng/stl4go v0.1.1/go.mod h1:5ml3psLgETJjRJnMbPE+JiHLrCpt+Ajc2weeTECXzWU=
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
github.com/daeuniverse/softwind v0.0.0-20231230065827-eed67f20d2c1 h1:qh16GLF9TfntnLIwos49rj7Yj4EHICDe9ToesIjTm1c=
github.com/daeuniverse/softwind v0.0.0-20231230065827-eed67f20d2c1/go.mod h1:ly72DcZIxHlKbOEz1qaSCh99lr7ns8T5JLpfww8hXrI=
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/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d h1:CPqTNIigGweVPT4CYb+OO2E6XyRKFOmvTHwWRLgCAlE=
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d/go.mod h1:QX5ZVULjAfZJux/W62Y91HvCh9hyW6enAwcrrv/sLj0=
github.com/dgryski/go-idea v0.0.0-20170306091226-d2fb45a411fb h1:zXpN5126w/mhECTkqazBkrOJIMatbPP71aSIDR5UuW4=
github.com/dgryski/go-idea v0.0.0-20170306091226-d2fb45a411fb/go.mod h1:F7WkpqJj9t98ePxB/WJGQTIDeOVPuSJ3qdn6JUjg170=
github.com/dgryski/go-rc2 v0.0.0-20150621095337-8a9021637152 h1:ED31mPIxDJnrLt9W9dH5xgd/6KjzEACKHBVGQ33czc0=
github.com/dgryski/go-rc2 v0.0.0-20150621095337-8a9021637152/go.mod h1:I9fhc/EvSg88cDxmfQ47v35Ssz9rlFunL/KY0A1JAYI=
github.com/ebfe/rc2 v0.0.0-20131011165748-24b9757f5521 h1:fBHFH+Y/GPGFGo7LIrErQc3p2MeAhoIQNgaxPWYsSxk=
github.com/ebfe/rc2 v0.0.0-20131011165748-24b9757f5521/go.mod h1:ucvhdsUCE3TH0LoLRb6ShHiJl8e39dGlx6A4g/ujlow=
github.com/eknkc/basex v1.0.1 h1:TcyAkqh4oJXgV3WYyL4KEfCMk9W8oJCpmx1bo+jVgKY=
github.com/eknkc/basex v1.0.1/go.mod h1:k/F/exNEHFdbs3ZHuasoP2E7zeWwZblG84Y7Z59vQRo=
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4=
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344/go.mod h1:GIjDIg/heH5DOkXY3YJ/wNhfHsQHoXGjl8G8amsYQ1I=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls=
github.com/golang/mock v1.7.0-rc.1 h1:YojYx61/OLFsiv6Rw1Z96LpldJIy31o+UHmwAUMJ6/U=
github.com/golang/mock v1.7.0-rc.1/go.mod h1:s42URUywIqd+OcERslBJvOjepvNymP31m3q8d/GkuRs=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
@@ -22,10 +41,14 @@ github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU=
github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 h1:n6vlPhxsA+BW/XsS5+uqi7GyzaLa5MH7qlSLBZtRdiA=
github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/juicity/juicity v0.4.0 h1:UGdiCar+lWoP+m2Uau3JVh31vEh5tDDGGk7pRqRwuWY=
github.com/juicity/juicity v0.4.0/go.mod h1:w8EriA7EyeHzagZ3K3lF1SdNa5HVjFg4m5vFFbHEhIw=
github.com/juju/ratelimit v1.0.2 h1:sRxmtRiajbvrcLQT7S+JbqU0ntsb9W2yhSdNN8tWfaI=
github.com/juju/ratelimit v1.0.2/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=
@@ -38,6 +61,14 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
github.com/mzz2017/disk-bloom v1.0.1 h1:rEF9MiXd9qMW3ibRpqcerLXULoTgRlM21yqqJl1B90M=
github.com/mzz2017/disk-bloom v1.0.1/go.mod h1:JLHETtUu44Z6iBmsqzkOtFlRvXSlKnxjwiBRDapizDI=
github.com/mzz2017/quic-go v0.0.0-20231230054300-5221ce9164a3 h1:V0C+4ZV0TzzKH05TAjtxAKODudB5dKyO6rayhtSO55I=
github.com/mzz2017/quic-go v0.0.0-20231230054300-5221ce9164a3/go.mod h1:RVldHw4emztg37XspqsQSOqptlBuYTCHD/brBTROQSw=
github.com/onsi/ginkgo/v2 v2.11.0 h1:WgqUCUt/lT6yXoQ8Wef0fsNn5cAuMK7+KT9UFRz2tcU=
github.com/onsi/ginkgo/v2 v2.11.0/go.mod h1:ZhrRA5XmEE3x3rhlzamx/JJvujdZoJ2uvgI7kR0iZvM=
github.com/onsi/gomega v1.27.8 h1:gegWiwZjBsf2DgiSbf5hpokZ98JVDMcWkUiigk6/KXc=
github.com/onsi/gomega v1.27.8/go.mod h1:2J8vzI/s+2shY9XHRApDkdgPo1TKT7P2u6fXeJKFnNQ=
github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pires/go-proxyproto v0.11.0 h1:gUQpS85X/VJMdUsYyEgyn59uLJvGqPhJV5YvG68wXH4=
@@ -46,6 +77,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/qtls-go1-20 v0.4.1 h1:D33340mCNDAIKBqXuAvexTNMUByrYmFYVfKfDN5nfFs=
github.com/quic-go/qtls-go1-20 v0.4.1/go.mod h1:X9Nh97ZL80Z+bX/gUXMbipO6OxdiDi58b/fMC9mAL+k=
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af h1:er2acxbi3N1nvEq6HXHUAR1nTWEJmQfqiGR8EVT9rfs=
github.com/refraction-networking/utls v1.8.3-0.20260301010127-aa6edf4b11af/go.mod h1:jkSOEkLqn+S/jtpEHPOsVv/4V4EVnelwbMQl4vCWXAM=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
@@ -54,6 +87,12 @@ 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/sagernet/sing-shadowsocks v0.2.7 h1:zaopR1tbHEw5Nk6FAkM05wCslV6ahVegEZaKMv9ipx8=
github.com/sagernet/sing-shadowsocks v0.2.7/go.mod h1:0rIKJZBR65Qi0zwdKezt4s57y/Tl1ofkaq6NlkzVuyE=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=
@@ -62,6 +101,8 @@ github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zd
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
github.com/xtls/reality v0.0.0-20260322125925-9234c772ba8f h1:iy2JRioxmUpoJ3SzbFPyTxHZMbR/rSHP7dOOgYaq1O8=
github.com/xtls/reality v0.0.0-20260322125925-9234c772ba8f/go.mod h1:DsJblcWDGt76+FVqBVwbwRhxyyNJsGV48gJLch0OOWI=
gitlab.com/yawning/chacha20.git v0.0.0-20230427033715-7877545b1b37 h1:ZrWBE3u/o9cHU2mySXf1687MaK09JOeZt1A+fHnCjmU=
gitlab.com/yawning/chacha20.git v0.0.0-20230427033715-7877545b1b37/go.mod h1:3x6b94nWCP/a2XB/joOPMiGYUBvqbLfeY/BkHLeDs6s=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=
@@ -88,6 +129,8 @@ 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/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190902133755-9109b7679e13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
@@ -116,6 +159,7 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
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=
gvisor.dev/gvisor v0.0.0-20260122175437-89a5d21be8f0 h1:Lk6hARj5UPY47dBep70OD/TIMwikJ5fGUGX0Rm3Xigk=
@@ -0,0 +1,131 @@
// Package command implements the v2ray-compatible ObservatoryService gRPC endpoint.
// This is structurally derived from v2ray's app/observatory/command/command.go,
// adapted to use xray's interfaces. The gRPC service is registered under the
// v2ray service name "v2ray.core.app.observatory.command.ObservatoryService" so
// that v2rayA's ObservatoryProducer can query it natively.
//
// The request type (GetOutboundStatusRequest) has a Tag field (proto field 1)
// that identifies the balancer group. The response uses xray's GetOutboundStatusResponse
// which is wire-compatible with v2ray's (identical field numbers).
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package command
import (
"context"
"github.com/v2rayA/v2raya-core/hint/app/observatory/multiobservatory"
xray_obs "github.com/xtls/xray-core/app/observatory"
xray_obs_cmd "github.com/xtls/xray-core/app/observatory/command"
"github.com/xtls/xray-core/common"
core "github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/features/extension"
"google.golang.org/grpc"
"google.golang.org/protobuf/proto"
)
// service implements the v2ray ObservatoryService using xray's observatory.
// It is structurally identical to v2ray's command.go service but uses xray's
// extension.Observatory and xray's GetOutboundStatusResponse internally.
type service struct {
v *core.Instance
observatory extension.Observatory
}
// GetOutboundStatus returns the observation result for the given balancer group tag.
// If tag is empty, all groups are aggregated. This matches v2ray's behavior.
func (s *service) GetOutboundStatus(ctx context.Context, req *GetOutboundStatusRequest) (*xray_obs_cmd.GetOutboundStatusResponse, error) {
if s.observatory == nil {
return &xray_obs_cmd.GetOutboundStatusResponse{}, nil
}
return s.getByTag(ctx, req.GetTag())
}
// getByTag routes the query to the correct observatory group.
// If the observatory is a MultiObservatory (v2rayA multi-group), it uses per-tag lookup.
// Otherwise, it calls GetObservation() to return all results.
func (s *service) getByTag(ctx context.Context, tag string) (*xray_obs_cmd.GetOutboundStatusResponse, error) {
if mo, ok := s.observatory.(*multiobservatory.MultiObservatory); ok {
result, err := mo.GetObservationByTag(tag, ctx)
if err != nil {
return nil, err
}
if obs, ok := result.(*xray_obs.ObservationResult); ok {
return &xray_obs_cmd.GetOutboundStatusResponse{Status: obs}, nil
}
}
result, err := s.observatory.GetObservation(ctx)
if err != nil {
return nil, err
}
if obs, ok := result.(*xray_obs.ObservationResult); ok {
return &xray_obs_cmd.GetOutboundStatusResponse{Status: obs}, nil
}
return &xray_obs_cmd.GetOutboundStatusResponse{}, nil
}
// Register implements commander.Service.
// It registers the ObservatoryService under the v2ray gRPC path so v2rayA can
// query it. The response type (xray's GetOutboundStatusResponse) is wire-
// compatible with v2ray's because both have identical proto field numbers.
func (s *service) Register(server *grpc.Server) {
server.RegisterService(&v2rayObservatoryServiceDesc, s)
}
// v2rayObservatoryServiceDesc is the gRPC ServiceDesc for
// v2ray.core.app.observatory.command.ObservatoryService.
// This mirrors v2ray's RegisterObservatoryServiceServer but without importing
// the v2fly module, to avoid proto type registry conflicts with xray.
var v2rayObservatoryServiceDesc = grpc.ServiceDesc{
ServiceName: "v2ray.core.app.observatory.command.ObservatoryService",
HandlerType: (*interface{})(nil), // using raw handler; type is checked via closure
Methods: []grpc.MethodDesc{
{
MethodName: "GetOutboundStatus",
Handler: getOutboundStatusHandler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "app/observatory/command/command.proto",
}
// getOutboundStatusHandler is the gRPC unary handler for GetOutboundStatus.
// It decodes the request as GetOutboundStatusRequest (which has Tag=field1) so
// the Tag is populated directly — no protowire extraction needed.
func getOutboundStatusHandler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetOutboundStatusRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(*service).GetOutboundStatus(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/v2ray.core.app.observatory.command.ObservatoryService/GetOutboundStatus",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(*service).GetOutboundStatus(ctx, req.(*GetOutboundStatusRequest))
}
return interceptor(ctx, in, info, handler)
}
// init registers this service's Config in xray's common registry so xray's commander
// can instantiate it from the TypedMessage in the config file.
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
s := core.MustFromContext(ctx)
sv := &service{v: s}
// RequireFeatures with optional=true: if no observatory is configured, the
// service still starts but returns empty results.
_ = s.RequireFeatures(func(obs extension.Observatory) {
sv.observatory = obs
}, true)
return sv, nil
}))
}
// Ensure proto.Message is imported (used for type assertion in getByTag).
var _ proto.Message = (*GetOutboundStatusRequest)(nil)
@@ -0,0 +1,160 @@
// Code generated manually for v2raya-core.
// Defines v2ray-compatible observatory command messages.
// Proto package: v2ray.core.app.observatory.command
// Source: hint/app/observatory/command/config.proto
package command
import (
reflect "reflect"
sync "sync"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
)
// GetOutboundStatusRequest is the v2ray-compatible request for querying observatory.
// Tag field (proto field 1, string) is wire-identical to v2ray's GetOutboundStatusRequest,
// so v2rayA's ObservatoryProducer requests are decoded correctly without protowire extraction.
type GetOutboundStatusRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Tag string `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetOutboundStatusRequest) Reset() {
*x = GetOutboundStatusRequest{}
mi := &file_hint_app_observatory_command_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetOutboundStatusRequest) String() string { return protoimpl.X.MessageStringOf(x) }
func (*GetOutboundStatusRequest) ProtoMessage() {}
func (x *GetOutboundStatusRequest) ProtoReflect() protoreflect.Message {
mi := &file_hint_app_observatory_command_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
func (*GetOutboundStatusRequest) Descriptor() ([]byte, []int) {
return file_hint_app_observatory_command_config_proto_rawDescGZIP(), []int{0}
}
func (x *GetOutboundStatusRequest) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
// Config is the empty marker config for registering this service in xray's commander.
type Config struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Config) Reset() {
*x = Config{}
mi := &file_hint_app_observatory_command_config_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Config) String() string { return protoimpl.X.MessageStringOf(x) }
func (*Config) ProtoMessage() {}
func (x *Config) ProtoReflect() protoreflect.Message {
mi := &file_hint_app_observatory_command_config_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
func (*Config) Descriptor() ([]byte, []int) {
return file_hint_app_observatory_command_config_proto_rawDescGZIP(), []int{1}
}
var File_hint_app_observatory_command_config_proto protoreflect.FileDescriptor
// rawDesc encodes the FileDescriptorProto for (len=205):
//
// syntax = "proto3";
// package v2ray.core.app.observatory.command;
// option go_package = "github.com/v2rayA/v2raya-core/hint/app/observatory/command";
// message GetOutboundStatusRequest { string tag = 1; }
// message Config {}
var file_hint_app_observatory_command_config_proto_rawDesc = []byte{
0x0a, 0x29, 0x68, 0x69, 0x6e, 0x74, 0x2f, 0x61, 0x70, 0x70, 0x2f, 0x6f, 0x62, 0x73, 0x65, 0x72,
0x76, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x2f, 0x63,
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x22, 0x76, 0x32, 0x72,
0x61, 0x79, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x6f, 0x62, 0x73, 0x65,
0x72, 0x76, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x22,
0x2c, 0x0a, 0x18, 0x47, 0x65, 0x74, 0x4f, 0x75, 0x74, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x53, 0x74,
0x61, 0x74, 0x75, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x74,
0x61, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x74, 0x61, 0x67, 0x22, 0x08, 0x0a,
0x06, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x42, 0x3c, 0x5a, 0x3a, 0x67, 0x69, 0x74, 0x68, 0x75,
0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x76, 0x32, 0x72, 0x61, 0x79, 0x41, 0x2f, 0x76, 0x32, 0x72,
0x61, 0x79, 0x61, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x68, 0x69, 0x6e, 0x74, 0x2f, 0x61, 0x70,
0x70, 0x2f, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x2f, 0x63, 0x6f,
0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_hint_app_observatory_command_config_proto_rawDescOnce sync.Once
file_hint_app_observatory_command_config_proto_rawDescData []byte
)
func file_hint_app_observatory_command_config_proto_rawDescGZIP() []byte {
file_hint_app_observatory_command_config_proto_rawDescOnce.Do(func() {
file_hint_app_observatory_command_config_proto_rawDescData = protoimpl.X.CompressGZIP(
file_hint_app_observatory_command_config_proto_rawDesc,
)
})
return file_hint_app_observatory_command_config_proto_rawDescData
}
var file_hint_app_observatory_command_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_hint_app_observatory_command_config_proto_goTypes = []any{
(*GetOutboundStatusRequest)(nil), // 0: v2ray.core.app.observatory.command.GetOutboundStatusRequest
(*Config)(nil), // 1: v2ray.core.app.observatory.command.Config
}
var file_hint_app_observatory_command_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_hint_app_observatory_command_config_proto_init() }
func file_hint_app_observatory_command_config_proto_init() {
if File_hint_app_observatory_command_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_hint_app_observatory_command_config_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_hint_app_observatory_command_config_proto_goTypes,
DependencyIndexes: file_hint_app_observatory_command_config_proto_depIdxs,
MessageInfos: file_hint_app_observatory_command_config_proto_msgTypes,
}.Build()
File_hint_app_observatory_command_config_proto = out.File
file_hint_app_observatory_command_config_proto_goTypes = nil
file_hint_app_observatory_command_config_proto_depIdxs = nil
}
-137
View File
@@ -1,137 +0,0 @@
// Package compat provides a v2ray-compatible observatory gRPC service.
// It registers the ObservatoryService under the v2ray gRPC service path
// so that v2rayA can query v2raya-core using its existing v2ray observatory client.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package compat
import (
"context"
xray_obs "github.com/xtls/xray-core/app/observatory"
xray_obs_cmd "github.com/xtls/xray-core/app/observatory/command"
"github.com/xtls/xray-core/common"
core "github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/features/extension"
"github.com/v2rayA/v2raya-core/hint/app/observatory/multiobservatory"
"google.golang.org/grpc"
"google.golang.org/protobuf/encoding/protowire"
)
// v2RayCompatServiceName is the full gRPC service name used by v2ray-core and v2rayA.
const v2RayCompatServiceName = "v2ray.core.app.observatory.command.ObservatoryService"
// compatService implements commander.Service to register under the v2ray gRPC path.
type compatService struct {
v *core.Instance
observatory extension.Observatory
}
// Register implements commander.Service; registers under the v2ray service name.
func (s *compatService) Register(server *grpc.Server) {
desc := &grpc.ServiceDesc{
ServiceName: v2RayCompatServiceName,
HandlerType: (*xray_obs_cmd.ObservatoryServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GetOutboundStatus",
Handler: s.handleGetOutboundStatus,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "app/observatory/command/command.proto",
}
server.RegisterService(desc, s)
}
// handleGetOutboundStatus serves GetOutboundStatus RPCs on the v2ray compat path.
// The v2ray client sends GetOutboundStatusRequest with a Tag field (proto field 1, string).
// We decode the Tag using protowire to enable per-group observatory queries.
func (s *compatService) handleGetOutboundStatus(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
req := &xray_obs_cmd.GetOutboundStatusRequest{}
if err := dec(req); err != nil {
return nil, err
}
// xray's GetOutboundStatusRequest has no Tag field; the tag was dropped by proto.Unmarshal.
// We cannot recover it here without a custom codec. Fall back to aggregate.
tag := extractTagFromContext(ctx)
handler := func(ctx context.Context, _ interface{}) (interface{}, error) {
return s.getByTag(ctx, tag)
}
if interceptor != nil {
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/" + v2RayCompatServiceName + "/GetOutboundStatus",
}
return interceptor(ctx, req, info, handler)
}
return handler(ctx, req)
}
// getByTag queries per-group when the observatory is a MultiObservatory, otherwise aggregates.
func (s *compatService) getByTag(ctx context.Context, tag string) (*xray_obs_cmd.GetOutboundStatusResponse, error) {
if mo, ok := s.observatory.(*multiobservatory.MultiObservatory); ok {
result, err := mo.GetObservationByTag(tag, ctx)
if err != nil {
return nil, err
}
if obs, ok := result.(*xray_obs.ObservationResult); ok {
return &xray_obs_cmd.GetOutboundStatusResponse{Status: obs}, nil
}
}
result, err := s.observatory.GetObservation(ctx)
if err != nil {
return nil, err
}
if obs, ok := result.(*xray_obs.ObservationResult); ok {
return &xray_obs_cmd.GetOutboundStatusResponse{Status: obs}, nil
}
return &xray_obs_cmd.GetOutboundStatusResponse{}, nil
}
// extractTagFromContext is a placeholder; gRPC-Go does not expose raw request bytes
// through standard interceptors. Per-tag routing requires a custom codec.
// For now, returns empty string (aggregate mode).
func extractTagFromContext(_ context.Context) string { return "" }
// extractTag decodes proto field 1 (string) from raw serialized bytes.
// Used when raw request bytes are available (e.g. custom codec path).
func extractTag(data []byte) string {
for len(data) > 0 {
num, typ, n := protowire.ConsumeTag(data)
if n < 0 {
break
}
data = data[n:]
if num == 1 && typ == protowire.BytesType {
v, n := protowire.ConsumeBytes(data)
if n < 0 {
break
}
return string(v)
}
n = protowire.ConsumeFieldValue(num, typ, data)
if n < 0 {
break
}
data = data[n:]
}
return ""
}
func init() {
common.Must(common.RegisterConfig((*CompatConfig)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
s := core.MustFromContext(ctx)
sv := &compatService{v: s}
err := s.RequireFeatures(func(obs extension.Observatory) {
sv.observatory = obs
}, false)
if err != nil {
return nil, err
}
return sv, nil
}))
}
@@ -1,112 +0,0 @@
// Code generated manually for v2raya-core.
// source: hint/app/observatory/compat/config.proto
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
package compat
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
// CompatConfig is a marker config type that enables the v2ray-compatible
// observatory gRPC service when included in the commander's service list.
type CompatConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CompatConfig) Reset() {
*x = CompatConfig{}
mi := &file_hint_app_observatory_compat_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CompatConfig) String() string { return protoimpl.X.MessageStringOf(x) }
func (*CompatConfig) ProtoMessage() {}
func (x *CompatConfig) ProtoReflect() protoreflect.Message {
mi := &file_hint_app_observatory_compat_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
func (*CompatConfig) Descriptor() ([]byte, []int) {
return file_hint_app_observatory_compat_config_proto_rawDescGZIP(), []int{0}
}
var (
file_hint_app_observatory_compat_config_proto_rawDescOnce sync.Once
file_hint_app_observatory_compat_config_proto_rawDescData []byte
)
func file_hint_app_observatory_compat_config_proto_rawDescGZIP() []byte {
file_hint_app_observatory_compat_config_proto_rawDescOnce.Do(func() {
file_hint_app_observatory_compat_config_proto_rawDescData =
file_hint_app_observatory_compat_config_proto_rawDesc
})
return file_hint_app_observatory_compat_config_proto_rawDescData
}
// rawDesc is the proto FileDescriptorProto for this package.
// Generated by encoding:
// syntax = "proto3";
// package v2raya.core.hint.app.observatory.compat;
// option go_package = "github.com/v2rayA/v2raya-core/hint/app/observatory/compat";
// message CompatConfig {}
var file_hint_app_observatory_compat_config_proto_rawDesc = []byte{
0x0a, 0x28, 0x68, 0x69, 0x6e, 0x74, 0x2f, 0x61, 0x70, 0x70, 0x2f, 0x6f, 0x62, 0x73, 0x65, 0x72,
0x76, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x2f, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x2f, 0x63, 0x6f,
0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x27, 0x76, 0x32, 0x72, 0x61,
0x79, 0x61, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x2e, 0x68, 0x69, 0x6e, 0x74, 0x2e, 0x61, 0x70, 0x70,
0x2e, 0x6f, 0x62, 0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x2e, 0x63, 0x6f, 0x6d,
0x70, 0x61, 0x74, 0x22, 0x0e, 0x0a, 0x0c, 0x43, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x43, 0x6f, 0x6e,
0x66, 0x69, 0x67, 0x42, 0x3b, 0x5a, 0x39, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f,
0x6d, 0x2f, 0x76, 0x32, 0x72, 0x61, 0x79, 0x41, 0x2f, 0x76, 0x32, 0x72, 0x61, 0x79, 0x61, 0x2d,
0x63, 0x6f, 0x72, 0x65, 0x2f, 0x68, 0x69, 0x6e, 0x74, 0x2f, 0x61, 0x70, 0x70, 0x2f, 0x6f, 0x62,
0x73, 0x65, 0x72, 0x76, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x2f, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74,
0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_hint_app_observatory_compat_config_proto_goTypes = []any{(*CompatConfig)(nil)}
file_hint_app_observatory_compat_config_proto_depIdxs = []int32{0, 0, 0, 0}
file_hint_app_observatory_compat_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
File_hint_app_observatory_compat_config_proto protoreflect.FileDescriptor
)
func init() { file_hint_app_observatory_compat_config_proto_init() }
func file_hint_app_observatory_compat_config_proto_init() {
if File_hint_app_observatory_compat_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_hint_app_observatory_compat_config_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_hint_app_observatory_compat_config_proto_goTypes,
DependencyIndexes: file_hint_app_observatory_compat_config_proto_depIdxs,
MessageInfos: file_hint_app_observatory_compat_config_proto_msgTypes,
}.Build()
File_hint_app_observatory_compat_config_proto = out.File
file_hint_app_observatory_compat_config_proto_goTypes = nil
file_hint_app_observatory_compat_config_proto_depIdxs = nil
}
@@ -6,8 +6,10 @@ package multiobservatory
import (
"context"
"sync"
"time"
"github.com/xtls/xray-core/app/observatory"
xray_obs "github.com/xtls/xray-core/app/observatory"
"github.com/xtls/xray-core/app/observatory/burst"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/features/extension"
"google.golang.org/protobuf/proto"
@@ -55,17 +57,17 @@ func (m *MultiObservatory) GetObservation(ctx context.Context) (proto.Message, e
m.mu.RLock()
defer m.mu.RUnlock()
var combined []*observatory.OutboundStatus
var combined []*xray_obs.OutboundStatus
for _, child := range m.children {
result, err := child.GetObservation(ctx)
if err != nil {
continue
}
if obs, ok := result.(*observatory.ObservationResult); ok {
if obs, ok := result.(*xray_obs.ObservationResult); ok {
combined = append(combined, obs.GetStatus()...)
}
}
return &observatory.ObservationResult{Status: combined}, nil
return &xray_obs.ObservationResult{Status: combined}, nil
}
// GetObservationByTag returns the ObservationResult for a specific group tag.
@@ -89,12 +91,20 @@ func New(ctx context.Context, config *Config) (*MultiObservatory, error) {
}
for _, obs := range config.GetObservers() {
childCfg := &observatory.Config{
SubjectSelector: obs.GetSubjectSelector(),
ProbeUrl: obs.GetProbeUrl(),
ProbeInterval: obs.GetProbeInterval(),
pingCfg := &burst.HealthPingConfig{
Destination: obs.GetProbeUrl(),
Interval: obs.GetProbeInterval(),
}
child, err := observatory.New(ctx, childCfg)
// Keep legacy 10s probing behavior when interval isn't configured.
if pingCfg.Interval == 0 {
pingCfg.Interval = int64(10 * time.Second)
}
childCfg := &burst.Config{
SubjectSelector: obs.GetSubjectSelector(),
PingConfig: pingCfg,
}
child, err := burst.New(ctx, childCfg)
if err != nil {
return nil, err
}
+369 -25
View File
@@ -1,6 +1,8 @@
// Package conf provides a v2raya-core JSON configuration loader.
// It extends xray-core's JSON loader with support for multiObservatory,
// and automatically injects the v2ray-compatible observatory gRPC service.
// It also pre-processes custom protocols (anytls, juicity) from the JSON
// config, strips them before xray parses, then appends the built handlers.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
@@ -13,26 +15,55 @@ import (
"encoding/json"
"io"
obscmd "github.com/v2rayA/v2raya-core/hint/app/observatory/command"
multiobs "github.com/v2rayA/v2raya-core/hint/app/observatory/multiobservatory"
hint_anytls "github.com/v2rayA/v2raya-core/hint/proxy/anytls"
hint_juicity "github.com/v2rayA/v2raya-core/hint/proxy/juicity"
xray_commander "github.com/xtls/xray-core/app/commander"
xray_core "github.com/xtls/xray-core/core"
xray_proxyman "github.com/xtls/xray-core/app/proxyman"
"github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/cmdarg"
"github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/serial"
xray_core "github.com/xtls/xray-core/core"
xray_conf "github.com/xtls/xray-core/infra/conf"
xray_cfgdur "github.com/xtls/xray-core/infra/conf/cfgcommon/duration"
conf_serial "github.com/xtls/xray-core/infra/conf/serial"
"github.com/xtls/xray-core/main/confloader"
compat "github.com/v2rayA/v2raya-core/hint/app/observatory/compat"
multiobs "github.com/v2rayA/v2raya-core/hint/app/observatory/multiobservatory"
)
// multiObsEntryJSON represents one observer group in the JSON config.
type multiObsEntryJSON struct {
Tag string `json:"tag"`
ProbeURL string `json:"probeURL"`
ProbeInterval xray_cfgdur.Duration `json:"probeInterval"`
SubjectSelector []string `json:"subjectSelector"`
Tag string `json:"tag"`
ProbeURL string `json:"probeURL"`
ProbeInterval xray_cfgdur.Duration `json:"probeInterval"`
SubjectSelector []string `json:"subjectSelector"`
Settings *obsSettingsJSON `json:"settings"`
Burst *burstObsJSON `json:"burstObservatory"`
}
// pingConfigJSON is the v5 PingConfigObject used by burstObservatory.
type pingConfigJSON struct {
Destination string `json:"destination"`
Connectivity string `json:"connectivity"`
Interval xray_cfgdur.Duration `json:"interval"`
SamplingCount int `json:"samplingCount"`
Timeout xray_cfgdur.Duration `json:"timeout"`
HTTPMethod string `json:"httpMethod"`
}
// obsSettingsJSON supports legacy observatory fields and v5 pingConfig.
type obsSettingsJSON struct {
SubjectSelector []string `json:"subjectSelector"`
ProbeURL string `json:"probeURL"`
ProbeInterval xray_cfgdur.Duration `json:"probeInterval"`
PingConfig *pingConfigJSON `json:"pingConfig"`
}
// burstObsJSON matches v5 burstObservatory object shape.
type burstObsJSON struct {
SubjectSelector []string `json:"subjectSelector"`
PingConfig *pingConfigJSON `json:"pingConfig"`
}
// multiObsJSON is the top-level JSON structure for the multiObservatory field.
@@ -43,24 +74,236 @@ type multiObsJSON struct {
// extendedJSON captures v2raya-core extension fields alongside standard xray JSON.
type extendedJSON struct {
MultiObservatory *multiObsJSON `json:"multiObservatory"`
BurstObservatory *burstObsJSON `json:"burstObservatory"`
}
// customOutboundJSON is the raw JSON form of an anytls or juicity outbound.
type customOutboundJSON struct {
Protocol string `json:"protocol"`
Tag string `json:"tag"`
Settings json.RawMessage `json:"settings"`
}
// customProtocols is the set of outbound protocols handled by hint/proxy.
var customProtocols = map[string]bool{
"anytls": true,
"juicity": true,
}
// stripCustomOutbounds parses raw JSON, removes custom-protocol outbound entries,
// and returns the modified JSON along with the stripped outbound descriptors.
// If the JSON is not valid or has no outbounds, raw is returned unchanged with
// nil custom list (safe to pass to xray unmodified).
func stripCustomOutbounds(raw []byte) ([]byte, []customOutboundJSON, error) {
var doc map[string]json.RawMessage
if err := json.Unmarshal(raw, &doc); err != nil {
return raw, nil, nil
}
outboundsRaw, ok := doc["outbounds"]
if !ok {
return raw, nil, nil
}
var outbounds []json.RawMessage
if err := json.Unmarshal(outboundsRaw, &outbounds); err != nil {
return raw, nil, nil
}
var remaining []json.RawMessage
var custom []customOutboundJSON
for _, ob := range outbounds {
var probe struct {
Protocol string `json:"protocol"`
}
if err := json.Unmarshal(ob, &probe); err != nil {
remaining = append(remaining, ob)
continue
}
if customProtocols[probe.Protocol] {
var c customOutboundJSON
if err := json.Unmarshal(ob, &c); err == nil {
custom = append(custom, c)
}
} else {
remaining = append(remaining, ob)
}
}
if len(custom) == 0 {
return raw, nil, nil
}
newOutbounds, err := json.Marshal(remaining)
if err != nil {
return raw, nil, err
}
doc["outbounds"] = newOutbounds
modified, err := json.Marshal(doc)
if err != nil {
return raw, nil, err
}
return modified, custom, nil
}
// buildCustomOutbounds converts stripped custom outbound JSON descriptors into
// xray OutboundHandlerConfig proto messages ready to append to coreConfig.Outbound.
func buildCustomOutbounds(customs []customOutboundJSON) ([]*xray_core.OutboundHandlerConfig, error) {
result := make([]*xray_core.OutboundHandlerConfig, 0, len(customs))
for _, c := range customs {
var proxySettings *serial.TypedMessage
switch c.Protocol {
case "anytls":
var cfg hint_anytls.ClientConfig
if c.Settings != nil {
if err := json.Unmarshal(c.Settings, &cfg); err != nil {
return nil, errors.New("invalid anytls settings for tag ", c.Tag).Base(err)
}
}
proxySettings = serial.ToTypedMessage(&cfg)
case "juicity":
var cfg hint_juicity.ClientConfig
if c.Settings != nil {
if err := json.Unmarshal(c.Settings, &cfg); err != nil {
return nil, errors.New("invalid juicity settings for tag ", c.Tag).Base(err)
}
}
proxySettings = serial.ToTypedMessage(&cfg)
default:
continue
}
result = append(result, &xray_core.OutboundHandlerConfig{
Tag: c.Tag,
SenderSettings: serial.ToTypedMessage(&xray_proxyman.SenderConfig{}),
ProxySettings: proxySettings,
})
}
return result, nil
}
// injectMultiObservatory appends the multiobservatory.Config TypedMessage to coreConfig.App.
func injectMultiObservatory(coreConfig *xray_core.Config, mo *multiObsJSON) {
cfg := &multiobs.Config{}
for _, e := range mo.Observers {
cfg.Observers = append(cfg.Observers, &multiobs.ObserverConfig{
Tag: e.Tag,
ProbeUrl: e.ProbeURL,
ProbeInterval: int64(e.ProbeInterval),
SubjectSelector: e.SubjectSelector,
})
observer := normalizeObserverConfig(e)
if observer == nil {
continue
}
cfg.Observers = append(cfg.Observers, observer)
}
if len(cfg.Observers) == 0 {
return
}
coreConfig.App = append(coreConfig.App, serial.ToTypedMessage(cfg))
}
// injectCompatService adds compat.CompatConfig to the commander's service list.
// If no commander is found (no api section), this is a no-op.
// injectBurstObservatoryAsMulti adapts v5 burstObservatory to a single-group MultiObservatory.
// This keeps v2rayA's per-tag API path working: unknown tag requests fall back to aggregated result.
func injectBurstObservatoryAsMulti(coreConfig *xray_core.Config, burst *burstObsJSON) {
if burst == nil || len(burst.SubjectSelector) == 0 {
return
}
observer := &multiobs.ObserverConfig{
Tag: "_burst_global",
SubjectSelector: burst.SubjectSelector,
}
if burst.PingConfig != nil {
observer.ProbeUrl = burst.PingConfig.Destination
observer.ProbeInterval = int64(burst.PingConfig.Interval)
}
cfg := &multiobs.Config{Observers: []*multiobs.ObserverConfig{observer}}
coreConfig.App = append(coreConfig.App, serial.ToTypedMessage(cfg))
}
// normalizeObserverConfig converts legacy + v5 observatory JSON into one runtime observer config.
func normalizeObserverConfig(e multiObsEntryJSON) *multiobs.ObserverConfig {
subjectSelector := e.SubjectSelector
probeURL := e.ProbeURL
probeInterval := e.ProbeInterval
if e.Settings != nil {
if len(subjectSelector) == 0 {
subjectSelector = e.Settings.SubjectSelector
}
if probeURL == "" {
probeURL = e.Settings.ProbeURL
}
if probeInterval == 0 {
probeInterval = e.Settings.ProbeInterval
}
if e.Settings.PingConfig != nil {
if probeURL == "" {
probeURL = e.Settings.PingConfig.Destination
}
if probeInterval == 0 {
probeInterval = e.Settings.PingConfig.Interval
}
}
}
if e.Burst != nil {
if len(subjectSelector) == 0 {
subjectSelector = e.Burst.SubjectSelector
}
if e.Burst.PingConfig != nil {
if probeURL == "" {
probeURL = e.Burst.PingConfig.Destination
}
if probeInterval == 0 {
probeInterval = e.Burst.PingConfig.Interval
}
}
}
if len(subjectSelector) == 0 {
return nil
}
return &multiobs.ObserverConfig{
Tag: e.Tag,
ProbeUrl: probeURL,
ProbeInterval: int64(probeInterval),
SubjectSelector: subjectSelector,
}
}
// reorderAppsForAPIReadiness ensures the commander (API/gRPC) app starts before
// the proxyman inbound manager. By default, xray puts InboundConfig first in
// config.App, which means the API port becomes connectable before the gRPC server
// is running — causing "did not connect: context deadline exceeded" from v2rayA's
// ObservatoryProducer. Moving the commander before InboundConfig fixes this race.
func reorderAppsForAPIReadiness(coreConfig *xray_core.Config) {
const commanderType = "xray.app.commander.Config"
const inboundMgrType = "xray.app.proxyman.InboundConfig"
commanderIdx := -1
inboundIdx := -1
for i, app := range coreConfig.App {
switch app.Type {
case commanderType:
commanderIdx = i
case inboundMgrType:
inboundIdx = i
}
}
// Only reorder if commander exists and is after the inbound manager.
if commanderIdx <= inboundIdx || commanderIdx < 0 || inboundIdx < 0 {
return
}
commander := coreConfig.App[commanderIdx]
newApp := make([]*serial.TypedMessage, 0, len(coreConfig.App))
for i, app := range coreConfig.App {
if i == inboundIdx {
newApp = append(newApp, commander)
}
if i != commanderIdx {
newApp = append(newApp, app)
}
}
coreConfig.App = newApp
}
// injectObsCommandService adds the v2ray-compatible ObservatoryService to the commander's
// service list. If no commander is found (no api section), this is a no-op.
func injectCompatService(coreConfig *xray_core.Config) {
const commanderType = "xray.app.commander.Config"
for i, app := range coreConfig.App {
@@ -75,7 +318,7 @@ func injectCompatService(coreConfig *xray_core.Config) {
if !ok {
continue
}
cmdCfg.Service = append(cmdCfg.Service, serial.ToTypedMessage(&compat.CompatConfig{}))
cmdCfg.Service = append(cmdCfg.Service, serial.ToTypedMessage(&obscmd.Config{}))
coreConfig.App[i] = serial.ToTypedMessage(cmdCfg)
return
}
@@ -83,38 +326,114 @@ func injectCompatService(coreConfig *xray_core.Config) {
// loadAndExtend reads a config file, decodes it as xray conf.Config, and
// also extracts the extendedJSON fields (e.g. multiObservatory).
func loadAndExtend(arg string) (*xray_conf.Config, *extendedJSON, error) {
// Custom-protocol outbounds (anytls, juicity) are stripped from the JSON
// before xray processes it, and returned separately.
func loadAndExtend(arg string) (*xray_conf.Config, *extendedJSON, []customOutboundJSON, error) {
r, err := confloader.LoadConfig(arg)
if err != nil {
return nil, nil, errors.New("failed to read config: ", arg).Base(err)
return nil, nil, nil, errors.New("failed to read config: ", arg).Base(err)
}
raw, err := io.ReadAll(r)
if err != nil {
return nil, nil, errors.New("failed to read config bytes: ", arg).Base(err)
return nil, nil, nil, errors.New("failed to read config bytes: ", arg).Base(err)
}
c, err := conf_serial.DecodeJSONConfig(bytes.NewReader(raw))
modified, customs, err := stripCustomOutbounds(raw)
if err != nil {
return nil, nil, errors.New("failed to decode config: ", arg).Base(err)
return nil, nil, nil, errors.New("failed to strip custom outbounds: ", arg).Base(err)
}
c, err := conf_serial.DecodeJSONConfig(bytes.NewReader(modified))
if err != nil {
return nil, nil, nil, errors.New("failed to decode config: ", arg).Base(err)
}
ext := &extendedJSON{}
// Ignore JSON errors here — unknown fields in extendedJSON are fine.
_ = json.Unmarshal(raw, ext)
return c, ext, nil
return c, ext, customs, nil
}
// buildConfigFromFiles is our replacement for xray's serial.BuildConfig.
// It strips anytls/juicity outbounds before xray's infra/conf processes them,
// then appends them as manually-built OutboundHandlerConfig entries.
func buildConfigFromFiles(files []*xray_core.ConfigSource) (*xray_core.Config, error) {
cf := &xray_conf.Config{}
var ext *extendedJSON
var allCustoms []customOutboundJSON
for i, file := range files {
errors.LogInfo(context.Background(), "v2raya-core: reading config: ", file)
r, err := confloader.LoadConfig(file.Name)
if err != nil {
return nil, errors.New("failed to read config: ", file).Base(err)
}
raw, err := io.ReadAll(r)
if err != nil {
return nil, errors.New("failed to read config bytes: ", file).Base(err)
}
// Strip custom outbounds before passing to xray.
modified, customs, err := stripCustomOutbounds(raw)
if err != nil {
return nil, errors.New("failed to strip custom outbounds: ", file).Base(err)
}
allCustoms = append(allCustoms, customs...)
c, err := conf_serial.DecodeJSONConfig(bytes.NewReader(modified))
if err != nil {
return nil, errors.New("failed to decode config: ", file).Base(err)
}
if i == 0 {
*cf = *c
} else {
cf.Override(c, file.Name)
}
e := &extendedJSON{}
_ = json.Unmarshal(raw, e)
if e.MultiObservatory != nil || e.BurstObservatory != nil {
ext = e
}
}
coreConfig, err := cf.Build()
if err != nil {
return nil, err
}
if ext != nil && ext.MultiObservatory != nil {
injectMultiObservatory(coreConfig, ext.MultiObservatory)
} else if ext != nil && ext.BurstObservatory != nil {
injectBurstObservatoryAsMulti(coreConfig, ext.BurstObservatory)
}
injectCompatService(coreConfig)
reorderAppsForAPIReadiness(coreConfig)
if len(allCustoms) > 0 {
customOutbounds, err := buildCustomOutbounds(allCustoms)
if err != nil {
return nil, err
}
coreConfig.Outbound = append(coreConfig.Outbound, customOutbounds...)
}
return coreConfig, nil
}
func init() {
// Override ConfigBuilderForFiles so that when core.LoadConfig is called with cmdarg.Arg,
// custom protocols (anytls, juicity) are stripped before xray's infra/conf processes them,
// then appended as fully built OutboundHandlerConfig entries.
xray_core.ConfigBuilderForFiles = buildConfigFromFiles
common.Must(xray_core.RegisterConfigLoader(&xray_core.ConfigFormat{
Name: "JSON",
Extension: []string{"json"},
Loader: func(input interface{}) (*xray_core.Config, error) {
var ext *extendedJSON
var allCustoms []customOutboundJSON
switch v := input.(type) {
case cmdarg.Arg:
cf := &xray_conf.Config{}
for i, arg := range v {
errors.LogInfo(context.Background(), "v2raya-core: reading config: ", arg)
c, e, err := loadAndExtend(arg)
c, e, customs, err := loadAndExtend(arg)
if err != nil {
return nil, err
}
@@ -124,9 +443,10 @@ func init() {
cf.Override(c, arg)
}
// Use extensions from the last file that defines them.
if e != nil && e.MultiObservatory != nil {
if e != nil && (e.MultiObservatory != nil || e.BurstObservatory != nil) {
ext = e
}
allCustoms = append(allCustoms, customs...)
}
coreConfig, err := cf.Build()
if err != nil {
@@ -134,8 +454,18 @@ func init() {
}
if ext != nil && ext.MultiObservatory != nil {
injectMultiObservatory(coreConfig, ext.MultiObservatory)
} else if ext != nil && ext.BurstObservatory != nil {
injectBurstObservatoryAsMulti(coreConfig, ext.BurstObservatory)
}
injectCompatService(coreConfig)
reorderAppsForAPIReadiness(coreConfig)
if len(allCustoms) > 0 {
customOutbounds, err := buildCustomOutbounds(allCustoms)
if err != nil {
return nil, err
}
coreConfig.Outbound = append(coreConfig.Outbound, customOutbounds...)
}
return coreConfig, nil
case io.Reader:
@@ -143,7 +473,11 @@ func init() {
if err != nil {
return nil, errors.New("failed to read config reader").Base(err)
}
c, err := conf_serial.DecodeJSONConfig(bytes.NewReader(raw))
modified, customs, err := stripCustomOutbounds(raw)
if err != nil {
return nil, errors.New("failed to strip custom outbounds").Base(err)
}
c, err := conf_serial.DecodeJSONConfig(bytes.NewReader(modified))
if err != nil {
return nil, errors.New("failed to decode JSON config").Base(err)
}
@@ -155,8 +489,18 @@ func init() {
}
if e.MultiObservatory != nil {
injectMultiObservatory(coreConfig, e.MultiObservatory)
} else if e.BurstObservatory != nil {
injectBurstObservatoryAsMulti(coreConfig, e.BurstObservatory)
}
injectCompatService(coreConfig)
reorderAppsForAPIReadiness(coreConfig)
if len(customs) > 0 {
customOutbounds, err := buildCustomOutbounds(customs)
if err != nil {
return nil, err
}
coreConfig.Outbound = append(coreConfig.Outbound, customOutbounds...)
}
return coreConfig, nil
default:
+173
View File
@@ -0,0 +1,173 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v7.34.1
// source: hint/proxy/anytls/config.proto
package anytls
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ClientConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Server hostname or IP
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
// Server port
Port uint32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"`
// Authentication password
Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"`
// TLS SNI override (optional)
Sni string `protobuf:"bytes,4,opt,name=sni,proto3" json:"sni,omitempty"`
// Allow insecure TLS (skip verification)
AllowInsecure bool `protobuf:"varint,5,opt,name=allow_insecure,json=allowInsecure,proto3" json:"allow_insecure,omitempty"`
// Minimum number of idle sessions to keep
MinIdleSessions uint32 `protobuf:"varint,6,opt,name=min_idle_sessions,json=minIdleSessions,proto3" json:"min_idle_sessions,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ClientConfig) Reset() {
*x = ClientConfig{}
mi := &file_hint_proxy_anytls_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ClientConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ClientConfig) ProtoMessage() {}
func (x *ClientConfig) ProtoReflect() protoreflect.Message {
mi := &file_hint_proxy_anytls_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead.
func (*ClientConfig) Descriptor() ([]byte, []int) {
return file_hint_proxy_anytls_config_proto_rawDescGZIP(), []int{0}
}
func (x *ClientConfig) GetAddress() string {
if x != nil {
return x.Address
}
return ""
}
func (x *ClientConfig) GetPort() uint32 {
if x != nil {
return x.Port
}
return 0
}
func (x *ClientConfig) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
func (x *ClientConfig) GetSni() string {
if x != nil {
return x.Sni
}
return ""
}
func (x *ClientConfig) GetAllowInsecure() bool {
if x != nil {
return x.AllowInsecure
}
return false
}
func (x *ClientConfig) GetMinIdleSessions() uint32 {
if x != nil {
return x.MinIdleSessions
}
return 0
}
var File_hint_proxy_anytls_config_proto protoreflect.FileDescriptor
const file_hint_proxy_anytls_config_proto_rawDesc = "" +
"\n" +
"\x1ehint/proxy/anytls/config.proto\x12\x13v2raya.proxy.anytls\"\xbd\x01\n" +
"\fClientConfig\x12\x18\n" +
"\aaddress\x18\x01 \x01(\tR\aaddress\x12\x12\n" +
"\x04port\x18\x02 \x01(\rR\x04port\x12\x1a\n" +
"\bpassword\x18\x03 \x01(\tR\bpassword\x12\x10\n" +
"\x03sni\x18\x04 \x01(\tR\x03sni\x12%\n" +
"\x0eallow_insecure\x18\x05 \x01(\bR\rallowInsecure\x12*\n" +
"\x11min_idle_sessions\x18\x06 \x01(\rR\x0fminIdleSessionsB1Z/github.com/v2rayA/v2raya-core/hint/proxy/anytlsb\x06proto3"
var (
file_hint_proxy_anytls_config_proto_rawDescOnce sync.Once
file_hint_proxy_anytls_config_proto_rawDescData []byte
)
func file_hint_proxy_anytls_config_proto_rawDescGZIP() []byte {
file_hint_proxy_anytls_config_proto_rawDescOnce.Do(func() {
file_hint_proxy_anytls_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_hint_proxy_anytls_config_proto_rawDesc), len(file_hint_proxy_anytls_config_proto_rawDesc)))
})
return file_hint_proxy_anytls_config_proto_rawDescData
}
var file_hint_proxy_anytls_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_hint_proxy_anytls_config_proto_goTypes = []any{
(*ClientConfig)(nil), // 0: v2raya.proxy.anytls.ClientConfig
}
var file_hint_proxy_anytls_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_hint_proxy_anytls_config_proto_init() }
func file_hint_proxy_anytls_config_proto_init() {
if File_hint_proxy_anytls_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_hint_proxy_anytls_config_proto_rawDesc), len(file_hint_proxy_anytls_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_hint_proxy_anytls_config_proto_goTypes,
DependencyIndexes: file_hint_proxy_anytls_config_proto_depIdxs,
MessageInfos: file_hint_proxy_anytls_config_proto_msgTypes,
}.Build()
File_hint_proxy_anytls_config_proto = out.File
file_hint_proxy_anytls_config_proto_goTypes = nil
file_hint_proxy_anytls_config_proto_depIdxs = nil
}
+19
View File
@@ -0,0 +1,19 @@
syntax = "proto3";
package v2raya.proxy.anytls;
option go_package = "github.com/v2rayA/v2raya-core/hint/proxy/anytls";
message ClientConfig {
// Server hostname or IP
string address = 1;
// Server port
uint32 port = 2;
// Authentication password
string password = 3;
// TLS SNI override (optional)
string sni = 4;
// Allow insecure TLS (skip verification)
bool allow_insecure = 5;
// Minimum number of idle sessions to keep
uint32 min_idle_sessions = 6;
}
+181
View File
@@ -0,0 +1,181 @@
package anytls
import (
"context"
"crypto/sha256"
"crypto/tls"
"encoding/binary"
"fmt"
"net"
"net/netip"
"time"
anytls_padding "anytls/proxy/padding"
"anytls/proxy/session"
anytls_util "anytls/util"
"github.com/sagernet/sing/common/buf"
M "github.com/sagernet/sing/common/metadata"
"github.com/xtls/xray-core/common"
xray_buf "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
xray_net "github.com/xtls/xray-core/common/net"
xray_session "github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet"
)
// Client is the anytls outbound handler.
type Client struct {
config *ClientConfig
sessionClient *session.Client
}
// NewClient creates a new anytls outbound handler.
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
if config.Address == "" {
return nil, errors.New("anytls: no server address")
}
if config.Port == 0 || config.Port > 65535 {
return nil, errors.New("anytls: invalid server port")
}
hash := sha256.Sum256([]byte(config.Password))
passwordHash := make([]byte, 32)
copy(passwordHash, hash[:])
serverAddr := fmt.Sprintf("%s:%d", config.Address, config.Port)
sni := config.Sni
if sni == "" {
sni = config.Address
}
tlsCfg := &tls.Config{
ServerName: sni,
InsecureSkipVerify: config.AllowInsecure, // #nosec G402 -- user-configurable
}
minIdle := int(config.MinIdleSessions)
if minIdle <= 0 {
minIdle = 5
}
serverDest := xray_net.TCPDestination(xray_net.ParseAddress(config.Address), xray_net.Port(config.Port))
_ = serverAddr // kept for readability
dialOut := anytls_util.DialOutFunc(func(ctx context.Context) (net.Conn, error) {
rawConn, err := internet.DialSystem(ctx, serverDest, nil)
if err != nil {
// Fallback: plain TCP dial
d := &net.Dialer{Timeout: 10 * time.Second}
rawConn, err = d.DialContext(ctx, "tcp", serverAddr)
if err != nil {
return nil, fmt.Errorf("anytls: failed to dial server: %w", err)
}
}
tlsConn := tls.Client(rawConn, tlsCfg)
// Write password SHA256 + padding (protocol handshake)
b := buf.NewPacket()
defer b.Release()
b.Write(passwordHash)
var paddingLen int
if pad := anytls_padding.DefaultPaddingFactory.Load().GenerateRecordPayloadSizes(0); len(pad) > 0 {
paddingLen = pad[0]
}
binary.BigEndian.PutUint16(b.Extend(2), uint16(paddingLen))
if paddingLen > 0 {
b.WriteZeroN(paddingLen)
}
if _, err = b.WriteTo(tlsConn); err != nil {
tlsConn.Close()
return nil, fmt.Errorf("anytls: failed to write handshake: %w", err)
}
return tlsConn, nil
})
bgCtx := context.Background()
sessionClient := session.NewClient(
bgCtx,
dialOut,
&anytls_padding.DefaultPaddingFactory,
30*time.Second,
30*time.Second,
minIdle,
)
return &Client{
config: config,
sessionClient: sessionClient,
}, nil
}
// Process implements proxy.Outbound.
func (c *Client) Process(ctx context.Context, link *transport.Link, _ internet.Dialer) error {
outbounds := xray_session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1]
if !ob.Target.IsValid() {
return errors.New("target not specified")
}
destination := ob.Target
// Build sing Socksaddr from xray Destination
dest := xrayDestToSocksaddr(destination)
stream, err := c.sessionClient.CreateStream(ctx)
if err != nil {
return errors.New("failed to create anytls stream").Base(err)
}
defer stream.Close()
if err := M.SocksaddrSerializer.WriteAddrPort(stream, dest); err != nil {
return errors.New("failed to write destination to anytls stream").Base(err)
}
postRequest := func() error {
return xray_buf.Copy(link.Reader, xray_buf.NewWriter(stream))
}
getResponse := func() error {
return xray_buf.Copy(xray_buf.NewReader(stream), link.Writer)
}
responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
return errors.New("anytls connection ends").Base(err)
}
return nil
}
// xrayDestToSocksaddr converts an xray net.Destination to a sing M.Socksaddr.
func xrayDestToSocksaddr(d xray_net.Destination) M.Socksaddr {
var sa M.Socksaddr
sa.Port = uint16(d.Port.Value())
addr := d.Address
if addr.Family().IsDomain() {
sa.Fqdn = addr.Domain()
} else {
ip := addr.IP()
if ip4 := ip.To4(); ip4 != nil {
var arr [4]byte
copy(arr[:], ip4)
sa.Addr = netip.AddrFrom4(arr)
} else {
var arr [16]byte
copy(arr[:], ip.To16())
sa.Addr = netip.AddrFrom16(arr)
}
}
return sa
}
func init() {
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewClient(ctx, config.(*ClientConfig))
}))
}
+183
View File
@@ -0,0 +1,183 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v7.34.1
// source: hint/proxy/juicity/config.proto
package juicity
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ClientConfig struct {
state protoimpl.MessageState `protogen:"open.v1"`
// Server address in "host:port" format
Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
// User UUID
Uuid string `protobuf:"bytes,2,opt,name=uuid,proto3" json:"uuid,omitempty"`
// Authentication password
Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"`
// TLS SNI override (optional)
Sni string `protobuf:"bytes,4,opt,name=sni,proto3" json:"sni,omitempty"`
// Allow insecure TLS (skip verification)
AllowInsecure bool `protobuf:"varint,5,opt,name=allow_insecure,json=allowInsecure,proto3" json:"allow_insecure,omitempty"`
// Congestion control algorithm: bbr, cubic, new_reno
CongestionControl string `protobuf:"bytes,6,opt,name=congestion_control,json=congestionControl,proto3" json:"congestion_control,omitempty"`
// Pinned certificate chain SHA256 hash (optional)
PinnedCertchainSha256 string `protobuf:"bytes,7,opt,name=pinned_certchain_sha256,json=pinnedCertchainSha256,proto3" json:"pinned_certchain_sha256,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ClientConfig) Reset() {
*x = ClientConfig{}
mi := &file_hint_proxy_juicity_config_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ClientConfig) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ClientConfig) ProtoMessage() {}
func (x *ClientConfig) ProtoReflect() protoreflect.Message {
mi := &file_hint_proxy_juicity_config_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ClientConfig.ProtoReflect.Descriptor instead.
func (*ClientConfig) Descriptor() ([]byte, []int) {
return file_hint_proxy_juicity_config_proto_rawDescGZIP(), []int{0}
}
func (x *ClientConfig) GetAddress() string {
if x != nil {
return x.Address
}
return ""
}
func (x *ClientConfig) GetUuid() string {
if x != nil {
return x.Uuid
}
return ""
}
func (x *ClientConfig) GetPassword() string {
if x != nil {
return x.Password
}
return ""
}
func (x *ClientConfig) GetSni() string {
if x != nil {
return x.Sni
}
return ""
}
func (x *ClientConfig) GetAllowInsecure() bool {
if x != nil {
return x.AllowInsecure
}
return false
}
func (x *ClientConfig) GetCongestionControl() string {
if x != nil {
return x.CongestionControl
}
return ""
}
func (x *ClientConfig) GetPinnedCertchainSha256() string {
if x != nil {
return x.PinnedCertchainSha256
}
return ""
}
var File_hint_proxy_juicity_config_proto protoreflect.FileDescriptor
const file_hint_proxy_juicity_config_proto_rawDesc = "" +
"\n" +
"\x1fhint/proxy/juicity/config.proto\x12\x14v2raya.proxy.juicity\"\xf8\x01\n" +
"\fClientConfig\x12\x18\n" +
"\aaddress\x18\x01 \x01(\tR\aaddress\x12\x12\n" +
"\x04uuid\x18\x02 \x01(\tR\x04uuid\x12\x1a\n" +
"\bpassword\x18\x03 \x01(\tR\bpassword\x12\x10\n" +
"\x03sni\x18\x04 \x01(\tR\x03sni\x12%\n" +
"\x0eallow_insecure\x18\x05 \x01(\bR\rallowInsecure\x12-\n" +
"\x12congestion_control\x18\x06 \x01(\tR\x11congestionControl\x126\n" +
"\x17pinned_certchain_sha256\x18\a \x01(\tR\x15pinnedCertchainSha256B2Z0github.com/v2rayA/v2raya-core/hint/proxy/juicityb\x06proto3"
var (
file_hint_proxy_juicity_config_proto_rawDescOnce sync.Once
file_hint_proxy_juicity_config_proto_rawDescData []byte
)
func file_hint_proxy_juicity_config_proto_rawDescGZIP() []byte {
file_hint_proxy_juicity_config_proto_rawDescOnce.Do(func() {
file_hint_proxy_juicity_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_hint_proxy_juicity_config_proto_rawDesc), len(file_hint_proxy_juicity_config_proto_rawDesc)))
})
return file_hint_proxy_juicity_config_proto_rawDescData
}
var file_hint_proxy_juicity_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_hint_proxy_juicity_config_proto_goTypes = []any{
(*ClientConfig)(nil), // 0: v2raya.proxy.juicity.ClientConfig
}
var file_hint_proxy_juicity_config_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_hint_proxy_juicity_config_proto_init() }
func file_hint_proxy_juicity_config_proto_init() {
if File_hint_proxy_juicity_config_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_hint_proxy_juicity_config_proto_rawDesc), len(file_hint_proxy_juicity_config_proto_rawDesc)),
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_hint_proxy_juicity_config_proto_goTypes,
DependencyIndexes: file_hint_proxy_juicity_config_proto_depIdxs,
MessageInfos: file_hint_proxy_juicity_config_proto_msgTypes,
}.Build()
File_hint_proxy_juicity_config_proto = out.File
file_hint_proxy_juicity_config_proto_goTypes = nil
file_hint_proxy_juicity_config_proto_depIdxs = nil
}
+21
View File
@@ -0,0 +1,21 @@
syntax = "proto3";
package v2raya.proxy.juicity;
option go_package = "github.com/v2rayA/v2raya-core/hint/proxy/juicity";
message ClientConfig {
// Server address in "host:port" format
string address = 1;
// User UUID
string uuid = 2;
// Authentication password
string password = 3;
// TLS SNI override (optional)
string sni = 4;
// Allow insecure TLS (skip verification)
bool allow_insecure = 5;
// Congestion control algorithm: bbr, cubic, new_reno
string congestion_control = 6;
// Pinned certificate chain SHA256 hash (optional)
string pinned_certchain_sha256 = 7;
}
+122
View File
@@ -0,0 +1,122 @@
package juicity
import (
"context"
"crypto/tls"
"fmt"
"io"
"github.com/daeuniverse/softwind/netproxy"
"github.com/daeuniverse/softwind/protocol"
"github.com/daeuniverse/softwind/protocol/direct"
_ "github.com/daeuniverse/softwind/protocol/juicity" // register juicity protocol
"github.com/xtls/xray-core/common"
xray_buf "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/errors"
xray_session "github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/task"
"github.com/xtls/xray-core/transport"
"github.com/xtls/xray-core/transport/internet"
)
// Client is the juicity outbound handler.
type Client struct {
config *ClientConfig
dialer netproxy.Dialer
}
// NewClient creates a new juicity outbound handler.
func NewClient(ctx context.Context, config *ClientConfig) (*Client, error) {
if config.Address == "" {
return nil, errors.New("juicity: no server address")
}
if config.Uuid == "" {
return nil, errors.New("juicity: no UUID")
}
sni := config.Sni
if sni == "" {
// extract host from address (may be host:port or just host)
host := config.Address
sni = host
}
tlsCfg := &tls.Config{
ServerName: sni,
InsecureSkipVerify: config.AllowInsecure, // #nosec G402 -- user-configurable
NextProtos: []string{"h3"},
MinVersion: tls.VersionTLS13,
}
congestion := config.CongestionControl
if congestion == "" {
congestion = "bbr"
}
dialer, err := protocol.NewDialer("juicity", direct.SymmetricDirect, protocol.Header{
ProxyAddress: config.Address,
Feature1: congestion,
TlsConfig: tlsCfg,
User: config.Uuid,
Password: config.Password,
IsClient: true,
})
if err != nil {
return nil, fmt.Errorf("juicity: failed to create dialer: %w", err)
}
return &Client{
config: config,
dialer: dialer,
}, nil
}
// Process implements proxy.Outbound.
func (c *Client) Process(ctx context.Context, link *transport.Link, _ internet.Dialer) error {
outbounds := xray_session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1]
if !ob.Target.IsValid() {
return errors.New("target not specified")
}
destination := ob.Target
// Build destination address string
destAddr := fmt.Sprintf("%s:%d", destination.Address.String(), destination.Port.Value())
conn, err := c.dialer.Dial("tcp", destAddr)
if err != nil {
return errors.New("juicity: failed to dial destination").Base(err)
}
defer conn.Close()
postRequest := func() error {
return xray_buf.Copy(link.Reader, xray_buf.NewWriter(netproxyConnAsWriter(conn)))
}
getResponse := func() error {
return xray_buf.Copy(xray_buf.NewReader(netproxyConnAsReader(conn)), link.Writer)
}
responseDoneAndCloseWriter := task.OnSuccess(getResponse, task.Close(link.Writer))
if err := task.Run(ctx, postRequest, responseDoneAndCloseWriter); err != nil {
return errors.New("juicity connection ends").Base(err)
}
return nil
}
// netproxyConn wraps a netproxy.Conn to expose io.Reader/io.Writer for xray's buf.
type netproxyConn struct {
c netproxy.Conn
}
func netproxyConnAsReader(c netproxy.Conn) io.Reader { return &netproxyConn{c} }
func netproxyConnAsWriter(c netproxy.Conn) io.Writer { return &netproxyConn{c} }
func (n *netproxyConn) Read(b []byte) (int, error) { return n.c.Read(b) }
func (n *netproxyConn) Write(b []byte) (int, error) { return n.c.Write(b) }
func init() {
common.Must(common.RegisterConfig((*ClientConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewClient(ctx, config.(*ClientConfig))
}))
}
+72 -68
View File
@@ -1,6 +1,6 @@
// Package all loads all v2raya-core features for the merged binary.
// It is based on xray-core's main/distro/all/all.go with the following changes:
// - multiobservatory and compat features from hint/ are added
// - multiobservatory and v2ray-compatible command features from hint/ are added
// - xray's main/json loader is replaced by our hint/conf loader
//
// This Source Code Form is subject to the terms of the Mozilla Public
@@ -9,83 +9,87 @@
package all
import (
// Mandatory xray features.
_ "github.com/xtls/xray-core/app/dispatcher"
_ "github.com/xtls/xray-core/app/proxyman/inbound"
_ "github.com/xtls/xray-core/app/proxyman/outbound"
// Mandatory xray features.
_ "github.com/xtls/xray-core/app/dispatcher"
_ "github.com/xtls/xray-core/app/proxyman/inbound"
_ "github.com/xtls/xray-core/app/proxyman/outbound"
// Commander and its services.
_ "github.com/xtls/xray-core/app/commander"
_ "github.com/xtls/xray-core/app/log/command"
_ "github.com/xtls/xray-core/app/proxyman/command"
_ "github.com/xtls/xray-core/app/stats/command"
// Commander and its services.
_ "github.com/xtls/xray-core/app/commander"
_ "github.com/xtls/xray-core/app/log/command"
_ "github.com/xtls/xray-core/app/proxyman/command"
_ "github.com/xtls/xray-core/app/stats/command"
// Observatory command (xray native gRPC path).
_ "github.com/xtls/xray-core/app/observatory/command"
// Observatory command (xray native gRPC path).
_ "github.com/xtls/xray-core/app/observatory/command"
// Other optional xray features.
_ "github.com/xtls/xray-core/app/dns"
_ "github.com/xtls/xray-core/app/dns/fakedns"
_ "github.com/xtls/xray-core/app/log"
_ "github.com/xtls/xray-core/app/metrics"
_ "github.com/xtls/xray-core/app/policy"
_ "github.com/xtls/xray-core/app/reverse"
_ "github.com/xtls/xray-core/app/router"
_ "github.com/xtls/xray-core/app/stats"
// Other optional xray features.
_ "github.com/xtls/xray-core/app/dns"
_ "github.com/xtls/xray-core/app/dns/fakedns"
_ "github.com/xtls/xray-core/app/log"
_ "github.com/xtls/xray-core/app/metrics"
_ "github.com/xtls/xray-core/app/policy"
_ "github.com/xtls/xray-core/app/reverse"
_ "github.com/xtls/xray-core/app/router"
_ "github.com/xtls/xray-core/app/stats"
// Fix dependency cycle.
_ "github.com/xtls/xray-core/transport/internet/tagged/taggedimpl"
// Fix dependency cycle.
_ "github.com/xtls/xray-core/transport/internet/tagged/taggedimpl"
// Observatory feature (single group).
_ "github.com/xtls/xray-core/app/observatory"
// Observatory feature (single group).
_ "github.com/xtls/xray-core/app/observatory"
// Inbound/outbound proxies.
_ "github.com/xtls/xray-core/proxy/blackhole"
_ "github.com/xtls/xray-core/proxy/dns"
_ "github.com/xtls/xray-core/proxy/dokodemo"
_ "github.com/xtls/xray-core/proxy/freedom"
_ "github.com/xtls/xray-core/proxy/http"
_ "github.com/xtls/xray-core/proxy/loopback"
_ "github.com/xtls/xray-core/proxy/shadowsocks"
_ "github.com/xtls/xray-core/proxy/socks"
_ "github.com/xtls/xray-core/proxy/trojan"
_ "github.com/xtls/xray-core/proxy/vless/inbound"
_ "github.com/xtls/xray-core/proxy/vless/outbound"
_ "github.com/xtls/xray-core/proxy/vmess/inbound"
_ "github.com/xtls/xray-core/proxy/vmess/outbound"
_ "github.com/xtls/xray-core/proxy/wireguard"
// Inbound/outbound proxies.
_ "github.com/xtls/xray-core/proxy/blackhole"
_ "github.com/xtls/xray-core/proxy/dns"
_ "github.com/xtls/xray-core/proxy/dokodemo"
_ "github.com/xtls/xray-core/proxy/freedom"
_ "github.com/xtls/xray-core/proxy/http"
_ "github.com/xtls/xray-core/proxy/loopback"
_ "github.com/xtls/xray-core/proxy/shadowsocks"
_ "github.com/xtls/xray-core/proxy/socks"
_ "github.com/xtls/xray-core/proxy/trojan"
_ "github.com/xtls/xray-core/proxy/vless/inbound"
_ "github.com/xtls/xray-core/proxy/vless/outbound"
_ "github.com/xtls/xray-core/proxy/vmess/inbound"
_ "github.com/xtls/xray-core/proxy/vmess/outbound"
_ "github.com/xtls/xray-core/proxy/wireguard"
// Transports.
_ "github.com/xtls/xray-core/transport/internet/grpc"
_ "github.com/xtls/xray-core/transport/internet/httpupgrade"
_ "github.com/xtls/xray-core/transport/internet/kcp"
_ "github.com/xtls/xray-core/transport/internet/reality"
_ "github.com/xtls/xray-core/transport/internet/splithttp"
_ "github.com/xtls/xray-core/transport/internet/tcp"
_ "github.com/xtls/xray-core/transport/internet/tls"
_ "github.com/xtls/xray-core/transport/internet/udp"
_ "github.com/xtls/xray-core/transport/internet/websocket"
// Transports.
_ "github.com/xtls/xray-core/transport/internet/grpc"
_ "github.com/xtls/xray-core/transport/internet/httpupgrade"
_ "github.com/xtls/xray-core/transport/internet/kcp"
_ "github.com/xtls/xray-core/transport/internet/reality"
_ "github.com/xtls/xray-core/transport/internet/splithttp"
_ "github.com/xtls/xray-core/transport/internet/tcp"
_ "github.com/xtls/xray-core/transport/internet/tls"
_ "github.com/xtls/xray-core/transport/internet/udp"
_ "github.com/xtls/xray-core/transport/internet/websocket"
// Transport headers.
_ "github.com/xtls/xray-core/transport/internet/headers/http"
_ "github.com/xtls/xray-core/transport/internet/headers/noop"
// Transport headers.
_ "github.com/xtls/xray-core/transport/internet/headers/http"
_ "github.com/xtls/xray-core/transport/internet/headers/noop"
// TOML and YAML config loaders (JSON is replaced by hint/conf below).
_ "github.com/xtls/xray-core/main/toml"
_ "github.com/xtls/xray-core/main/yaml"
// TOML and YAML config loaders (JSON is replaced by hint/conf below).
_ "github.com/xtls/xray-core/main/toml"
_ "github.com/xtls/xray-core/main/yaml"
// Config loader from file or http(s).
_ "github.com/xtls/xray-core/main/confloader/external"
// Config loader from file or http(s).
_ "github.com/xtls/xray-core/main/confloader/external"
// xray sub-commands.
_ "github.com/xtls/xray-core/main/commands/all"
// xray sub-commands.
_ "github.com/xtls/xray-core/main/commands/all"
// v2raya-core extensions:
// - MultiObservatory: multi-group observatory backed by xray observatory
// - compat: v2ray-compatible gRPC observatory service path
// - hint/conf: JSON config loader that supports multiObservatory field
// (replaces github.com/xtls/xray-core/main/json)
_ "github.com/v2rayA/v2raya-core/hint/app/observatory/multiobservatory"
_ "github.com/v2rayA/v2raya-core/hint/app/observatory/compat"
_ "github.com/v2rayA/v2raya-core/hint/conf"
// v2raya-core extensions:
// - MultiObservatory: multi-group observatory backed by xray observatory
// - command: v2ray-compatible observatory gRPC service (native v2ray service name)
// - hint/conf: JSON config loader that supports multiObservatory field
// (replaces github.com/xtls/xray-core/main/json)
// - hint/proxy/anytls: native anytls outbound protocol handler
// - hint/proxy/juicity: native juicity outbound protocol handler
_ "github.com/v2rayA/v2raya-core/hint/app/observatory/command"
_ "github.com/v2rayA/v2raya-core/hint/app/observatory/multiobservatory"
_ "github.com/v2rayA/v2raya-core/hint/conf"
_ "github.com/v2rayA/v2raya-core/hint/proxy/anytls"
_ "github.com/v2rayA/v2raya-core/hint/proxy/juicity"
)
-2
View File
@@ -218,8 +218,6 @@ func getConfigFormat() string {
func startXray() (core.Server, error) {
configFiles := getConfigFilePath(true)
// config, err := core.LoadConfig(getConfigFormat(), configFiles[0], configFiles)
c, err := core.LoadConfig(getConfigFormat(), configFiles)
if err != nil {
return nil, errors.New("failed to load config files: [", configFiles.String(), "]").Base(err)
+18 -15
View File
@@ -4,31 +4,34 @@
package main
import (
"fmt"
"runtime"
"fmt"
"runtime"
xray_core "github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/main/commands/base"
"github.com/xtls/xray-core/main/commands/base"
)
// Version is the v2rayA version, injected at build time via -ldflags.
// It matches the v2raya service binary version.
var Version = "debug"
var cmdVersion = &base.Command{
UsageLine: "{{.Exec}} version",
Short: "Show current version of v2raya-core",
Long: `Version prints the build information for v2raya-core.`,
Run: executeVersion,
UsageLine: "{{.Exec}} version",
Short: "Show current version of v2raya-core",
Long: `Version prints the build information for v2raya-core.`,
Run: executeVersion,
}
func executeVersion(cmd *base.Command, args []string) {
printVersion()
printVersion()
}
// printVersion prints the version string.
// The first line MUST start with "V2RAYA_CORE " for v2rayA variant detection.
func printVersion() {
fmt.Printf("V2RAYA_CORE %s (xray-core) (%s %s/%s)\n",
xray_core.Version(),
runtime.Version(),
runtime.GOOS,
runtime.GOARCH,
)
fmt.Printf("V2RAYA_CORE %s (xray-core) (%s %s/%s)\n",
Version,
runtime.Version(),
runtime.GOOS,
runtime.GOARCH,
)
}
-2
View File
@@ -373,7 +373,6 @@ ref="v2ray_key" v-model="v2ray.key" :placeholder="$t('configureServer.password')
<b-field :label="$t('setting.nodeBackend')" label-position="on-border">
<b-select v-model="ss.backend" expanded>
<option value="">{{ $t("setting.options.backendSystemDefault") }}</option>
<option value="daeuniverse">{{ $t("setting.options.backendDaeuniverse") }}</option>
<option value="v2ray">{{ $t("setting.options.backendV2ray") }}</option>
</b-select>
</b-field>
@@ -546,7 +545,6 @@ ref="v2ray_key" v-model="v2ray.key" :placeholder="$t('configureServer.password')
<b-field :label="$t('setting.nodeBackend')" label-position="on-border">
<b-select v-model="trojan.backend" expanded>
<option value="">{{ $t("setting.options.backendSystemDefault") }}</option>
<option value="daeuniverse">{{ $t("setting.options.backendDaeuniverse") }}</option>
<option value="v2ray">{{ $t("setting.options.backendV2ray") }}</option>
</b-select>
</b-field>
-17
View File
@@ -298,19 +298,6 @@
style="flex: 1" />
</b-field>
<b-field :label="$t('setting.ssBackend')" label-position="on-border">
<b-select v-model="ssBackend" expanded>
<option value="">{{ $t("setting.options.backendDaeuniverse") }}</option>
<option value="v2ray">{{ $t("setting.options.backendV2ray") }}</option>
</b-select>
</b-field>
<b-field :label="$t('setting.trojanBackend')" label-position="on-border">
<b-select v-model="trojanBackend" expanded>
<option value="">{{ $t("setting.options.backendDaeuniverse") }}</option>
<option value="v2ray">{{ $t("setting.options.backendV2ray") }}</option>
</b-select>
</b-field>
<b-field v-show="pacMode === 'gfwlist' || transparent === 'gfwlist'" :label="$t('setting.autoUpdateGfwlist')"
label-position="on-border">
@@ -420,8 +407,6 @@ export default {
tunTeardownScript: "",
tunProcessBackend: "",
tunExcludeProcesses: "",
ssBackend: "",
trojanBackend: "",
pacAutoUpdateMode: "none",
pacAutoUpdateIntervalHour: 0,
subscriptionAutoUpdateMode: "none",
@@ -579,8 +564,6 @@ export default {
tunTeardownScript: this.tunTeardownScript,
tunProcessBackend: this.tunProcessBackend,
tunExcludeProcesses: this.tunExcludeProcesses,
ssBackend: this.ssBackend,
trojanBackend: this.trojanBackend,
},
cancelToken: new axios.CancelToken(function executor(c) {
cancel = c;
-1
View File
@@ -163,7 +163,6 @@ export default {
leastPing: "Least Latency First",
tunBackendTun: "TUN (default, /proc process lookup)",
tunBackendEbpf: "eBPF (cgroupv2 process exclusion)",
backendDaeuniverse: "daeuniverse/outbound",
backendV2ray: "v2ray / xray",
backendSystemDefault: "System Default",
},
-1
View File
@@ -144,7 +144,6 @@ export default {
closed: "خاموش",
advanced: "تنظیمات پیشرفته",
leastPing: "اول سرور با پینگ کمتر",
backendDaeuniverse: "daeuniverse/outbound",
backendV2ray: "v2ray / xray",
backendSystemDefault: "System Default",
},
-1
View File
@@ -146,7 +146,6 @@ export default {
closed: "Desligado",
advanced: "Configuração Avançada",
leastPing: "Menor Latência Primeiro",
backendDaeuniverse: "daeuniverse/outbound",
backendV2ray: "v2ray / xray",
backendSystemDefault: "Padrão do Sistema",
},
-1
View File
@@ -148,7 +148,6 @@ export default {
closed: "Выключено",
advanced: "Расширенная настройка",
leastPing: "С наименьшей задержкой",
backendDaeuniverse: "daeuniverse/outbound",
backendV2ray: "v2ray / xray",
backendSystemDefault: "По умолчанию",
},
-1
View File
@@ -162,7 +162,6 @@ export default {
leastPing: "最小时延优先",
tunBackendTun: "TUN(默认,/proc 进程查找)",
tunBackendEbpf: "eBPF(cgroupv2 进程排除)",
backendDaeuniverse: "daeuniverse/outbound",
backendV2ray: "v2ray / xray",
backendSystemDefault: "跟随系统设置",
},
+30 -3
View File
@@ -1,5 +1,7 @@
package coreObj
import "encoding/json"
type APIObject struct {
Tag string `json:"tag"`
Services []string `json:"services"`
@@ -12,9 +14,19 @@ type ObservatoryItem struct {
Settings Observatory `json:"settings"`
}
type Observatory struct {
SubjectSelector []string `json:"subjectSelector"`
ProbeURL string `json:"probeURL,omitempty"`
ProbeInterval string `json:"probeInterval,omitempty"`
SubjectSelector []string `json:"subjectSelector"`
PingConfig *PingConfig `json:"pingConfig,omitempty"`
ProbeURL string `json:"probeURL,omitempty"`
ProbeInterval string `json:"probeInterval,omitempty"`
}
type PingConfig struct {
Destination string `json:"destination,omitempty"`
Connectivity string `json:"connectivity,omitempty"`
Interval string `json:"interval,omitempty"`
SamplingCount int `json:"samplingCount,omitempty"`
Timeout string `json:"timeout,omitempty"`
HTTPMethod string `json:"httpMethod,omitempty"`
}
type Balancer struct {
Tag string `json:"tag"`
@@ -120,7 +132,22 @@ type Settings struct {
Network string `json:"network,omitempty"`
Redirect string `json:"redirect,omitempty"`
UserLevel *int `json:"userLevel,omitempty"`
// Inlined, when non-nil, replaces the entire settings JSON during serialization.
// Used for non-standard protocols such as anytls/juicity whose settings do not
// fit the standard fields above.
Inlined json.RawMessage `json:"-"`
}
// MarshalJSON implements json.Marshaler. When Inlined is set it is emitted verbatim;
// otherwise normal struct marshaling is used.
func (s Settings) MarshalJSON() ([]byte, error) {
if s.Inlined != nil {
return s.Inlined, nil
}
type Alias Settings
return json.Marshal(Alias(s))
}
type TLSSettings struct {
AllowInsecure bool `json:"allowInsecure"`
ServerName interface{} `json:"serverName,omitempty"`
+45 -10
View File
@@ -1,11 +1,12 @@
package serverObj
import (
"encoding/json"
"fmt"
"net"
"net/url"
"strconv"
"strings"
"github.com/v2rayA/v2rayA/core/coreObj"
)
func init() {
@@ -45,16 +46,50 @@ func ParseAnyTLSURL(link string) (data *AnyTLS, err error) {
}, nil
}
// anytlsSettings holds the settings serialized into the hybrid-core xray config.
type anytlsSettings struct {
Address string `json:"address"`
Port int `json:"port"`
Password string `json:"password"`
SNI string `json:"sni,omitempty"`
AllowInsecure bool `json:"allow_insecure,omitempty"`
MinIdleSessions int `json:"min_idle_sessions,omitempty"`
}
func (s *AnyTLS) Configuration(info PriorInfo) (c Configuration, err error) {
socks5 := url.URL{
Scheme: "socks5",
Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(info.PluginPort)),
u, err := url.Parse(s.Link)
if err != nil {
return c, fmt.Errorf("anytls: parse link: %w", err)
}
chain := []string{socks5.String(), s.Link}
password := ""
if u.User != nil {
password = u.User.Username()
}
q := u.Query()
sni := q.Get("sni")
insecure := q.Get("insecure") == "1" || q.Get("allowInsecure") == "1"
minIdle, _ := strconv.Atoi(q.Get("minIdleSession"))
settingsJSON, err := json.Marshal(anytlsSettings{
Address: s.Server,
Port: s.Port,
Password: password,
SNI: sni,
AllowInsecure: insecure,
MinIdleSessions: minIdle,
})
if err != nil {
return c, fmt.Errorf("anytls: marshal settings: %w", err)
}
return Configuration{
CoreOutbound: info.PluginObj(),
PluginChain: strings.Join(chain, ","),
UDPSupport: true,
CoreOutbound: coreObj.OutboundObject{
Tag: info.Tag,
Protocol: "anytls",
Settings: coreObj.Settings{Inlined: settingsJSON},
},
UDPSupport: true,
}, nil
}
@@ -63,7 +98,7 @@ func (s *AnyTLS) ExportToURL() string {
}
func (s *AnyTLS) NeedPluginPort() bool {
return true
return false
}
func (s *AnyTLS) ProtoToShow() string {
+54 -9
View File
@@ -1,11 +1,13 @@
package serverObj
import (
"encoding/json"
"fmt"
"net"
"net/url"
"strconv"
"strings"
"github.com/v2rayA/v2rayA/core/coreObj"
)
func init() {
@@ -45,16 +47,59 @@ func ParseJuicityURL(link string) (data *Juicity, err error) {
}, nil
}
// juicitySettings holds the settings serialized into the hybrid-core xray config.
type juicitySettings struct {
// Address is "host:port".
Address string `json:"address"`
UUID string `json:"uuid"`
Password string `json:"password"`
SNI string `json:"sni,omitempty"`
AllowInsecure bool `json:"allow_insecure,omitempty"`
CongestionControl string `json:"congestion_control,omitempty"`
PinnedSHA256 string `json:"pinned_certchain_sha256,omitempty"`
}
func (s *Juicity) Configuration(info PriorInfo) (c Configuration, err error) {
socks5 := url.URL{
Scheme: "socks5",
Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(info.PluginPort)),
u, err := url.Parse(s.Link)
if err != nil {
return c, fmt.Errorf("juicity: parse link: %w", err)
}
chain := []string{socks5.String(), s.Link}
uuid := ""
password := ""
if u.User != nil {
uuid = u.User.Username()
password, _ = u.User.Password()
}
q := u.Query()
sni := q.Get("sni")
insecure := q.Get("insecure") == "1" || q.Get("allowInsecure") == "1"
congestion := q.Get("congestion_control")
if congestion == "" {
congestion = q.Get("congestionControl")
}
pinnedSHA := q.Get("pinned_certchain_sha256")
settingsJSON, err := json.Marshal(juicitySettings{
Address: net.JoinHostPort(s.Server, strconv.Itoa(s.Port)),
UUID: uuid,
Password: password,
SNI: sni,
AllowInsecure: insecure,
CongestionControl: congestion,
PinnedSHA256: pinnedSHA,
})
if err != nil {
return c, fmt.Errorf("juicity: marshal settings: %w", err)
}
return Configuration{
CoreOutbound: info.PluginObj(),
PluginChain: strings.Join(chain, ","),
UDPSupport: true,
CoreOutbound: coreObj.OutboundObject{
Tag: info.Tag,
Protocol: "juicity",
Settings: coreObj.Settings{Inlined: settingsJSON},
},
UDPSupport: true,
}, nil
}
@@ -63,7 +108,7 @@ func (s *Juicity) ExportToURL() string {
}
func (s *Juicity) NeedPluginPort() bool {
return true
return false
}
func (s *Juicity) ProtoToShow() string {
+5 -19
View File
@@ -333,27 +333,13 @@ func (s *Shadowsocks) GetBackend() string {
}
func (s *Shadowsocks) Configuration(info PriorInfo) (c Configuration, err error) {
if info.Backend == "v2ray" {
if info.Variant == where.Xray {
return s.ConfigurationMT(info)
}
return s.ConfigurationMC(info)
if info.Variant == where.Xray {
return s.ConfigurationMT(info)
}
// daeuniverse/outbound path
socks5 := url.URL{
Scheme: "socks5",
Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(info.PluginPort)),
}
chain := []string{socks5.String(), s.exportToChainURL()}
return Configuration{
CoreOutbound: info.PluginObj(),
PluginChain: strings.Join(chain, ","),
UDPSupport: true,
}, nil
return s.ConfigurationMC(info)
}
// exportToChainURL returns the URL for use in the daeuniverse plugin chain.
// It excludes v2rayA-specific metadata like v2raya-backend.
// exportToChainURL is kept for the ConfigurationMC path used by non-xray variants.
func (s *Shadowsocks) exportToChainURL() string {
u := &url.URL{
Scheme: "ss",
@@ -390,7 +376,7 @@ func (s *Shadowsocks) ExportToURL() string {
}
func (s *Shadowsocks) NeedPluginPort() bool {
return true
return false
}
func (s *Shadowsocks) GetProtocol() string {
+4 -61
View File
@@ -141,67 +141,10 @@ func (t *Trojan) ConfigurationMT(info PriorInfo) (c Configuration, err error) {
}
func (t *Trojan) Configuration(info PriorInfo) (c Configuration, err error) {
if info.Backend == "v2ray" {
if info.Variant == where.Xray {
return t.ConfigurationMT(info)
}
return t.ConfigurationMC(info)
if info.Variant == where.Xray {
return t.ConfigurationMT(info)
}
// daeuniverse/outbound path
socks5 := url.URL{
Scheme: "socks5",
Host: net.JoinHostPort("127.0.0.1", strconv.Itoa(info.PluginPort)),
}
// Build chain URL without v2raya metadata
chainURL := t.exportToChainURL()
chain := []string{socks5.String(), chainURL}
return Configuration{
CoreOutbound: info.PluginObj(),
PluginChain: strings.Join(chain, ","),
UDPSupport: true,
}, nil
}
// exportToChainURL returns the URL for use in the daeuniverse plugin chain,
// without v2rayA-specific metadata.
func (t *Trojan) exportToChainURL() string {
u := &url.URL{
Scheme: "trojan",
User: url.User(t.Password),
Host: net.JoinHostPort(t.Server, strconv.Itoa(t.Port)),
Fragment: t.Name,
}
query := u.Query()
setValue(&query, "type", t.Type)
net := strings.ToLower(t.Type)
switch net {
case "websocket", "ws", "http", "h2":
setValue(&query, "path", t.Path)
setValue(&query, "host", t.Host)
case "mkcp", "kcp":
setValue(&query, "headerType", t.Type)
setValue(&query, "seed", t.Path)
case "tcp":
setValue(&query, "headerType", t.Type)
setValue(&query, "host", t.Host)
setValue(&query, "path", t.Path)
case "grpc":
setValue(&query, "serviceName", t.ServiceName)
}
if t.AllowInsecure {
query.Set("allowInsecure", "1")
}
setValue(&query, "sni", t.Sni)
if t.Protocol == "trojan-go" {
u.Scheme = "trojan-go"
setValue(&query, "host", t.Host)
setValue(&query, "encryption", t.Encryption)
setValue(&query, "type", t.Type)
setValue(&query, "path", t.Path)
setValue(&query, "serviceName", t.ServiceName)
}
u.RawQuery = query.Encode()
return u.String()
return t.ConfigurationMC(info)
}
func (t *Trojan) ExportToURL() string {
@@ -254,7 +197,7 @@ func (t *Trojan) ExportToURL() string {
}
func (t *Trojan) NeedPluginPort() bool {
return true
return false
}
func (t *Trojan) ProtoToShow() string {
+10 -21
View File
@@ -16,7 +16,6 @@ import (
"github.com/muhammadmuzzammil1998/jsonc"
"github.com/v2rayA/v2rayA/common/files"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/v2ray/where"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
@@ -35,25 +34,15 @@ func GetV2rayLocationAssetOverride() string {
}
func GetV2rayLocationAsset(filename string) (string, error) {
variant, _, err := where.GetV2rayServiceVersion()
if err != nil {
variant = where.Unknown
}
var location string
var folder string
switch variant {
case where.V2rayaCore:
location = "XRAY_LOCATION_ASSET"
folder = "xray"
default:
location = "XRAY_LOCATION_ASSET"
folder = "xray"
}
// All variants use XRAY_LOCATION_ASSET; dat files are stored under
// v2raya's own XDG data subdirectory ("v2raya/"), not under "xray/".
const envKey = "XRAY_LOCATION_ASSET"
const folder = "v2raya"
location = os.Getenv(location)
// check if V2RAY_LOCATION_ASSET is set
location := os.Getenv(envKey)
// check if XRAY_LOCATION_ASSET is set
if location != "" {
// add V2RAY_LOCATION_ASSET to search path
// add XRAY_LOCATION_ASSET to search path
searchPaths := []string{
filepath.Join(location, filename),
}
@@ -66,18 +55,18 @@ func GetV2rayLocationAsset(filename string) (string, error) {
)
}
for _, searchPath := range searchPaths {
if _, err = os.Stat(searchPath); err != nil && errors.Is(err, fs.ErrNotExist) {
if _, err := os.Stat(searchPath); err != nil && errors.Is(err, fs.ErrNotExist) {
continue
}
// return the first path that exists
return searchPath, nil
}
// or download asset into V2RAY_LOCATION_ASSET
// or download asset into XRAY_LOCATION_ASSET
return searchPaths[0], nil
} else {
if runtime.GOOS != "windows" {
// search XDG data directories on non windows platform
// symlink all assets into XDG_RUNTIME_DIR
// symlink all assets into XDG_RUNTIME_DIR so xray-core can find them
relpath := filepath.Join(folder, filename)
fullpath, err := xdg.SearchDataFile(relpath)
if err != nil {
+1 -32
View File
@@ -31,8 +31,7 @@ type Process struct {
// mutex protect the proc
mutex sync.Mutex
proc *os.Process
procCancel func() // cancel func for proc and pluginManagers
pluginManagers []*os.Process
procCancel func() // cancel func for proc
template *Template
tag2WhichIndex map[string]int
done chan struct{}
@@ -62,35 +61,12 @@ func NewProcess(tmpl *Template,
if err = tmpl.CheckInboundPortsOccupied(); err != nil {
return nil, fmt.Errorf("%v", err)
}
go tmpl.ServePlugins()
pCtx, cancel := context.WithCancel(context.Background())
defer func() {
if err != nil {
cancel()
}
}()
// start PluginManagers
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
for _, v := range tmpl.PluginManagerInfoList {
arguments := []string{
pm,
"--stage=run",
fmt.Sprintf("--link=%v", v.Link),
fmt.Sprintf("--port=%v", v.Port),
fmt.Sprintf("--v2raya-confdir=%v", conf.GetEnvironmentConfig().Config),
}
proc, err := RunWithLog(pCtx, pm, arguments, "", os.Environ())
if err != nil {
// clean
for _, pm := range process.pluginManagers {
_ = pm.Kill()
}
process.pluginManagers = nil
return nil, fmt.Errorf("executing PluginManager [state: run, link: %v]: %w", v.Link, err)
}
process.pluginManagers = append(process.pluginManagers, proc)
}
}
defer func() {
if err != nil {
_ = tmpl.Close()
@@ -135,13 +111,6 @@ func NewProcess(tmpl *Template,
}()
// ports to check
portList := []string{strconv.Itoa(tmpl.ApiPort)}
for _, plu := range tmpl.Plugins {
_, port, err := net.SplitHostPort(plu.ListenAddr())
if err != nil {
return nil, err
}
portList = append(portList, port)
}
log.Trace("portList for connectivity test: %+v", portList)
startTime := time.Now()
startTimeOut := time.Duration(conf.GetEnvironmentConfig().CoreStartupTimeout) * time.Second
-18
View File
@@ -1,9 +1,7 @@
package v2ray
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
"sync"
@@ -177,7 +175,6 @@ func (m *CoreProcessManager) stop(saveRunning bool) {
if err != nil {
log.Warn("CoreProcessManager.Stop: %v", err)
}
m.terminatePluginManagers(p)
if saveRunning {
configure.SetRunning(false)
}
@@ -190,21 +187,6 @@ func (m *CoreProcessManager) stop(saveRunning bool) {
ApiFeed.ProductMessage("running_state", map[string]interface{}{"running": false})
}
func (m *CoreProcessManager) terminatePluginManagers(p *Process) {
if p == nil {
return
}
for _, pm := range p.pluginManagers {
if pm == nil {
continue
}
if err := pm.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
log.Warn("failed to stop PluginManager (pid: %d): %v", pm.Pid, err)
}
}
p.pluginManagers = nil
}
func (m *CoreProcessManager) handleUnexpectedStop(p *Process) {
m.mu.Lock()
defer m.mu.Unlock()
+19 -105
View File
@@ -12,7 +12,6 @@ import (
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/go-leo/slicex"
@@ -30,7 +29,6 @@ import (
"github.com/v2rayA/v2rayA/core/v2ray/asset"
"github.com/v2rayA/v2rayA/core/v2ray/where"
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
@@ -49,57 +47,20 @@ type Template struct {
Observatory *coreObj.ObservatoryItem `json:"observatory,omitempty"`
API *coreObj.APIObject `json:"api,omitempty"`
Variant where.Variant `json:"-"`
CoreVersion string `json:"-"`
Plugins []plugin.Server `json:"-"`
OutboundTags []string `json:"-"`
ApiCloses []func() `json:"-"`
ApiPort int `json:"-"`
Setting *configure.Setting `json:"-"`
PluginManagerInfoList []PluginManagerInfo `json:"-"`
serverInfoMap map[string]*serverInfo `json:"-"` // outbound tag -> server info
}
type PluginManagerInfo struct {
Link string
Port int
Variant where.Variant `json:"-"`
CoreVersion string `json:"-"`
OutboundTags []string `json:"-"`
ApiCloses []func() `json:"-"`
ApiPort int `json:"-"`
Setting *configure.Setting `json:"-"`
serverInfoMap map[string]*serverInfo `json:"-"` // outbound tag -> server info
}
func (t *Template) Close() error {
var err error
for _, p := range t.Plugins {
if e := p.Close(); err == nil && e != nil {
err = e
}
}
for _, f := range t.ApiCloses {
f()
}
return err
}
func (t *Template) ServePlugins() error {
var wg sync.WaitGroup
var err error
for _, p := range t.Plugins {
wg.Add(1)
nodeName := p.NodeName()
if nodeName == "" {
nodeName = "unknown"
}
log.Trace("[v2ray] starting plugin on %s (node: %s)", p.ListenAddr(), nodeName)
go func(p plugin.Server) {
if e := p.ListenAndServe(); e != nil {
log.Warn("[v2ray] plugin on %s (node: %s) exited with error: %v", p.ListenAddr(), p.NodeName(), e)
err = e
} else {
log.Trace("[v2ray] plugin on %s (node: %s) stopped", p.ListenAddr(), p.NodeName())
}
wg.Done()
}(p)
}
log.Trace("[v2ray] all plugins are starting...")
return err
return nil
}
type Addr struct {
@@ -1519,7 +1480,6 @@ func (t *Template) resolveOutbounds(
weight int
outbound coreObj.OutboundObject
balancer bool
plugin plugin.Server
}
serverInfo2Index := make(map[*serverInfo]int)
for i := range serverData.ServerInfos {
@@ -1532,8 +1492,7 @@ func (t *Template) resolveOutbounds(
setting := configure.GetSettingNotNil()
for obj, sInfos := range serverData.ServerObj2ServerInfos() {
var (
usedByBalancer bool
balancerPluginPort int
usedByBalancer bool
)
// an vmessInfo(server template) may be used by multiple serverInfos(a connected server)
@@ -1548,7 +1507,6 @@ func (t *Template) resolveOutbounds(
// balancer
if !usedByBalancer {
usedByBalancer = true
balancerPluginPort = sInfo.PluginPort
}
balancers = append(balancers, balancer{
name: sInfo.OutboundName,
@@ -1570,24 +1528,10 @@ func (t *Template) resolveOutbounds(
// Store server info for this outbound
t.serverInfoMap[outboundTag] = sInfo
extraOutbounds = append(extraOutbounds, c.ExtraOutbounds...)
if c.PluginManagerServerLink != "" {
t.PluginManagerInfoList = append(t.PluginManagerInfoList, PluginManagerInfo{
Link: c.PluginManagerServerLink,
Port: sInfo.PluginPort,
})
}
var s plugin.Server
if len(c.PluginChain) > 0 {
s, err = plugin.ServerFromChain(c.PluginChain, sInfo.Info.GetName())
if err != nil {
return nil, nil, err
}
}
outbounds = append(outbounds, _outbound{
weight: serverInfo2Index[sInfo],
outbound: c.CoreOutbound,
balancer: false,
plugin: s,
})
outboundTags[serverInfo2Index[sInfo]] = outboundTag
supportUDP[sInfo.OutboundName] = c.UDPSupport
@@ -1600,7 +1544,7 @@ func (t *Template) resolveOutbounds(
Variant: t.Variant,
CoreVersion: t.CoreVersion,
Tag: outboundTag,
PluginPort: balancerPluginPort,
PluginPort: 0,
Backend: resolveEffectiveBackend(obj, setting),
})
if err != nil {
@@ -1614,12 +1558,6 @@ func (t *Template) resolveOutbounds(
for _, v := range balancers {
c.CoreOutbound.Balancers = append(c.CoreOutbound.Balancers, v.name)
}
if c.PluginManagerServerLink != "" {
t.PluginManagerInfoList = append(t.PluginManagerInfoList, PluginManagerInfo{
Link: c.PluginManagerServerLink,
Port: balancerPluginPort,
})
}
// we use the lowest serverInfo index as the order weight of the balancer outbound
weight := -1
for _, v := range balancers {
@@ -1630,18 +1568,10 @@ func (t *Template) resolveOutbounds(
// tag
outboundTags[index] = outboundTag
}
var s plugin.Server
if len(c.PluginChain) > 0 {
s, err = plugin.ServerFromChain(c.PluginChain, obj.GetName())
if err != nil {
return nil, nil, err
}
}
outbounds = append(outbounds, _outbound{
weight: weight,
outbound: c.CoreOutbound,
balancer: true,
plugin: s,
})
// if any node does not support UDP, the outbound should be tagged as UDP unsupported
@@ -1660,9 +1590,6 @@ func (t *Template) resolveOutbounds(
return outbounds[i].weight < outbounds[j].weight
})
for _, v := range outbounds {
if v.plugin != nil {
t.Plugins = append(t.Plugins, v.plugin)
}
t.Outbounds = append(t.Outbounds, v.outbound)
}
t.Outbounds = append(t.Outbounds, coreObj.OutboundObject{
@@ -1742,15 +1669,20 @@ func (t *Template) SetAPI(serverData *ServerData) (port int, err error) {
Tag: outbound,
Settings: coreObj.Observatory{
SubjectSelector: selector,
ProbeURL: probeUrl,
ProbeInterval: interval.String(),
PingConfig: &coreObj.PingConfig{
Destination: probeUrl,
Interval: interval.String(),
},
// Keep legacy fields for backward compatibility with older custom cores.
ProbeURL: probeUrl,
ProbeInterval: interval.String(),
},
})
}
}
if t.MultiObservatory != nil || t.Observatory != nil {
// v2raya_core supports ObservatoryService via the v2ray-compat gRPC path.
if t.Variant == where.V2rayaCore {
// v2raya_core supports ObservatoryService via the v2ray-compat gRPC path.
if t.Variant == where.V2rayaCore {
var observatoryTags []string
for name, isGroup := range t.outNames() {
@@ -2091,24 +2023,6 @@ func (t *Template) InsertMappingOutbound(o serverObj.ServerObj, inboundPort stri
if err != nil {
return err
}
if len(c.PluginChain) > 0 {
if server, err := plugin.ServerFromChain(c.PluginChain, o.GetName()); err != nil {
return err
} else {
t.Plugins = append(t.Plugins, server)
}
}
if c.PluginManagerServerLink != "" {
t.PluginManagerInfoList = append(t.PluginManagerInfoList, PluginManagerInfo{
Link: c.PluginManagerServerLink,
Port: pluginPort,
})
}
if strings.EqualFold(protocol, "") || strings.EqualFold(protocol, "socks") {
if len(c.PluginChain) > 0 && c.UDPSupport {
udpSupport = true
}
}
var mark = 0x80
t.checkAndSetMark(&c.CoreOutbound, mark)
t.Outbounds = append(t.Outbounds, c.CoreOutbound)
+1 -33
View File
@@ -2,8 +2,6 @@ module github.com/v2rayA/v2rayA
go 1.24.7
require github.com/daeuniverse/outbound v0.0.0-20250722064253-00c4fbb38759
require (
github.com/adrg/xdg v0.4.0
github.com/beevik/ntp v0.3.0
@@ -25,7 +23,6 @@ require (
github.com/v2fly/v2ray-core/v5 v5.7.0
github.com/v2rayA/RoutingA v1.0.2
github.com/v2rayA/beego/v2 v2.0.7
github.com/v2rayA/shadowsocksR v1.0.4
github.com/v2rayA/v2rayA-lib4 v0.0.0-20230812094818-595f87cb2a49
github.com/vearutop/statigz v1.1.7
go.etcd.io/bbolt v1.3.8
@@ -38,74 +35,47 @@ require (
require (
github.com/andybalholm/brotli v1.0.6 // indirect
github.com/awnumar/fastrand v0.0.0-20210315215012-30ee0990fa2d // indirect
github.com/awnumar/memcall v0.0.0-20190816154910-db5ea08008a3 // indirect
github.com/awnumar/memguard v0.19.1 // indirect
github.com/bytedance/sonic v1.11.2 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
github.com/chenzhuoyu/iasm v0.9.1 // indirect
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d // indirect
github.com/dgryski/go-idea v0.0.0-20170306091226-d2fb45a411fb // indirect
github.com/dgryski/go-rc2 v0.0.0-20150621095337-8a9021637152 // indirect
github.com/djherbis/times v1.5.0 // indirect
github.com/eknkc/basex v1.0.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.19.0 // indirect
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
github.com/gocarina/gocsv v0.0.0-20210408192840-02d7211d929d // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/google/pprof v0.0.0-20250208200701-d0013a598941 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/klauspost/compress v1.17.4 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mzz2017/disk-bloom v1.0.1 // indirect
github.com/oklog/ulid/v2 v2.1.1 // indirect
github.com/olicesx/quic-go v0.0.0-20260226044315-bb65418d151a // indirect
github.com/onsi/ginkgo/v2 v2.22.2 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.1.1 // indirect
github.com/pires/go-proxyproto v0.7.0 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/quic-go/qpack v0.5.1 // indirect
github.com/quic-go/qtls-go1-20 v0.3.3 // indirect
github.com/refraction-networking/utls v1.8.2 // indirect
github.com/sagernet/sing v0.6.0 // indirect
github.com/sagernet/sing-shadowtls v0.2.0 // indirect
github.com/samber/lo v1.52.0 // indirect
github.com/samber/oops v1.19.4 // indirect
github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/stretchr/testify v1.11.1 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/yusufpapurcu/wmi v1.2.2 // indirect
gitlab.com/yawning/chacha20.git v0.0.0-20230427033715-7877545b1b37 // indirect
go.opentelemetry.io/otel v1.29.0 // indirect
go.opentelemetry.io/otel/trace v1.29.0 // indirect
go.uber.org/mock v0.5.0 // indirect
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba // indirect
golang.org/x/arch v0.7.0 // indirect
golang.org/x/crypto v0.41.0 // indirect
golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3 // indirect
golang.org/x/mod v0.26.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/time v0.7.0 // indirect
golang.org/x/tools v0.35.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230807174057-1744710a1577 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
lukechampine.com/blake3 v1.4.1 // indirect
)
// Replace dependency modules with local developing copy
@@ -117,5 +87,3 @@ require (
// replace github.com/daeuniverse/softwind => ../../softwind
replace github.com/v2fly/v2ray-core/v5 => github.com/v2rayA/v2ray-core/v5 v5.0.0-20230812170925-960565fa0686
replace github.com/daeuniverse/outbound => github.com/olicesx/outbound v0.0.0-sticky-ip.0.20260331084054-80c3a9f61c45
+1 -83
View File
@@ -7,13 +7,6 @@ github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI=
github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/awnumar/fastrand v0.0.0-20210315215012-30ee0990fa2d h1:NkqtWyrOjr0QK1FSCmXS6Whbwh100Qt74SaRn92PemU=
github.com/awnumar/fastrand v0.0.0-20210315215012-30ee0990fa2d/go.mod h1:TO59kqNCiDBKS0qjRYUI8qJtkFL6SkP2EKqeOQ6xg/o=
github.com/awnumar/memcall v0.0.0-20190811121346-2affb857f00a/go.mod h1:sbEXyqNZZ3Cebk+6zOUmFNN8OuHHlugjiUmqn2tfiiM=
github.com/awnumar/memcall v0.0.0-20190816154910-db5ea08008a3 h1:pq6ZBJsmKeTOUOgeX3Ed6Td4loLrca4xIq6lstFN7AI=
github.com/awnumar/memcall v0.0.0-20190816154910-db5ea08008a3/go.mod h1:CszzLMKGwNr15cNA+0SuWkZLnPXGgUw+9kxRNbwUVnE=
github.com/awnumar/memguard v0.19.1 h1:y9k2r1XKaBeLWvB3kyQPNyxD/+qxwDjeZwX+4VZXzUk=
github.com/awnumar/memguard v0.19.1/go.mod h1:tewJ+MrJ12cFtR5gH5zNJs8A6BjBv8709binaV+1pws=
github.com/beevik/ntp v0.3.0 h1:xzVrPrE4ziasFXgBVBZJDP0Wg/KpMwk2KHJ4Ba8GrDw=
github.com/beevik/ntp v0.3.0/go.mod h1:hIHWr+l3+/clUnF44zdK+CWW7fO8dR5cIylAQ76NRpg=
github.com/boljen/go-bitmap v0.0.0-20151001105940-23cd2fb0ce7d h1:zsO4lp+bjv5XvPTF58Vq+qgmZEYZttJK+CWtSZhKenI=
@@ -40,22 +33,12 @@ github.com/devfeel/mapper v0.7.5 h1:YZISGXQbYkdh5Gn3uJlL++UqCzMJDxZoYKAtS58ZdGo=
github.com/devfeel/mapper v0.7.5/go.mod h1:foz4u16jrssGoDfnWYQGFcthjlU6uBV5UV8uYJfKneA=
github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1 h1:CaO/zOnF8VvUfEbhRatPcwKVWamvbYd8tQGRWacE9kU=
github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1/go.mod h1:+hnT3ywWDTAFrW5aE+u2Sa/wT555ZqwoCS+pk3p6ry4=
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d h1:CPqTNIigGweVPT4CYb+OO2E6XyRKFOmvTHwWRLgCAlE=
github.com/dgryski/go-camellia v0.0.0-20191119043421-69a8a13fb23d/go.mod h1:QX5ZVULjAfZJux/W62Y91HvCh9hyW6enAwcrrv/sLj0=
github.com/dgryski/go-idea v0.0.0-20170306091226-d2fb45a411fb h1:zXpN5126w/mhECTkqazBkrOJIMatbPP71aSIDR5UuW4=
github.com/dgryski/go-idea v0.0.0-20170306091226-d2fb45a411fb/go.mod h1:F7WkpqJj9t98ePxB/WJGQTIDeOVPuSJ3qdn6JUjg170=
github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140 h1:y7y0Oa6UawqTFPCDw9JG6pdKt4F9pAhHv0B7FMGaGD0=
github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140/go.mod h1:c9O8+fpSOX1DM8cPNSkX/qsBWdkD4yd2dpciOWQjpBw=
github.com/dgryski/go-rc2 v0.0.0-20150621095337-8a9021637152 h1:ED31mPIxDJnrLt9W9dH5xgd/6KjzEACKHBVGQ33czc0=
github.com/dgryski/go-rc2 v0.0.0-20150621095337-8a9021637152/go.mod h1:I9fhc/EvSg88cDxmfQ47v35Ssz9rlFunL/KY0A1JAYI=
github.com/djherbis/times v1.5.0 h1:79myA211VwPhFTqUk8xehWrsEO+zcIZj0zT8mXPVARU=
github.com/djherbis/times v1.5.0/go.mod h1:5q7FDLvbNg1L/KaBmPcWlVR9NmoKo3+ucqUA3ijQhA0=
github.com/ebfe/bcrypt_pbkdf v0.0.0-20140212075826-3c8d2dcb253a h1:YtdtTUN1iH97s+6PUjLnaiKSQj4oG1/EZ3N9bx6g4kU=
github.com/ebfe/bcrypt_pbkdf v0.0.0-20140212075826-3c8d2dcb253a/go.mod h1:/CZpbhAusDOobpcb9yubw46kdYjq0zRC0Wpg9a9zFQM=
github.com/ebfe/rc2 v0.0.0-20131011165748-24b9757f5521 h1:fBHFH+Y/GPGFGo7LIrErQc3p2MeAhoIQNgaxPWYsSxk=
github.com/ebfe/rc2 v0.0.0-20131011165748-24b9757f5521/go.mod h1:ucvhdsUCE3TH0LoLRb6ShHiJl8e39dGlx6A4g/ujlow=
github.com/eknkc/basex v1.0.1 h1:TcyAkqh4oJXgV3WYyL4KEfCMk9W8oJCpmx1bo+jVgKY=
github.com/eknkc/basex v1.0.1/go.mod h1:k/F/exNEHFdbs3ZHuasoP2E7zeWwZblG84Y7Z59vQRo=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/gin-contrib/cors v1.6.0 h1:0Z7D/bVhE6ja07lI8CTjTonp6SB07o8bNuFyRbsBUQg=
@@ -70,8 +53,6 @@ github.com/go-chi/render v1.0.2 h1:4ER/udB0+fMWB2Jlf15RV3F4A2FDuYi/9f+lFttR/Lg=
github.com/go-chi/render v1.0.2/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0=
github.com/go-leo/slicex v1.0.14 h1:55wIj8dF8q8kXECRuynPH+crJSLlBvIvIKq9aINDidI=
github.com/go-leo/slicex v1.0.14/go.mod h1:C89MVuPcTxesKqUXwHhUQ9oU8fHRkif547Gdmv0YXyw=
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
@@ -83,6 +64,7 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.19.0 h1:ol+5Fu+cSq9JD7SoSqe04GMI92cbn0+wvQ3bZ8b/AU4=
github.com/go-playground/validator/v10 v10.19.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI=
github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/gocarina/gocsv v0.0.0-20201103164230-b291445e0dd2/go.mod h1:5YoVOkjYAQumqlV356Hj3xeYh4BdZuLE0/nRkf2NKkI=
@@ -102,8 +84,6 @@ github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20250208200701-d0013a598941 h1:43XjGa6toxLpeksjcxs1jIoIyr+vUfOqY2c6HB4bpoc=
github.com/google/pprof v0.0.0-20250208200701-d0013a598941/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
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/jhump/protoreflect v1.15.1 h1:HUMERORf3I3ZdX05WaQ6MIpd/NJ434hTp5YiKgfCL6c=
@@ -146,22 +126,11 @@ github.com/mustafaturan/bus v1.0.2 h1:2x3ErwZ0uUPwwZ5ZZoknEQprdaxr68Yl3mY8jDye1W
github.com/mustafaturan/bus v1.0.2/go.mod h1:h7gfehm8TThv4Dcaa+wDQG7r7j6p74v+7ftr0Rq9i1Q=
github.com/mustafaturan/monoton v1.0.0 h1:8SCej+JiNn0lyps7V+Jzc1CRAkDR4EZPWrTupQ61YCQ=
github.com/mustafaturan/monoton v1.0.0/go.mod h1:FOnE7NV3s3EWPXb8/7+/OSdiMBbdlkV0Lz8p1dc+vy8=
github.com/mzz2017/disk-bloom v1.0.1 h1:rEF9MiXd9qMW3ibRpqcerLXULoTgRlM21yqqJl1B90M=
github.com/mzz2017/disk-bloom v1.0.1/go.mod h1:JLHETtUu44Z6iBmsqzkOtFlRvXSlKnxjwiBRDapizDI=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s=
github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=
github.com/olicesx/outbound v0.0.0-sticky-ip.0.20260331084054-80c3a9f61c45 h1:a7ze7ED9eJ46fAbKxlBkDKwj/5wo6llrDvFiRkFoZ1E=
github.com/olicesx/outbound v0.0.0-sticky-ip.0.20260331084054-80c3a9f61c45/go.mod h1:9tP4s+zsFE4HqSoqz0kIsvE4TeMfaLsXGsdS6jIaW10=
github.com/olicesx/quic-go v0.0.0-20260226044315-bb65418d151a h1:Y+ONsSTQsqr2PpiXQnOU+pIcTILGn7qhHMzim1GYqoM=
github.com/olicesx/quic-go v0.0.0-20260226044315-bb65418d151a/go.mod h1:4i75wxoxXaebP2bt5TFzSx9zf3+M7g8NQJ8PZIaIuIQ=
github.com/onsi/ginkgo/v2 v2.22.2 h1:/3X8Panh8/WwhU/3Ssa6rCKqPLuAkVY2I0RoyDLySlU=
github.com/onsi/ginkgo/v2 v2.22.2/go.mod h1:oeMosUL+8LtarXBHu/c0bx2D/K9zyQ6uX3cTyztHwsk=
github.com/onsi/gomega v1.36.2 h1:koNYke6TVk6ZmnyHrCXba/T/MoLBXFjeC1PtvYgw0A8=
github.com/onsi/gomega v1.36.2/go.mod h1:DdwyADRjrc825LhMEkD76cHR5+pUnjhUN8GlHlRPHzY=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
@@ -185,8 +154,6 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw=
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
github.com/quic-go/qtls-go1-20 v0.3.3 h1:17/glZSLI9P9fDAeyCHBFSWSqJcwx1byhLwP5eUIDCM=
github.com/quic-go/qtls-go1-20 v0.3.3/go.mod h1:X9Nh97ZL80Z+bX/gUXMbipO6OxdiDi58b/fMC9mAL+k=
github.com/quic-go/quic-go v0.37.4 h1:ke8B73yMCWGq9MfrCCAw0Uzdm7GaViC3i39dsIdDlH4=
@@ -197,14 +164,6 @@ github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 h1:f/FNXud6gA3MNr
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3/go.mod h1:HgjTstvQsPGkxUsCd2KWxErBblirPizecHcpD3ffK+s=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/sagernet/sing v0.6.0 h1:jT55zAXrG7H3x+s/FlrC15xQy3LcmuZ2GGA9+8IJdt0=
github.com/sagernet/sing v0.6.0/go.mod h1:ARkL0gM13/Iv5VCZmci/NuoOlePoIsW0m7BWfln/Hak=
github.com/sagernet/sing-shadowtls v0.2.0 h1:cLKe4OAOFwuhmAIuPLj//CIL7Q9js+pIDardhJ+/osk=
github.com/sagernet/sing-shadowtls v0.2.0/go.mod h1:agU+Fw5X+xnWVyRHyFthoZCX3MfWKCFPm4JUf+1oaxo=
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
github.com/samber/oops v1.19.4 h1:NMzXd3JtdJ4IM2dJgJ4/W8V2bljeCACKYRfPg9vWjeg=
github.com/samber/oops v1.19.4/go.mod h1:Hsm/sKPxtCfPh0w/cE3xVoRfSiE1joDRiStPAsmG9bo=
github.com/secure-io/siv-go v0.0.0-20180922214919-5ff40651e2c4 h1:zOjq+1/uLzn/Xo40stbvjIY/yehG0+mfmlsiEmc0xmQ=
github.com/secure-io/siv-go v0.0.0-20180922214919-5ff40651e2c4/go.mod h1:aI+8yClBW+1uovkHw6HM01YXnYB8vohtB9C83wzx34E=
github.com/seiflotfy/cuckoofilter v0.0.0-20220411075957-e3b120b3f5fb h1:XfLJSPIOUX+osiMraVgIrMR27uMXnRJWGm1+GL8/63U=
@@ -213,18 +172,12 @@ github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 h1:DAYUYH5869yV94
github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg=
github.com/shirou/gopsutil/v3 v3.21.11 h1:d5tOAP5+bmJ8Hf2+4bxOSkQ/64+sjEbjU9nSW9nJgG0=
github.com/shirou/gopsutil/v3 v3.21.11/go.mod h1:BToYZVTlSVlfazpDDYFnsVZLaoRG+g8ufT6fPQLdJzA=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stevenroose/gonfig v0.1.5 h1:6rIKxNWEU/S/auIVMedWiOqGtnSSwsa5c+a0VTyGHjM=
github.com/stevenroose/gonfig v0.1.5/go.mod h1:JBkjIE8NdLbRNBowFCgK7wirNR0GHhnRhtdJgZMIylM=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
@@ -256,8 +209,6 @@ github.com/v2rayA/RoutingA v1.0.2 h1:UHBIdrflQ0zj+PXnEDLj9D2aTk2gYreIsvtfPKNdpu4
github.com/v2rayA/RoutingA v1.0.2/go.mod h1:M9kQE+WtKChg48TABm9jdVBPjvm1bNDjm1zFPNfyU/c=
github.com/v2rayA/beego/v2 v2.0.7 h1:1794GEbEnC0VQ2TOVWFmaiyHreMQKJZf5kGQK7VH0yc=
github.com/v2rayA/beego/v2 v2.0.7/go.mod h1:DfxatafB8bCtcjsFtDVVR5Qq7XC+HOcfwFAVmpFaIco=
github.com/v2rayA/shadowsocksR v1.0.4 h1:65Ltdy+I/DnlkQTJj+R+X85zhZ63ORE1Roy+agAcF/s=
github.com/v2rayA/shadowsocksR v1.0.4/go.mod h1:CyOhDLy8/AKedsi16xRYAMmkxSCH1ukJPaacaTdRfQg=
github.com/v2rayA/v2ray-core/v5 v5.0.0-20230812170925-960565fa0686 h1:8XPGtxiuXq947v27WlwYk2oVvKCjjLjoJl0ooQIjQYI=
github.com/v2rayA/v2ray-core/v5 v5.0.0-20230812170925-960565fa0686/go.mod h1:tiVJLn1dTYsGQewhzmMYpBTyLuCAFDJIPz7FkzHUelI=
github.com/v2rayA/v2rayA-lib4 v0.0.0-20230812094818-595f87cb2a49 h1:FE97Oau4RRlIKTCpMAg6rBxy+mhtbZDgF0UcRbntTt4=
@@ -270,68 +221,38 @@ github.com/xtaci/smux v1.5.24 h1:77emW9dtnOxxOQ5ltR+8BbsX1kzcOxQ5gB+aaV9hXOY=
github.com/xtaci/smux v1.5.24/go.mod h1:OMlQbT5vcgl2gb49mFkYo6SMf+zP3rcjcwQz7ZU7IGY=
github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg=
github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
gitlab.com/yawning/chacha20.git v0.0.0-20190903091407-6d1cb28dc72c/go.mod h1:3x6b94nWCP/a2XB/joOPMiGYUBvqbLfeY/BkHLeDs6s=
gitlab.com/yawning/chacha20.git v0.0.0-20230427033715-7877545b1b37 h1:ZrWBE3u/o9cHU2mySXf1687MaK09JOeZt1A+fHnCjmU=
gitlab.com/yawning/chacha20.git v0.0.0-20230427033715-7877545b1b37/go.mod h1:3x6b94nWCP/a2XB/joOPMiGYUBvqbLfeY/BkHLeDs6s=
go.etcd.io/bbolt v1.3.8 h1:xs88BrvEv273UsB79e0hcVrlUWmS0a8upikMFhSyAtA=
go.etcd.io/bbolt v1.3.8/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8=
go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4=
go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ=
go.starlark.net v0.0.0-20230612165344-9532f5667272 h1:2/wtqS591wZyD2OsClsVBKRPEvBsQt/Js+fsCiYhwu8=
go.starlark.net v0.0.0-20230612165344-9532f5667272/go.mod h1:jxU+3+j+71eXOW14274+SmmuW82qJzl6iZSeqEtTGds=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.7.0 h1:pskyeJh/3AmoQ8CPE95vxHLqp1G1GfGNXTmcl9NEKTc=
golang.org/x/arch v0.7.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3 h1:qNgPs5exUA+G0C96DrPwNrvLSj7GT/9D+3WMWUcUg34=
golang.org/x/exp v0.0.0-20250207012021-f9890c6ad9f3/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU=
golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190116161447-11f53e031339/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190902133755-9109b7679e13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201202213521-69691e467435/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210816074244-15123e1e1f71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ=
golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -347,7 +268,6 @@ google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/g
google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
@@ -357,7 +277,5 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/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=
lukechampine.com/blake3 v1.4.1 h1:I3Smz7gso8w4/TunLKec6K2fn+kyKtDxr/xcQEN84Wg=
lukechampine.com/blake3 v1.4.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
-14
View File
@@ -3,20 +3,6 @@ package main
import (
"github.com/gin-gonic/gin"
_ "github.com/v2rayA/v2rayA/conf/report"
_ "github.com/v2rayA/v2rayA/pkg/plugin/anytls"
_ "github.com/v2rayA/v2rayA/pkg/plugin/http"
_ "github.com/v2rayA/v2rayA/pkg/plugin/hysteria2"
_ "github.com/v2rayA/v2rayA/pkg/plugin/juicity"
_ "github.com/v2rayA/v2rayA/pkg/plugin/simpleobfs"
_ "github.com/v2rayA/v2rayA/pkg/plugin/socks5"
_ "github.com/v2rayA/v2rayA/pkg/plugin/ss"
_ "github.com/v2rayA/v2rayA/pkg/plugin/ssr"
_ "github.com/v2rayA/v2rayA/pkg/plugin/tcp"
_ "github.com/v2rayA/v2rayA/pkg/plugin/tls"
_ "github.com/v2rayA/v2rayA/pkg/plugin/trojan"
_ "github.com/v2rayA/v2rayA/pkg/plugin/trojanc"
_ "github.com/v2rayA/v2rayA/pkg/plugin/tuic"
_ "github.com/v2rayA/v2rayA/pkg/plugin/ws"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
-73
View File
@@ -1,73 +0,0 @@
package anytls
import (
"context"
"fmt"
"net"
"github.com/daeuniverse/outbound/dialer"
"github.com/daeuniverse/outbound/dialer/anytls"
"github.com/daeuniverse/outbound/netproxy"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
_ "github.com/daeuniverse/outbound/protocol/anytls"
)
type AnyTLS struct {
dialer netproxy.Dialer
}
func init() {
log.Trace("[anytls] registering dialer")
plugin.RegisterDialer("anytls", NewAnytlsDialer)
}
func NewAnytlsDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
dialer, _, err := anytls.NewAnytls(
&dialer.ExtraOption{},
&plugin.Converter{
Dialer: d,
},
s,
)
if err != nil {
return nil, err
}
return &AnyTLS{
dialer: dialer,
}, nil
}
func (a *AnyTLS) Addr() string {
return ""
}
func (a *AnyTLS) Dial(network, address string) (net.Conn, error) {
return a.DialContext(context.Background(), network, address)
}
func (a *AnyTLS) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
magicNetwork := netproxy.MagicNetwork{
Network: network,
Mark: plugin.ShouldSetMark(),
}
conn, err := a.dialer.DialContext(ctx, magicNetwork.Encode(), address)
if err != nil {
return nil, err
}
return plugin.NewFakeNetConn(conn), nil
}
func (a *AnyTLS) DialUDP(network string) (plugin.FakeNetPacketConn, error) {
log.Info("[%s] dialing udp", "anytls")
magicNetwork := netproxy.MagicNetwork{
Network: "udp",
Mark: plugin.ShouldSetMark(),
}
rc, err := a.dialer.DialContext(context.TODO(), magicNetwork.Encode(), "")
if err != nil {
return nil, fmt.Errorf("[anytls]: dial udp %w", err)
}
return plugin.NewFakeNetPacketConn(rc.(netproxy.PacketConn)), nil
}
-52
View File
@@ -1,52 +0,0 @@
package plugin
import (
"fmt"
"net/url"
"strings"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// The first is a server plugin, and the others are client plugins. Split by ",".
func ServerFromChain(chain string, nodeName string) (s Server, err error) {
log.Trace("[plugin] building server from chain: %s (node: %s)", chain, nodeName)
plugins := strings.Split(chain, ",")
if len(plugins) == 0 {
return nil, fmt.Errorf("empty plugin chain")
}
server := plugins[0]
log.Trace("[plugin] server plugin: %s (node: %s)", server, nodeName)
var dialer Dialer = &Direct{}
for i := 1; i < len(plugins); i++ {
log.Trace("[plugin] adding client plugin [%d/%d]: %s (node: %s)", i, len(plugins)-1, plugins[i], nodeName)
dialer, err = DialerFromURL(plugins[i], dialer)
if err != nil {
log.Warn("[plugin] failed to build client plugin chain at step %d (node: %s): %v", i, nodeName, err)
return nil, fmt.Errorf("build client plugin %d (%s): %w", i, plugins[i], err)
}
}
log.Trace("[plugin] creating server from URL: %s (node: %s)", server, nodeName)
// Extract protocol from the first client plugin (outbound protocol)
// The server is the inbound protocol, client plugins are the outbound protocols
protocol := "direct"
if len(plugins) > 1 {
// Use the first client plugin's protocol as it's the actual outbound protocol
if u, err := url.Parse(plugins[1]); err == nil && u.Scheme != "" {
protocol = u.Scheme
}
}
s, err = ServerFromURL(server, nodeName, Dialer2Proxy(dialer, nodeName, protocol))
if err != nil {
log.Warn("[plugin] failed to create server (node: %s): %v", nodeName, err)
return nil, fmt.Errorf("create server: %w", err)
}
log.Trace("[plugin] successfully built server chain (node: %s)", nodeName)
return s, nil
}
-48
View File
@@ -1,48 +0,0 @@
package plugin
import (
"context"
"fmt"
"github.com/daeuniverse/outbound/netproxy"
)
type Converter struct {
Dialer
}
// DialContext implements netproxy.Dialer.
func (c *Converter) DialContext(ctx context.Context, network string, addr string) (netproxy.Conn, error) {
magic, err := netproxy.ParseMagicNetwork(network)
if err != nil {
return nil, err
}
switch magic.Network {
case "tcp":
rc, err := c.Dialer.DialContext(ctx, magic.Network, addr)
if err != nil {
return nil, err
}
if nrc, ok := rc.(netproxy.Conn); ok {
return nrc, nil
}
return &netproxy.FakeNetConn{Conn: rc, LAddr: rc.LocalAddr(), RAddr: rc.RemoteAddr()}, nil
case "udp":
pc, err := c.Dialer.DialUDP(magic.Network)
if err != nil {
return nil, err
}
return &PacketConnConverter{
PacketConn: pc,
Target: addr,
}, nil
}
return nil, fmt.Errorf("unexpected network: %v", magic.Network)
}
// Dial implements netproxy.Dialer.
func (c *Converter) Dial(network string, addr string) (netproxy.Conn, error) {
return c.DialContext(context.TODO(), network, addr)
}
var _ netproxy.Dialer = &Converter{}
-189
View File
@@ -1,189 +0,0 @@
package plugin
import (
"context"
"fmt"
"net"
"net/url"
"runtime"
"strings"
"syscall"
"github.com/daeuniverse/outbound/netproxy"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
type FakeNetPacketConn interface {
net.PacketConn
}
type fakeNetPacketConn struct {
netproxy.PacketConn
}
type fakeNetConn struct {
netproxy.Conn
}
func (f *fakeNetConn) LocalAddr() net.Addr {
return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 30000}
}
func (f *fakeNetConn) RemoteAddr() net.Addr {
return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 80}
}
func (f *fakeNetConn) Read(b []byte) (n int, err error) {
n, err = f.Conn.Read(b)
if n > 0 {
log.Trace("[conn] read %d bytes from %v", n, f.RemoteAddr())
}
return
}
func (f *fakeNetConn) Write(b []byte) (n int, err error) {
n, err = f.Conn.Write(b)
if n > 0 {
log.Trace("[conn] write %d bytes to %v", n, f.RemoteAddr())
}
return
}
func (f *fakeNetConn) SyscallConn() (syscall.RawConn, error) {
if sc, ok := f.Conn.(syscall.Conn); ok {
return sc.SyscallConn()
}
return nil, fmt.Errorf("connection doesn't allow to get Syscall.RawConn")
}
func NewFakeNetConn(c netproxy.Conn) net.Conn {
if c == nil {
return nil
}
return &fakeNetConn{Conn: c}
}
func (f *fakeNetPacketConn) LocalAddr() net.Addr {
return &net.UDPAddr{}
}
func (f *fakeNetPacketConn) RemoteAddr() net.Addr {
return &net.UDPAddr{}
}
func (f *fakeNetPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
n, ap, err := f.PacketConn.ReadFrom(p)
if err != nil {
return 0, nil, err
}
return n, net.UDPAddrFromAddrPort(ap), nil
}
func (f *fakeNetPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
return f.PacketConn.WriteTo(p, addr.String())
}
func (f *fakeNetPacketConn) WriteMsgUDP(b []byte, oob []byte, addr *net.UDPAddr) (n int, oobn int, err error) {
if pc, ok := f.PacketConn.(interface {
WriteMsgUDP(b []byte, oob []byte, addr *net.UDPAddr) (n int, oobn int, err error)
}); ok {
return pc.WriteMsgUDP(b, oob, addr)
}
return 0, 0, fmt.Errorf("WriteMsgUDP not supported by underlying PacketConn: %T", f.PacketConn)
}
func (f *fakeNetPacketConn) SyscallConn() (syscall.RawConn, error) {
if sc, ok := f.PacketConn.(syscall.Conn); ok {
return sc.SyscallConn()
}
return nil, fmt.Errorf("connection doesn't allow to get Syscall.RawConn")
}
func NewFakeNetPacketConn(pc netproxy.PacketConn) FakeNetPacketConn {
return &fakeNetPacketConn{PacketConn: pc}
}
// Dialer is used to create connection.
type Dialer interface {
// Addr is the dialer's addr
Addr() string
// Dial connects to the given address
Dial(network, addr string) (c net.Conn, err error)
DialContext(ctx context.Context, network, addr string) (c net.Conn, err error)
// DialUDP connects to the given address
DialUDP(network string) (pc FakeNetPacketConn, err error)
}
// DialerCreator is a function to create dialers.
type DialerCreator func(s string, dialer Dialer) (Dialer, error)
var (
dialerMap = make(map[string]DialerCreator)
)
// RegisterDialer is used to register a dialer.
func RegisterDialer(name string, c DialerCreator) {
dialerMap[name] = c
}
// getAvailableSchemes returns a list of registered dialer schemes
func getAvailableSchemes() []string {
schemes := make([]string, 0, len(dialerMap))
for k := range dialerMap {
schemes = append(schemes, k)
}
return schemes
}
// DialerFromURL calls the registered creator to create dialers.
// dialer is the default upstream dialer so cannot be nil, we can use Default when calling this function.
func DialerFromURL(s string, dialer Dialer) (Dialer, error) {
if dialer == nil {
return nil, fmt.Errorf("DialerFromURL: dialer cannot be nil")
}
u, err := url.Parse(s)
if err != nil {
log.Warn("[plugin] parse URL '%s' failed: %v", s, err)
return nil, fmt.Errorf("parse URL: %w", err)
}
scheme := strings.ToLower(u.Scheme)
c, ok := dialerMap[scheme]
if !ok {
log.Warn("[plugin] unknown scheme '%s' in URL: %s. Available schemes: %v", u.Scheme, s, getAvailableSchemes())
return nil, fmt.Errorf("unknown scheme '%s'", u.Scheme)
}
log.Trace("[plugin] creating dialer for scheme '%s' from URL: %s", scheme, s)
result, err := c(s, dialer)
if err != nil {
log.Warn("[plugin] failed to create dialer for scheme '%s': %v", scheme, err)
return nil, fmt.Errorf("create %s dialer: %w", scheme, err)
}
log.Trace("[plugin] successfully created dialer for scheme '%s'", scheme)
return result, nil
}
// ShouldSetMark determines if SO_MARK should be set on sockets.
// SO_MARK should only be set on Linux with root privileges.
// Returns 0x80 if mark should be set, 0 otherwise.
func ShouldSetMark() uint32 {
// Don't set mark on Windows or macOS (they don't support redirect/tproxy)
if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
return 0
}
// Don't set mark in lite mode (no root privileges)
if conf.GetEnvironmentConfig().Lite {
return 0
}
// Set mark on Linux with root privileges
return 0x80
}
-67
View File
@@ -1,67 +0,0 @@
package plugin
import (
"context"
"net"
"net/netip"
"github.com/daeuniverse/outbound/netproxy"
"github.com/daeuniverse/outbound/protocol/direct"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
var (
directDialer netproxy.Dialer
)
func init() {
directDialer = direct.NewDirectDialerLaddr(netip.Addr{}, direct.Option{FullCone: true})
}
type Direct struct {
}
// Addr implements Dialer.
func (d *Direct) Addr() string {
return ""
}
// Dial implements Dialer.
func (d *Direct) Dial(network string, addr string) (c net.Conn, err error) {
return d.DialContext(context.Background(), network, addr)
}
func (d *Direct) DialContext(ctx context.Context, network string, addr string) (c net.Conn, err error) {
log.Info("[%s] dialing %s", "direct", addr)
magicNetwork := netproxy.MagicNetwork{
Network: network,
Mark: ShouldSetMark(),
}
conn, err := directDialer.DialContext(ctx, magicNetwork.Encode(), addr)
if err != nil {
return nil, err
}
return NewFakeNetConn(conn), nil
}
// DialUDP implements Dialer.
func (d *Direct) DialUDP(network string) (pc FakeNetPacketConn, err error) {
log.Info("[%s] dialing udp", "direct")
magicNetwork := netproxy.MagicNetwork{
Network: "udp",
Mark: ShouldSetMark(),
}
conn, err := directDialer.DialContext(context.TODO(), magicNetwork.Encode(), "")
if err != nil {
return nil, err
}
// directDialer returns directPacketConn which implements net.PacketConn
// and has SyscallConn() method. Return it directly to preserve raw socket access.
if netConn, ok := conn.(net.PacketConn); ok {
return netConn, nil
}
// Fallback: wrap it if it's not a net.PacketConn
return NewFakeNetPacketConn(conn.(netproxy.PacketConn)), nil
}
var _ Dialer = &Direct{}
-68
View File
@@ -1,68 +0,0 @@
package http
import (
"context"
"fmt"
"net"
"github.com/daeuniverse/outbound/dialer"
"github.com/daeuniverse/outbound/dialer/http"
"github.com/daeuniverse/outbound/netproxy"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
_ "github.com/daeuniverse/outbound/protocol/http"
)
// HTTP is a base http struct
type HTTP struct {
dialer netproxy.Dialer
}
func init() {
log.Trace("[http] registering dialer")
plugin.RegisterDialer("http", NewHTTPDialer)
plugin.RegisterDialer("https", NewHTTPDialer)
}
func NewHTTPDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
dialer, _, err := http.NewHTTP(
&dialer.ExtraOption{
TlsImplementation: "tls",
},
&plugin.Converter{
Dialer: d,
},
s,
)
if err != nil {
return nil, err
}
return &HTTP{
dialer: dialer,
}, nil
}
// Addr returns forwarder's address.
func (s *HTTP) Addr() string {
return ""
}
// Dial connects to the address addr on the network net via the infra.
func (s *HTTP) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *HTTP) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
rc, err := s.dialer.DialContext(ctx, "tcp", addr)
if err != nil {
return nil, fmt.Errorf("[http]: dial to %s: %w", addr, err)
}
return plugin.NewFakeNetConn(rc), nil
}
// DialUDP connects to the given address via the infra.
func (s *HTTP) DialUDP(network string) (plugin.FakeNetPacketConn, error) {
return nil, fmt.Errorf("[http] udp not supported")
}
-76
View File
@@ -1,76 +0,0 @@
package hysteria2
import (
"context"
"fmt"
"net"
"github.com/daeuniverse/outbound/dialer"
"github.com/daeuniverse/outbound/dialer/hysteria2"
"github.com/daeuniverse/outbound/netproxy"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// Hysteria2 is a base hysteria2 struct
type Hysteria2 struct {
dialer netproxy.Dialer
}
func init() {
log.Trace("[hysteria2] registering dialer")
plugin.RegisterDialer("hysteria2", NewHysteria2Dialer)
}
func NewHysteria2Dialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
dialer, _, err := hysteria2.NewHysteria2(
&dialer.ExtraOption{},
&plugin.Converter{
Dialer: d,
},
s,
)
if err != nil {
return nil, err
}
return &Hysteria2{
dialer: dialer,
}, nil
}
// Addr returns forwarder's address.
func (s *Hysteria2) Addr() string {
return ""
}
// Dial connects to the address addr on the network net via the infra.
func (s *Hysteria2) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Hysteria2) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
magicNetwork := netproxy.MagicNetwork{
Network: network,
Mark: plugin.ShouldSetMark(),
}
conn, err := s.dialer.DialContext(ctx, magicNetwork.Encode(), addr)
if err != nil {
return nil, err
}
return plugin.NewFakeNetConn(conn), nil
}
// DialUDP connects to the given address via the infra.
func (s *Hysteria2) DialUDP(network string) (plugin.FakeNetPacketConn, error) {
log.Info("[%s] dialing udp", "hysteria2")
magicNetwork := netproxy.MagicNetwork{
Network: "udp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(context.TODO(), magicNetwork.Encode(), "")
if err != nil {
return nil, fmt.Errorf("[hysteria2]: dial udp %w", err)
}
return plugin.NewFakeNetPacketConn(rc.(netproxy.PacketConn)), nil
}
@@ -1,16 +0,0 @@
package common
import "crypto/sha256"
func GenerateCertChainHash(rawCerts [][]byte) (chainHash []byte) {
for _, cert := range rawCerts {
certHash := sha256.Sum256(cert)
if chainHash == nil {
chainHash = certHash[:]
} else {
newHash := sha256.Sum256(append(chainHash, certHash[:]...))
chainHash = newHash[:]
}
}
return chainHash
}
-78
View File
@@ -1,78 +0,0 @@
package juicity
import (
"context"
"fmt"
"net"
"github.com/daeuniverse/outbound/dialer"
"github.com/daeuniverse/outbound/dialer/juicity"
"github.com/daeuniverse/outbound/netproxy"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
_ "github.com/daeuniverse/outbound/protocol/juicity"
)
// Juicity is a base juicity struct
type Juicity struct {
dialer netproxy.Dialer
}
func init() {
log.Trace("[juicity] registering dialer")
plugin.RegisterDialer("juicity", NewJuicityDialer)
}
func NewJuicityDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
dialer, _, err := juicity.NewJuicity(
&dialer.ExtraOption{},
&plugin.Converter{
Dialer: d,
},
s,
)
if err != nil {
return nil, err
}
return &Juicity{
dialer: dialer,
}, nil
}
// Addr returns forwarder's address.
func (s *Juicity) Addr() string {
return ""
}
// Dial connects to the address addr on the network net via the infra.
func (s *Juicity) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Juicity) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
magicNetwork := netproxy.MagicNetwork{
Network: "tcp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(ctx, magicNetwork.Encode(), addr)
if err != nil {
return nil, fmt.Errorf("[juicity]: dial to %s: %w", addr, err)
}
return plugin.NewFakeNetConn(rc), nil
}
// DialUDP connects to the given address via the infra.
func (s *Juicity) DialUDP(network string) (plugin.FakeNetPacketConn, error) {
log.Info("[%s] dialing udp", "juicity")
magicNetwork := netproxy.MagicNetwork{
Network: "udp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(context.TODO(), magicNetwork.Encode(), "")
if err != nil {
return nil, fmt.Errorf("[juicity]: dial udp %w", err)
}
return plugin.NewFakeNetPacketConn(rc.(netproxy.PacketConn)), nil
}
-109
View File
@@ -1,109 +0,0 @@
package plugin
import (
"fmt"
"net"
"net/netip"
"syscall"
"github.com/daeuniverse/outbound/netproxy"
)
type PacketConnConverter struct {
net.PacketConn
Target string
cacheTgt net.Addr
}
// Read implements netproxy.PacketConn.
func (pc *PacketConnConverter) Read(b []byte) (n int, err error) {
n, _, err = pc.PacketConn.ReadFrom(b)
return
}
// Write implements netproxy.PacketConn.
func (pc *PacketConnConverter) Write(b []byte) (n int, err error) {
if pc.cacheTgt == nil {
addr, err := net.ResolveUDPAddr("udp", pc.Target)
if err != nil {
return 0, err
}
pc.cacheTgt = addr
}
return pc.PacketConn.WriteTo(b, pc.cacheTgt)
}
// ReadFrom implements netproxy.PacketConn.
func (pc *PacketConnConverter) ReadFrom(p []byte) (n int, addr netip.AddrPort, err error) {
n, _addr, err := pc.PacketConn.ReadFrom(p)
if err != nil {
return 0, netip.AddrPort{}, err
}
return n, _addr.(*net.UDPAddr).AddrPort(), nil
}
// WriteTo implements netproxy.PacketConn.
func (pc *PacketConnConverter) WriteTo(p []byte, _addr string) (n int, err error) {
addr, err := net.ResolveUDPAddr("udp", _addr)
if err != nil {
return 0, err
}
return pc.PacketConn.WriteTo(p, addr)
}
func (pc *PacketConnConverter) SetWriteBuffer(size int) error {
c, ok := pc.PacketConn.(interface{ SetWriteBuffer(int) error })
if !ok {
return fmt.Errorf("connection doesn't allow setting of send buffer size. Not a *net.UDPConn?: %T", pc.PacketConn)
}
return c.SetWriteBuffer(size)
}
func (pc *PacketConnConverter) SetReadBuffer(size int) error {
c, ok := pc.PacketConn.(interface{ SetReadBuffer(int) error })
if !ok {
return fmt.Errorf("connection doesn't allow setting of send buffer size. Not a *net.UDPConn?: %T", pc.PacketConn)
}
return c.SetReadBuffer(size)
}
func (pc *PacketConnConverter) SyscallConn() (syscall.RawConn, error) {
c, ok := pc.PacketConn.(interface {
SyscallConn() (syscall.RawConn, error)
})
if !ok {
return nil, fmt.Errorf("connection doesn't allow to get Syscall.RawConn. Not a *net.UDPConn?: %T", pc.PacketConn)
}
return c.SyscallConn()
}
// ReadMsgUDP implements quic.OOBCapablePacketConn.
func (conn *PacketConnConverter) ReadMsgUDP(b []byte, oob []byte) (n int, oobn int, flags int, addr *net.UDPAddr, err error) {
c, ok := conn.PacketConn.(interface {
ReadMsgUDP(b []byte, oob []byte) (n int, oobn int, flags int, addr *net.UDPAddr, err error)
})
if !ok {
return 0, 0, 0, nil, fmt.Errorf("connection doesn't allow to get ReadMsgUDP. Not a *net.UDPConn? : %T", conn.PacketConn)
}
return c.ReadMsgUDP(b, oob)
}
// WriteMsgUDP implements quic.OOBCapablePacketConn.
func (conn *PacketConnConverter) WriteMsgUDP(b []byte, oob []byte, addr *net.UDPAddr) (n int, oobn int, err error) {
c, ok := conn.PacketConn.(interface {
WriteMsgUDP(b []byte, oob []byte, addr *net.UDPAddr) (n int, oobn int, err error)
})
if !ok {
// Log additional context for debugging
return 0, 0, fmt.Errorf("connection doesn't allow to get WriteMsgUDP. Not a *net.UDPConn? : %T, target: %v", conn.PacketConn, addr)
}
return c.WriteMsgUDP(b, oob, addr)
}
var _ netproxy.PacketConn = &PacketConnConverter{}
var _ interface {
SyscallConn() (syscall.RawConn, error)
SetReadBuffer(int) error
ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error)
WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error)
} = &PacketConnConverter{}
-74
View File
@@ -1,74 +0,0 @@
package plugin
import (
"context"
"net"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// Proxy is a dialer manager
type Proxy interface {
// Dial connects to the given address via the proxy.
Dial(network, addr string) (c net.Conn, proxy string, err error)
DialContext(ctx context.Context, network, addr string) (c net.Conn, proxy string, err error)
// DialUDP connects to the given address via the proxy.
DialUDP(network string) (pc FakeNetPacketConn, proxy string, err error)
// Get the dialer by dstAddr
NextDialer(dstAddr string) Dialer
}
type DirectProxy struct {
Dialer Dialer
NodeName string
Protocol string
}
func Dialer2Proxy(dialer Dialer, nodeName string, protocol string) (p Proxy) {
return DirectProxy{
Dialer: dialer,
NodeName: nodeName,
Protocol: protocol,
}
}
// Dial connects to the given address via the infra.
func (p DirectProxy) Dial(network, addr string) (net.Conn, string, error) {
return p.DialContext(context.Background(), network, addr)
}
func (p DirectProxy) DialContext(ctx context.Context, network, addr string) (net.Conn, string, error) {
nodeInfo := ""
if p.NodeName != "" {
nodeInfo = "[" + p.NodeName + "]"
}
protocolInfo := ""
if p.Protocol != "" {
protocolInfo = "[" + p.Protocol + "]"
}
prefix := nodeInfo + protocolInfo
if prefix == "" {
prefix = "[proxy]"
}
c, err := p.Dialer.DialContext(ctx, network, addr)
if err != nil {
log.Info("%s dial %s failed: %v", prefix, addr, err)
} else {
log.Info("%s dial %s success", prefix, addr)
}
return c, p.Dialer.Addr(), err
}
// DialUDP connects to the given address via the infra.
func (p DirectProxy) DialUDP(network string) (pc FakeNetPacketConn, proxy string, err error) {
pc, err = p.Dialer.DialUDP(network)
return pc, p.Dialer.Addr(), err
}
func (p DirectProxy) NextDialer(dstAddr string) Dialer {
return &Direct{}
}
-75
View File
@@ -1,75 +0,0 @@
package plugin
import (
"fmt"
"net/url"
"strings"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// Server interface
type Server interface {
// ListenAndServe sets up a listener and serve on it
ListenAndServe() error
ListenAddr() string
NodeName() string
Close() error
}
// ServerCreator is a function to create proxy servers
type ServerCreator func(s string, nodeName string, proxy Proxy) (Server, error)
var (
serverCreators = make(map[string]ServerCreator)
)
// RegisterServer is used to register a proxy server
func RegisterServer(name string, c ServerCreator) {
serverCreators[name] = c
}
// getAvailableServerSchemes returns a list of registered server schemes
func getAvailableServerSchemes() []string {
schemes := make([]string, 0, len(serverCreators))
for k := range serverCreators {
schemes = append(schemes, k)
}
return schemes
}
// ServerFromURL calls the registered creator to create proxy servers
// dialer is the default upstream dialer so cannot be nil, we can use Default when calling this function
func ServerFromURL(s string, nodeName string, p Proxy) (Server, error) {
if p == nil {
return nil, fmt.Errorf("ServerFromURL: dialer cannot be nil")
}
if !strings.Contains(s, "://") {
s = "socks5://" + s
log.Trace("[plugin] URL scheme missing, defaulting to socks5: %s", s)
}
u, err := url.Parse(s)
if err != nil {
log.Warn("[plugin] parse server URL '%s' failed: %v", s, err)
return nil, fmt.Errorf("parse URL: %w", err)
}
scheme := strings.ToLower(u.Scheme)
c, ok := serverCreators[scheme]
if !ok {
log.Warn("[plugin] unknown server scheme '%s' in URL: %s. Available schemes: %v", u.Scheme, s, getAvailableServerSchemes())
return nil, fmt.Errorf("unknown server scheme '%s'", u.Scheme)
}
log.Trace("[plugin] creating server for scheme '%s' from URL: %s (node: %s)", scheme, s, nodeName)
result, err := c(s, nodeName, p)
if err != nil {
log.Warn("[plugin] failed to create server for scheme '%s' (node: %s): %v", scheme, nodeName, err)
return nil, fmt.Errorf("create %s server: %w", scheme, err)
}
log.Info("[plugin] successfully created server for scheme '%s' at %s (node: %s)", scheme, result.ListenAddr(), nodeName)
return result, nil
}
-85
View File
@@ -1,85 +0,0 @@
//go:build linux
// +build linux
package plugin
import (
"fmt"
"github.com/v2rayA/v2rayA/pkg/util/log"
"golang.org/x/sys/unix"
"net"
"runtime"
"syscall"
)
var fwmarkIoctl int
func init() {
switch runtime.GOOS {
case "linux", "android":
fwmarkIoctl = 36 /* unix.SO_MARK */
case "freebsd":
fwmarkIoctl = 0x1015 /* unix.SO_USER_COOKIE */
case "openbsd":
fwmarkIoctl = 0x1021 /* unix.SO_RTABLE */
}
}
func SoMarkControl(c syscall.RawConn) error {
return c.Control(func(fd uintptr) {
//TODO: force to set 0xff. any chances to customize this value?
err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, fwmarkIoctl, 0x80)
if err != nil {
return
}
})
}
func BindControl(c syscall.RawConn, laddr string, lport uint32) error {
return c.Control(func(fd uintptr) {
err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, fwmarkIoctl, 0x80)
if err != nil {
log.Warn("control: %s", err)
return
}
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil {
log.Warn("control: failed to set IP_TRANSPARENT")
return
}
ip := net.ParseIP(laddr).To4()
if err := bindAddr(fd, ip, lport); err != nil {
log.Warn("control: %s", err)
return
}
})
}
func bindAddr(fd uintptr, ip []byte, port uint32) error {
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1); err != nil {
return fmt.Errorf("failed to set resuse_addr")
}
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
return fmt.Errorf("failed to set resuse_port")
}
var sockaddr syscall.Sockaddr
switch len(ip) {
case net.IPv4len:
a4 := &syscall.SockaddrInet4{
Port: int(port),
}
copy(a4.Addr[:], ip)
sockaddr = a4
case net.IPv6len:
a6 := &syscall.SockaddrInet6{
Port: int(port),
}
copy(a6.Addr[:], ip)
sockaddr = a6
default:
return fmt.Errorf("unexpected length of ip")
}
return syscall.Bind(int(fd), sockaddr)
}
-13
View File
@@ -1,13 +0,0 @@
//go:build !linux
// +build !linux
package plugin
import "syscall"
func SoMarkControl(c syscall.RawConn) error {
return nil
}
func BindControl(c syscall.RawConn, laddr string, lport uint32) error {
return nil
}
-107
View File
@@ -1,107 +0,0 @@
// from https://github.com/Dreamacro/clash/blob/master/component/simple-obfs/http.go
package simpleobfs
import (
"bytes"
"encoding/base64"
"fmt"
"github.com/v2rayA/shadowsocksR/tools/leakybuf"
"io"
"math/rand"
"net"
"net/http"
"strings"
"sync"
)
// HTTPObfs is shadowsocks http simple-obfs implementation
type HTTPObfs struct {
net.Conn
host string
port string
path string
buf []byte
offset int
firstRequest bool
firstResponse bool
rMu sync.Mutex
wMu sync.Mutex
}
func (ho *HTTPObfs) Read(b []byte) (int, error) {
ho.rMu.Lock()
defer ho.rMu.Unlock()
if ho.buf != nil {
n := copy(b, ho.buf[ho.offset:])
ho.offset += n
if ho.offset == len(ho.buf) {
leakybuf.GlobalLeakyBuf.Put(ho.buf)
ho.buf = nil
}
return n, nil
}
if ho.firstResponse {
buf := leakybuf.GlobalLeakyBuf.Get()
n, err := ho.Conn.Read(buf)
if err != nil {
leakybuf.GlobalLeakyBuf.Put(buf)
return 0, err
}
idx := bytes.Index(buf[:n], []byte("\r\n\r\n"))
if idx == -1 {
leakybuf.GlobalLeakyBuf.Put(buf)
return 0, io.EOF
}
ho.firstResponse = false
length := n - (idx + 4)
n = copy(b, buf[idx+4:n])
if length > n {
ho.buf = buf[:idx+4+length]
ho.offset = idx + 4 + n
} else {
leakybuf.GlobalLeakyBuf.Put(buf)
}
return n, nil
}
return ho.Conn.Read(b)
}
func (ho *HTTPObfs) Write(b []byte) (int, error) {
ho.wMu.Lock()
defer ho.wMu.Unlock()
if ho.firstRequest {
randBytes := make([]byte, 16)
rand.Read(randBytes)
req, _ := http.NewRequest("GET", fmt.Sprintf("http://%s%s", ho.host, ho.path), bytes.NewBuffer(b[:]))
req.Header.Set("User-Agent", fmt.Sprintf("curl/7.%d.%d", rand.Int()%54, rand.Int()%2))
req.Header.Set("Upgrade", "websocket")
req.Header.Set("Connection", "Upgrade")
if ho.port != "80" {
req.Host = fmt.Sprintf("%s:%s", ho.host, ho.port)
}
req.Header.Set("Sec-WebSocket-Key", base64.URLEncoding.EncodeToString(randBytes))
req.ContentLength = int64(len(b))
err := req.Write(ho.Conn)
ho.firstRequest = false
return len(b), err
}
return ho.Conn.Write(b)
}
// NewHTTPObfs return a HTTPObfs
func NewHTTPObfs(conn net.Conn, host string, port string, path string) net.Conn {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return &HTTPObfs{
Conn: conn,
firstRequest: true,
firstResponse: true,
host: host,
port: port,
path: path,
}
}
-111
View File
@@ -1,111 +0,0 @@
package simpleobfs
import (
"context"
"fmt"
"net"
"net/url"
"strings"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
type ObfsType int
const (
HTTP ObfsType = iota
TLS
)
func init() {
log.Trace("[simpleobfs] registering dialer")
plugin.RegisterDialer("simpleobfs", NewSimpleObfsDialer)
plugin.RegisterDialer("simple-obfs", NewSimpleObfsDialer)
plugin.RegisterDialer("obfs-local", NewSimpleObfsDialer)
}
// NewSimpleObfsDialer returns a simple-obfs proxy dialer.
func NewSimpleObfsDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
return NewSimpleObfs(s, d)
}
// SimpleObfs is a base http-obfs struct
type SimpleObfs struct {
dialer plugin.Dialer
obfstype ObfsType
addr string
path string
host string
}
// NewSimpleobfs returns a simpleobfs proxy.
func NewSimpleObfs(s string, d plugin.Dialer) (*SimpleObfs, error) {
u, err := url.Parse(s)
if err != nil {
return nil, fmt.Errorf("simpleobfs: %w", err)
}
t := &SimpleObfs{
dialer: d,
addr: u.Host,
}
query := u.Query()
obfstype := query.Get("type")
if obfstype == "" {
obfstype = query.Get("obfs")
}
switch strings.ToLower(obfstype) {
case "http":
t.obfstype = HTTP
case "tls":
t.obfstype = TLS
default:
return nil, fmt.Errorf("unsupported obfs type %v", obfstype)
}
t.host = query.Get("host")
t.path = query.Get("path")
if t.path == "" {
t.path = query.Get("uri")
}
return t, nil
}
// Addr returns forwarder's address.
func (s *SimpleObfs) Addr() string {
if s.addr == "" {
return s.dialer.Addr()
}
return s.addr
}
// Dial connects to the address addr on the network net via the proxy.
func (s *SimpleObfs) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *SimpleObfs) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
log.Info("[simpleobfs] dialing %s via %s (type=%v host=%v path=%v)", addr, s.addr, s.obfstype, s.host, s.path)
rc, err := s.dialer.DialContext(ctx, "tcp", s.addr)
if err != nil {
return nil, fmt.Errorf("[simpleobfs]: dial to %s: %w", s.addr, err)
}
var c net.Conn
switch s.obfstype {
case HTTP:
_, port, _ := net.SplitHostPort(s.addr)
if port == "" {
port = "80"
}
c = NewHTTPObfs(rc, s.host, port, s.path)
case TLS:
c = NewTLSObfs(rc, s.host)
}
return c, nil
}
// DialUDP connects to the given address via the proxy.
func (s *SimpleObfs) DialUDP(network string) (pc plugin.FakeNetPacketConn, err error) {
//TODO
return nil, nil
}
-203
View File
@@ -1,203 +0,0 @@
// from https://github.com/Dreamacro/clash/blob/master/component/simple-obfs/tls.go
package simpleobfs
import (
"bytes"
"encoding/binary"
"io"
"math/rand"
"net"
"sync"
"time"
)
func init() {
rand.Seed(time.Now().Unix())
}
const (
chunkSize = 1 << 14 // 2 ** 14 == 16 * 1024
)
// TLSObfs is shadowsocks tls simple-obfs implementation
type TLSObfs struct {
net.Conn
server string
remain int
firstRequest bool
firstResponse bool
rMu sync.Mutex
wMu sync.Mutex
}
func (to *TLSObfs) read(b []byte, discardN int) (int, error) {
buf := make([]byte, discardN)
_, err := io.ReadFull(to.Conn, buf)
if err != nil {
return 0, err
}
sizeBuf := make([]byte, 2)
_, err = io.ReadFull(to.Conn, sizeBuf)
if err != nil {
return 0, nil
}
length := int(binary.BigEndian.Uint16(sizeBuf))
if length > len(b) {
n, err := to.Conn.Read(b)
if err != nil {
return n, err
}
to.remain = length - n
return n, nil
}
return io.ReadFull(to.Conn, b[:length])
}
func (to *TLSObfs) Read(b []byte) (int, error) {
to.rMu.Lock()
defer to.rMu.Unlock()
if to.remain > 0 {
length := to.remain
if length > len(b) {
length = len(b)
}
n, err := io.ReadFull(to.Conn, b[:length])
to.remain -= n
return n, err
}
if to.firstResponse {
// type + ver + lensize + 91 = 96
// type + ver + lensize + 1 = 6
// type + ver = 3
to.firstResponse = false
return to.read(b, 105)
}
// type + ver = 3
return to.read(b, 3)
}
func (to *TLSObfs) Write(b []byte) (int, error) {
to.wMu.Lock()
defer to.wMu.Unlock()
length := len(b)
for i := 0; i < length; i += chunkSize {
end := i + chunkSize
if end > length {
end = length
}
n, err := to.write(b[i:end])
if err != nil {
return n, err
}
}
return length, nil
}
func (to *TLSObfs) write(b []byte) (int, error) {
if to.firstRequest {
helloMsg := makeClientHelloMsg(b, to.server)
_, err := to.Conn.Write(helloMsg)
to.firstRequest = false
return len(b), err
}
buf := &bytes.Buffer{}
buf.Write([]byte{0x17, 0x03, 0x03})
binary.Write(buf, binary.BigEndian, uint16(len(b)))
buf.Write(b)
_, err := to.Conn.Write(buf.Bytes())
return len(b), err
}
// NewTLSObfs return a SimpleObfs
func NewTLSObfs(conn net.Conn, server string) net.Conn {
return &TLSObfs{
Conn: conn,
server: server,
firstRequest: true,
firstResponse: true,
}
}
func makeClientHelloMsg(data []byte, server string) []byte {
random := make([]byte, 28)
sessionID := make([]byte, 32)
rand.Read(random)
rand.Read(sessionID)
buf := &bytes.Buffer{}
// handshake, TLS 1.0 version, length
buf.WriteByte(22)
buf.Write([]byte{0x03, 0x01})
length := uint16(212 + len(data) + len(server))
buf.WriteByte(byte(length >> 8))
buf.WriteByte(byte(length & 0xff))
// clientHello, length, TLS 1.2 version
buf.WriteByte(1)
buf.WriteByte(0)
binary.Write(buf, binary.BigEndian, uint16(208+len(data)+len(server)))
buf.Write([]byte{0x03, 0x03})
// random with timestamp, sid len, sid
binary.Write(buf, binary.BigEndian, uint32(time.Now().Unix()))
buf.Write(random)
buf.WriteByte(32)
buf.Write(sessionID)
// cipher suites
buf.Write([]byte{0x00, 0x38})
buf.Write([]byte{
0xc0, 0x2c, 0xc0, 0x30, 0x00, 0x9f, 0xcc, 0xa9, 0xcc, 0xa8, 0xcc, 0xaa, 0xc0, 0x2b, 0xc0, 0x2f,
0x00, 0x9e, 0xc0, 0x24, 0xc0, 0x28, 0x00, 0x6b, 0xc0, 0x23, 0xc0, 0x27, 0x00, 0x67, 0xc0, 0x0a,
0xc0, 0x14, 0x00, 0x39, 0xc0, 0x09, 0xc0, 0x13, 0x00, 0x33, 0x00, 0x9d, 0x00, 0x9c, 0x00, 0x3d,
0x00, 0x3c, 0x00, 0x35, 0x00, 0x2f, 0x00, 0xff,
})
// compression
buf.Write([]byte{0x01, 0x00})
// extension length
binary.Write(buf, binary.BigEndian, uint16(79+len(data)+len(server)))
// session ticket
buf.Write([]byte{0x00, 0x23})
binary.Write(buf, binary.BigEndian, uint16(len(data)))
buf.Write(data)
// server name
buf.Write([]byte{0x00, 0x00})
binary.Write(buf, binary.BigEndian, uint16(len(server)+5))
binary.Write(buf, binary.BigEndian, uint16(len(server)+3))
buf.WriteByte(0)
binary.Write(buf, binary.BigEndian, uint16(len(server)))
buf.Write([]byte(server))
// ec_point
buf.Write([]byte{0x00, 0x0b, 0x00, 0x04, 0x03, 0x01, 0x00, 0x02})
// groups
buf.Write([]byte{0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x1d, 0x00, 0x17, 0x00, 0x19, 0x00, 0x18})
// signature
buf.Write([]byte{
0x00, 0x0d, 0x00, 0x20, 0x00, 0x1e, 0x06, 0x01, 0x06, 0x02, 0x06, 0x03, 0x05,
0x01, 0x05, 0x02, 0x05, 0x03, 0x04, 0x01, 0x04, 0x02, 0x04, 0x03, 0x03, 0x01,
0x03, 0x02, 0x03, 0x03, 0x02, 0x01, 0x02, 0x02, 0x02, 0x03,
})
// encrypt then mac
buf.Write([]byte{0x00, 0x16, 0x00, 0x00})
// extended master secret
buf.Write([]byte{0x00, 0x17, 0x00, 0x00})
return buf.Bytes()
}
-167
View File
@@ -1,167 +0,0 @@
package socks
import (
"errors"
"io"
"net"
"strconv"
)
// SOCKS auth type
const (
AuthNone = 0
AuthPassword = 2
)
// SOCKS request commands as defined in RFC 1928 section 4
const (
CmdError byte = 0
CmdConnect byte = 1
CmdBind byte = 2
CmdUDPAssociate byte = 3
)
// SOCKS address types as defined in RFC 1928 section 5
const (
ATypIP4 = 1
ATypDomain = 3
ATypIP6 = 4
)
// MaxAddrLen is the maximum size of SOCKS address in bytes
const MaxAddrLen = 1 + 1 + 255 + 2
// Errors are socks5 errors
var Errors = []error{
errors.New(""),
errors.New("general failure"),
errors.New("connection forbidden"),
errors.New("network unreachable"),
errors.New("host unreachable"),
errors.New("connection refused"),
errors.New("TTL expired"),
errors.New("command not supported"),
errors.New("address type not supported"),
errors.New("socks5UDPAssociate"),
}
// Addr represents a SOCKS address as defined in RFC 1928 section 5.
type Addr []byte
// String serializes SOCKS address a to string form.
func (a Addr) String() string {
var host, port string
switch a[0] { // address type
case ATypDomain:
host = string(a[2 : 2+int(a[1])])
port = strconv.Itoa((int(a[2+int(a[1])]) << 8) | int(a[2+int(a[1])+1]))
case ATypIP4:
host = net.IP(a[1 : 1+net.IPv4len]).String()
port = strconv.Itoa((int(a[1+net.IPv4len]) << 8) | int(a[1+net.IPv4len+1]))
case ATypIP6:
host = net.IP(a[1 : 1+net.IPv6len]).String()
port = strconv.Itoa((int(a[1+net.IPv6len]) << 8) | int(a[1+net.IPv6len+1]))
}
return net.JoinHostPort(host, port)
}
// ReadAddrBuf reads just enough bytes from r to get a valid Addr.
func ReadAddrBuf(r io.Reader, b []byte) (Addr, error) {
if len(b) < MaxAddrLen {
return nil, io.ErrShortBuffer
}
_, err := io.ReadFull(r, b[:1]) // read 1st byte for address type
if err != nil {
return nil, err
}
switch b[0] {
case ATypDomain:
_, err = io.ReadFull(r, b[1:2]) // read 2nd byte for domain length
if err != nil {
return nil, err
}
_, err = io.ReadFull(r, b[2:2+int(b[1])+2])
return b[:1+1+int(b[1])+2], err
case ATypIP4:
_, err = io.ReadFull(r, b[1:1+net.IPv4len+2])
return b[:1+net.IPv4len+2], err
case ATypIP6:
_, err = io.ReadFull(r, b[1:1+net.IPv6len+2])
return b[:1+net.IPv6len+2], err
}
return nil, Errors[8]
}
// ReadAddr reads just enough bytes from r to get a valid Addr.
func ReadAddr(r io.Reader) (Addr, error) {
return ReadAddrBuf(r, make([]byte, MaxAddrLen))
}
// SplitAddr slices a SOCKS address from beginning of b. Returns nil if failed.
func SplitAddr(b []byte) Addr {
addrLen := 1
if len(b) < addrLen {
return nil
}
switch b[0] {
case ATypDomain:
if len(b) < 2 {
return nil
}
addrLen = 1 + 1 + int(b[1]) + 2
case ATypIP4:
addrLen = 1 + net.IPv4len + 2
case ATypIP6:
addrLen = 1 + net.IPv6len + 2
default:
return nil
}
if len(b) < addrLen {
return nil
}
return b[:addrLen]
}
// ParseAddr parses the address in string s. Returns nil if failed.
func ParseAddr(s string) Addr {
var addr Addr
host, port, err := net.SplitHostPort(s)
if err != nil {
return nil
}
if ip := net.ParseIP(host); ip != nil {
if ip4 := ip.To4(); ip4 != nil {
addr = make([]byte, 1+net.IPv4len+2)
addr[0] = ATypIP4
copy(addr[1:], ip4)
} else {
addr = make([]byte, 1+net.IPv6len+2)
addr[0] = ATypIP6
copy(addr[1:], ip)
}
} else {
if len(host) > 255 {
return nil
}
addr = make([]byte, 1+1+len(host)+2)
addr[0] = ATypDomain
addr[1] = byte(len(host))
copy(addr[2:], host)
}
portnum, err := strconv.ParseUint(port, 10, 16)
if err != nil {
return nil
}
addr[len(addr)-2], addr[len(addr)-1] = byte(portnum>>8), byte(portnum)
return addr
}
-99
View File
@@ -1,99 +0,0 @@
package socks5
import (
"github.com/v2rayA/v2rayA/pkg/plugin/socks"
"net"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// PktConn .
type PktConn struct {
net.PacketConn
writeAddr net.Addr // write to and read from addr
tgtAddr socks.Addr
tgtHeader bool
ctrlConn net.Conn // tcp control conn
}
// NewPktConn returns a PktConn
func NewPktConn(c net.PacketConn, writeAddr net.Addr, tgtAddr socks.Addr, tgtHeader bool, ctrlConn net.Conn) *PktConn {
pc := &PktConn{
PacketConn: c,
writeAddr: writeAddr,
tgtAddr: tgtAddr,
tgtHeader: tgtHeader,
ctrlConn: ctrlConn}
if ctrlConn != nil {
go func() {
buf := make([]byte, 1)
for {
_, err := ctrlConn.Read(buf)
if err, ok := err.(net.Error); ok && err.Timeout() {
continue
}
log.Trace("[socks5] dialudp udp associate end")
return
}
}()
}
return pc
}
// ReadFrom overrides the original function from net.PacketConn
func (pc *PktConn) ReadFrom(b []byte) (int, net.Addr, error) {
if !pc.tgtHeader {
return pc.PacketConn.ReadFrom(b)
}
buf := make([]byte, len(b))
n, raddr, err := pc.PacketConn.ReadFrom(buf)
if err != nil {
return n, raddr, err
}
// https://tools.ietf.org/html/rfc1928#section-7
// +----+------+------+----------+----------+----------+
// |RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
// +----+------+------+----------+----------+----------+
// | 2 | 1 | 1 | Variable | 2 | Variable |
// +----+------+------+----------+----------+----------+
tgtAddr := socks.SplitAddr(buf[3:])
copy(b, buf[3+len(tgtAddr):])
//test
if pc.writeAddr == nil {
pc.writeAddr = raddr
}
if pc.tgtAddr == nil {
pc.tgtAddr = tgtAddr
}
return n - len(tgtAddr) - 3, raddr, err
}
// WriteTo overrides the original function from net.PacketConn
func (pc *PktConn) WriteTo(b []byte, addr net.Addr) (int, error) {
if !pc.tgtHeader {
return pc.PacketConn.WriteTo(b, addr)
}
buf := append([]byte{0, 0, 0}, pc.tgtAddr...)
buf = append(buf, b[:]...)
return pc.PacketConn.WriteTo(buf, pc.writeAddr)
}
// Close .
func (pc *PktConn) Close() error {
if pc.ctrlConn != nil {
pc.ctrlConn.Close()
}
return pc.PacketConn.Close()
}
-528
View File
@@ -1,528 +0,0 @@
// https://tools.ietf.org/html/rfc1928
// socks5 client:
// https://github.com/golang/net/tree/master/proxy
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package socks5 implements a socks5 proxy.
package socks5
import (
"context"
"fmt"
"io"
"net"
"net/url"
"strconv"
"strings"
"time"
"github.com/v2rayA/shadowsocksR/tools/leakybuf"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/plugin/socks"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// Version is socks5 version number.
const Version = 5
// Socks5 is a base socks5 struct.
type Socks5 struct {
dialer plugin.Dialer
proxy plugin.Proxy
addr string
nodeName string
user string
password string
TcpListener net.Listener
}
func init() {
println("[DEBUG] socks5.init called")
log.Trace("[socks5] registering server and dialer")
plugin.RegisterServer("socks5", NewSocks5Server)
plugin.RegisterServer("socks", NewSocks5Server)
plugin.RegisterDialer("socks5", NewSocks5Dialer)
plugin.RegisterDialer("socks", NewSocks5Dialer)
}
// NewSocks5 returns a Proxy that makes SOCKS v5 connections to the given address
// with an optional username and password. (RFC 1928)
func NewSocks5(s string, nodeName string, d plugin.Dialer, p plugin.Proxy) (*Socks5, error) {
u, err := url.Parse(s)
if err != nil {
log.Warn("parse err: %s", err)
return nil, err
}
addr := u.Host
var user, pass string
if u.User != nil {
user = u.User.Username()
pass, _ = u.User.Password()
}
h := &Socks5{
dialer: d,
proxy: p,
addr: addr,
nodeName: nodeName,
user: user,
password: pass,
}
return h, nil
}
// NewSocks5Dialer returns a socks5 proxy dialer.
func NewSocks5Dialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
return NewSocks5(s, "", d, nil)
}
// NewSocks5Server returns a socks5 proxy server.
func NewSocks5Server(s string, nodeName string, p plugin.Proxy) (plugin.Server, error) {
return NewSocks5(s, nodeName, nil, p)
}
// ListenAndServe serves socks5 requests.
func (s *Socks5) ListenAndServe() error {
//go s.ListenAndServeUDP()
return s.ListenAndServeTCP()
}
func (s *Socks5) ListenAddr() string {
return s.addr
}
func (s *Socks5) NodeName() string {
return s.nodeName
}
// ListenAndServeTCP listen and serve on tcp port.
func (s *Socks5) ListenAndServeTCP() error {
l, err := net.Listen("tcp", s.addr)
if err != nil {
log.Warn("[socks5] failed to listen on %s: %v", s.addr, err)
return err
}
s.TcpListener = l
log.Trace("[socks5] listening TCP on %s", s.addr)
for {
c, err := l.Accept()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
return nil
}
log.Debug("[socks5] failed to accept: %v", err)
continue
}
go s.Serve(c)
}
}
func (s *Socks5) Close() error {
if s.TcpListener == nil {
return nil
}
return s.TcpListener.Close()
}
// Serve serves a connection.
func (s *Socks5) Serve(c net.Conn) {
defer c.Close()
log.Trace("[socks5] accepted connection from %s", c.RemoteAddr())
tgt, err := s.handshake(c)
if err != nil {
// UDP: keep the connection until disconnect then free the UDP socket
if err == socks.Errors[9] {
log.Trace("[socks5] UDP associate with %s", c.RemoteAddr())
buf := leakybuf.GlobalLeakyBuf.Get()
defer leakybuf.GlobalLeakyBuf.Put(buf)
// block here
for {
_, err := c.Read(buf)
if err, ok := err.(net.Error); ok && err.Timeout() {
continue
}
// log.Println("[socks5] servetcp udp associate end")
return
}
}
log.Debug("[socks5] failed in handshake with %s: %v", c.RemoteAddr(), err)
return
}
log.Trace("[socks5] %s requests to connect %v", c.RemoteAddr(), tgt)
// we should write the reply AFTER the dial to upstream is completed successfully,
// because the client (v2ray) may send data immediately after receiving the success reply.
rc, dialer, err := s.proxy.Dial("tcp", tgt.String())
if err != nil {
log.Trace("[socks5] %s <-> %s via %s, dial failed: %v", c.RemoteAddr(), tgt, dialer, err)
// send failure reply: 0x01 General SOCKS server failure
c.Write([]byte{5, 1, 0, 1, 0, 0, 0, 0, 0, 0})
return
}
defer rc.Close()
if _, err := c.Write([]byte{5, 0, 0, 1, 0, 0, 0, 0, 0, 0}); err != nil {
log.Trace("[socks5] %s <-> %s, failed to write success reply: %v", c.RemoteAddr(), tgt, err)
return
}
log.Trace("[socks5] %s <-> %s via %s established", c.RemoteAddr(), tgt, dialer)
n1, n2, err := Relay(c, rc)
if err != nil {
log.Trace("[socks5] relay error between %s and %s: %v, bytes: %d/%d", c.RemoteAddr(), tgt, err, n1, n2)
} else {
log.Trace("[socks5] %s <-> %s relay finished successfully, bytes: %d/%d", c.RemoteAddr(), tgt, n1, n2)
}
}
// Relay relays between left and right.
func Relay(left, right net.Conn) (int64, int64, error) {
type res struct {
N int64
Err error
}
ch := make(chan res)
go func() {
n, err := io.Copy(right, left)
right.SetDeadline(time.Now()) // wake up the other goroutine blocking on right
left.SetDeadline(time.Now()) // wake up the other goroutine blocking on left
ch <- res{n, err}
}()
n, err := io.Copy(left, right)
right.SetDeadline(time.Now()) // wake up the other goroutine blocking on right
left.SetDeadline(time.Now()) // wake up the other goroutine blocking on left
rs := <-ch
if err == nil {
err = rs.Err
}
return n, rs.N, err
}
// Addr returns forwarder's address.
func (s *Socks5) Addr() string {
if s.addr == "" {
return s.dialer.Addr()
}
return s.addr
}
// Dial connects to the address addr on the network net via the SOCKS5 proxy.
func (s *Socks5) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Socks5) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
switch network {
case "tcp", "tcp6", "tcp4":
default:
return nil, fmt.Errorf("[socks5]: no support for connection type %v", network)
}
c, err := s.dialer.DialContext(ctx, network, s.addr)
if err != nil {
log.Debug("[socks5]: dial to %s error: %s", s.addr, err)
return nil, err
}
if err := s.connect(c, addr); err != nil {
c.Close()
return nil, err
}
return c, nil
}
// DialUDP connects to the given address via the proxy.
func (s *Socks5) DialUDP(network string) (plugin.FakeNetPacketConn, error) {
c, err := s.dialer.DialContext(context.TODO(), "tcp", s.addr)
if err != nil {
log.Debug("[socks5] dialudp dial tcp to %s error: %s", s.addr, err)
return nil, err
}
// send VER, NMETHODS, METHODS
c.Write([]byte{Version, 1, 0})
buf := make([]byte, socks.MaxAddrLen)
// read VER METHOD
if _, err := io.ReadFull(c, buf[:2]); err != nil {
return nil, err
}
dstAddr := socks.ParseAddr("0.0.0.0:0")
// write VER CMD RSV ATYP DST.ADDR DST.PORT
c.Write(append([]byte{Version, socks.CmdUDPAssociate, 0}, dstAddr...))
// read VER REP RSV ATYP BND.ADDR BND.PORT
if _, err := io.ReadFull(c, buf[:3]); err != nil {
return nil, err
}
rep := buf[1]
if rep != 0 {
log.Debug("[socks5] server reply: %d, not succeeded", rep)
return nil, fmt.Errorf("server connect failed")
}
uAddr, err := socks.ReadAddrBuf(c, buf)
if err != nil {
return nil, err
}
pc, err := s.dialer.DialUDP(network)
if err != nil {
log.Debug("[socks5] dialudp to %s error: %s", uAddr.String(), err)
return nil, err
}
wAddr, _ := net.ResolveUDPAddr("udp", uAddr.String())
return NewPktConn(pc, wAddr, dstAddr, true, c), nil
}
// connect takes an existing connection to a socks5 proxy server,
// and commands the server to extend that connection to target,
// which must be a canonical address with a host and port.
func (s *Socks5) connect(conn net.Conn, target string) error {
host, portStr, err := net.SplitHostPort(target)
if err != nil {
return err
}
port, err := strconv.Atoi(portStr)
if err != nil {
return fmt.Errorf("proxy: failed to parse port number: %v", portStr)
}
if port < 1 || port > 0xffff {
return fmt.Errorf("proxy: port number out of range: %v", portStr)
}
// the size here is just an estimate
buf := make([]byte, 0, 6+len(host))
buf = append(buf, Version)
if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 {
buf = append(buf, 2 /* num auth methods */, socks.AuthNone, socks.AuthPassword)
} else {
buf = append(buf, 1 /* num auth methods */, socks.AuthNone)
}
if _, err := conn.Write(buf); err != nil {
return fmt.Errorf("proxy: failed to write greeting to SOCKS5 proxy at %v: %w", s.addr, err)
}
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
return fmt.Errorf("proxy: failed to read greeting from SOCKS5 proxy at %v: %w", s.addr, err)
}
if buf[0] != Version {
return fmt.Errorf("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0])))
}
if buf[1] == 0xff {
return fmt.Errorf("proxy: SOCKS5 proxy at " + s.addr + " requires authentication")
}
if buf[1] == socks.AuthPassword {
buf = buf[:0]
buf = append(buf, 1 /* password protocol version */)
buf = append(buf, uint8(len(s.user)))
buf = append(buf, s.user...)
buf = append(buf, uint8(len(s.password)))
buf = append(buf, s.password...)
if _, err := conn.Write(buf); err != nil {
return fmt.Errorf("proxy: failed to write authentication request to SOCKS5 proxy at %v: %w", s.addr, err)
}
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
return fmt.Errorf("proxy: failed to read authentication reply from SOCKS5 proxy at %v: %w", s.addr, err)
}
if buf[1] != 0 {
return fmt.Errorf("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password")
}
}
buf = buf[:0]
buf = append(buf, Version, socks.CmdConnect, 0 /* reserved */)
if ip := net.ParseIP(host); ip != nil {
if ip4 := ip.To4(); ip4 != nil {
buf = append(buf, socks.ATypIP4)
ip = ip4
} else {
buf = append(buf, socks.ATypIP6)
}
buf = append(buf, ip...)
} else {
if len(host) > 255 {
return fmt.Errorf("proxy: destination hostname too long: " + host)
}
buf = append(buf, socks.ATypDomain)
buf = append(buf, byte(len(host)))
buf = append(buf, host...)
}
buf = append(buf, byte(port>>8), byte(port))
if _, err := conn.Write(buf); err != nil {
return fmt.Errorf("proxy: failed to write connect request to SOCKS5 proxy at %v: %w", s.addr, err)
}
if _, err := io.ReadFull(conn, buf[:4]); err != nil {
return fmt.Errorf("proxy: failed to read connect reply from SOCKS5 proxy at %v: %w", s.addr, err)
}
if int(buf[1]) != 0 {
failure := "unknown error"
if int(buf[1]) < len(socks.Errors) {
failure = socks.Errors[buf[1]].Error()
}
return fmt.Errorf("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure)
}
bytesToDiscard := 0
switch buf[3] {
case socks.ATypIP4:
bytesToDiscard = net.IPv4len
case socks.ATypIP6:
bytesToDiscard = net.IPv6len
case socks.ATypDomain:
_, err := io.ReadFull(conn, buf[:1])
if err != nil {
return fmt.Errorf("proxy: failed to read domain length from SOCKS5 proxy at %v: %w", s.addr, err)
}
bytesToDiscard = int(buf[0])
default:
return fmt.Errorf("proxy: got unknown address type %v", strconv.Itoa(int(buf[3]))+" from SOCKS5 proxy at "+s.addr)
}
if cap(buf) < bytesToDiscard {
buf = make([]byte, bytesToDiscard)
} else {
buf = buf[:bytesToDiscard]
}
if _, err := io.ReadFull(conn, buf); err != nil {
return fmt.Errorf("proxy: failed to read address from SOCKS5 proxy at %v: %w", s.addr, err)
}
// Also need to discard the port number
if _, err := io.ReadFull(conn, buf[:2]); err != nil {
return fmt.Errorf("proxy: failed to read port from SOCKS5 proxy at %v, %w", s.addr, err)
}
return nil
}
// Handshake fast-tracks SOCKS initialization to get target address to connect.
func (s *Socks5) handshake(rw io.ReadWriter) (socks.Addr, error) {
// Read RFC 1928 for request and reply structure and sizes
buf := make([]byte, socks.MaxAddrLen)
// read VER, NMETHODS, METHODS
if _, err := io.ReadFull(rw, buf[:2]); err != nil {
return nil, err
}
nmethods := buf[1]
if _, err := io.ReadFull(rw, buf[:nmethods]); err != nil {
return nil, err
}
// write VER METHOD
if s.user != "" && s.password != "" {
_, err := rw.Write([]byte{Version, socks.AuthPassword})
if err != nil {
return nil, err
}
_, err = io.ReadFull(rw, buf[:2])
if err != nil {
return nil, err
}
// Get username
userLen := int(buf[1])
if userLen <= 0 {
rw.Write([]byte{1, 1})
return nil, fmt.Errorf("auth failed: wrong username length")
}
if _, err := io.ReadFull(rw, buf[:userLen]); err != nil {
return nil, fmt.Errorf("auth failed: cannot get username")
}
user := string(buf[:userLen])
// Get password
_, err = rw.Read(buf[:1])
if err != nil {
return nil, fmt.Errorf("auth failed: cannot get password len")
}
passLen := int(buf[0])
if passLen <= 0 {
rw.Write([]byte{1, 1})
return nil, fmt.Errorf("auth failed: wrong password length")
}
_, err = io.ReadFull(rw, buf[:passLen])
if err != nil {
return nil, fmt.Errorf("auth failed: cannot get password")
}
pass := string(buf[:passLen])
// Verify
if user != s.user || pass != s.password {
_, err = rw.Write([]byte{1, 1})
if err != nil {
return nil, err
}
return nil, fmt.Errorf("auth failed, authinfo: " + user + ":" + pass)
}
// Response auth state
_, err = rw.Write([]byte{1, 0})
if err != nil {
return nil, err
}
} else if _, err := rw.Write([]byte{Version, socks.AuthNone}); err != nil {
return nil, err
}
// read VER CMD RSV ATYP DST.ADDR DST.PORT
if _, err := io.ReadFull(rw, buf[:3]); err != nil {
return nil, err
}
cmd := buf[1]
addr, err := socks.ReadAddrBuf(rw, buf)
if err != nil {
return nil, err
}
switch cmd {
case socks.CmdConnect:
// wait for dial success
case socks.CmdUDPAssociate:
listenAddr := socks.ParseAddr(rw.(net.Conn).LocalAddr().String())
_, err = rw.Write(append([]byte{5, 0, 0}, listenAddr...)) // SOCKS v5, reply succeeded
if err != nil {
return nil, socks.Errors[7]
}
err = socks.Errors[9]
default:
return nil, socks.Errors[7]
}
return addr, err // skip VER, CMD, RSV fields
}
-78
View File
@@ -1,78 +0,0 @@
package ss
import (
"context"
"fmt"
"net"
"github.com/daeuniverse/outbound/dialer"
"github.com/daeuniverse/outbound/dialer/shadowsocks"
"github.com/daeuniverse/outbound/netproxy"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
_ "github.com/daeuniverse/outbound/protocol/shadowsocks"
_ "github.com/daeuniverse/outbound/protocol/shadowsocks_2022"
)
// Shadowsocks is a base shadowsocks struct
type Shadowsocks struct {
dialer netproxy.Dialer
}
func init() {
log.Trace("[shadowsocks] registering dialer")
plugin.RegisterDialer("ss", NewShadowsocksDialer)
}
func NewShadowsocksDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
dialer, _, err := shadowsocks.NewShadowsocksFromLink(
&dialer.ExtraOption{},
&plugin.Converter{
Dialer: d,
},
s,
)
if err != nil {
return nil, err
}
return &Shadowsocks{
dialer: dialer,
}, nil
}
// Addr returns forwarder's address.
func (s *Shadowsocks) Addr() string {
return ""
}
// Dial connects to the address addr on the network net via the infra.
func (s *Shadowsocks) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Shadowsocks) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
magicNetwork := netproxy.MagicNetwork{
Network: "tcp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(ctx, magicNetwork.Encode(), addr)
if err != nil {
return nil, fmt.Errorf("[shadowsocks]: dial to %s: %w", addr, err)
}
return plugin.NewFakeNetConn(rc), nil
}
// DialUDP connects to the given address via the infra.
func (s *Shadowsocks) DialUDP(network string) (plugin.FakeNetPacketConn, error) {
log.Info("[%s] dialing udp", "shadowsocks")
magicNetwork := netproxy.MagicNetwork{
Network: "udp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(context.TODO(), magicNetwork.Encode(), "")
if err != nil {
return nil, fmt.Errorf("[shadowsocks]: dial udp %w", err)
}
return plugin.NewFakeNetPacketConn(rc.(netproxy.PacketConn)), nil
}
-69
View File
@@ -1,69 +0,0 @@
package ssr
import (
"context"
"fmt"
"net"
"github.com/daeuniverse/outbound/dialer"
"github.com/daeuniverse/outbound/dialer/shadowsocksr"
"github.com/daeuniverse/outbound/netproxy"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
_ "github.com/daeuniverse/outbound/protocol/shadowsocks_stream"
)
// SSR struct.
type SSR struct {
dialer netproxy.Dialer
}
// Addr implements plugin.Dialer.
func (*SSR) Addr() string {
return ""
}
func init() {
log.Trace("[shadowsocksr] registering dialer")
plugin.RegisterDialer("ssr", NewSSRDialer)
}
// NewSSRDialer returns a ssr proxy dialer.
func NewSSRDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
dialer, _, err := shadowsocksr.NewShadowsocksR(
&dialer.ExtraOption{},
&plugin.Converter{
Dialer: d,
},
s,
)
if err != nil {
return nil, err
}
return &SSR{
dialer: dialer,
}, nil
}
// Dial connects to the address addr on the network net via the proxy.
func (s *SSR) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *SSR) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
magicNetwork := netproxy.MagicNetwork{
Network: "tcp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(ctx, magicNetwork.Encode(), addr)
if err != nil {
return nil, fmt.Errorf("[ssr]: dial to %s: %w", addr, err)
}
return plugin.NewFakeNetConn(rc), nil
}
// DialUDP connects to the given address via the proxy.
func (s *SSR) DialUDP(network string) (plugin.FakeNetPacketConn, error) {
return nil, fmt.Errorf("[ssr] udp not supported now")
}
-192
View File
@@ -1,192 +0,0 @@
package tcp
import (
"context"
"fmt"
"io"
"net"
"net/url"
"strings"
"time"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// Tcp is a base tcp struct.
type Tcp struct {
dialer plugin.Dialer
proxy plugin.Proxy
listenAddr string
nodeName string
target string
TcpListener net.Listener
}
func init() {
plugin.RegisterServer("tcp", NewTcpServer)
}
func NewTcp(s string, nodeName string, d plugin.Dialer, p plugin.Proxy) (*Tcp, error) {
u, err := url.Parse(s)
if err != nil {
log.Warn("parse err: %s", err)
return nil, err
}
addr := u.Host
h := &Tcp{
dialer: d,
proxy: p,
listenAddr: addr,
nodeName: nodeName,
target: u.Query().Get("target"),
}
return h, nil
}
// NewTcpDialer returns a tcp proxy dialer.
func NewTcpDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
return NewTcp(s, "", d, nil)
}
// NewTcpServer returns a tcp proxy server.
func NewTcpServer(s string, nodeName string, p plugin.Proxy) (plugin.Server, error) {
return NewTcp(s, nodeName, nil, p)
}
// ListenAndServe serves tcp requests.
func (s *Tcp) ListenAndServe() error {
//go s.ListenAndServeUDP()
return s.ListenAndServeTCP()
}
func (s *Tcp) ListenAddr() string {
return s.listenAddr
}
func (s *Tcp) NodeName() string {
return s.nodeName
}
// ListenAndServeTCP listen and serve on tcp port.
func (s *Tcp) ListenAndServeTCP() error {
l, err := net.Listen("tcp", s.listenAddr)
if err != nil {
log.Warn("[tcp] failed to listen on %s: %v", s.listenAddr, err)
return err
}
s.TcpListener = l
log.Trace("[tcp] listening TCP on %s", s.listenAddr)
for {
c, err := l.Accept()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
return nil
}
log.Debug("[tcp] failed to accept: %v", err)
continue
}
go s.Serve(c)
}
}
func (s *Tcp) Close() error {
if s.TcpListener == nil {
return nil
}
return s.TcpListener.Close()
}
// Serve serves a connection.
func (s *Tcp) Serve(c net.Conn) {
defer c.Close()
if c, ok := c.(*net.TCPConn); ok {
c.SetKeepAlive(true)
}
rc, dialer, err := s.proxy.Dial("tcp", s.target)
if err != nil {
log.Debug("[tcp] %s <-> %s, error in dial: %v", c.RemoteAddr(), dialer, err)
return
}
defer rc.Close()
log.Trace("[tcp] %s <-> %s", c.RemoteAddr(), dialer)
_, _, err = Relay(c, rc)
if err != nil {
if err, ok := err.(net.Error); ok && err.Timeout() {
return // ignore i/o timeout
}
log.Debug("[tcp] relay error: %v", err)
}
}
// Relay relays between left and right.
func Relay(left, right net.Conn) (int64, int64, error) {
type res struct {
N int64
Err error
}
ch := make(chan res)
go func() {
n, err := io.Copy(right, left)
right.SetDeadline(time.Now()) // wake up the other goroutine blocking on right
left.SetDeadline(time.Now()) // wake up the other goroutine blocking on left
ch <- res{n, err}
}()
n, err := io.Copy(left, right)
right.SetDeadline(time.Now()) // wake up the other goroutine blocking on right
left.SetDeadline(time.Now()) // wake up the other goroutine blocking on left
rs := <-ch
if err == nil {
err = rs.Err
}
return n, rs.N, err
}
// Addr returns forwarder's address.
func (s *Tcp) Addr() string {
if s.listenAddr == "" {
return s.dialer.Addr()
}
return s.listenAddr
}
// Dial connects to the address addr on the network net via the TCP proxy.
func (s *Tcp) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Tcp) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
log.Info("[tcp] dialing %s via %s", addr, s.listenAddr)
switch network {
case "tcp", "tcp6", "tcp4":
default:
return nil, fmt.Errorf("[tcp]: no support for connection type " + network)
}
c, err := s.dialer.DialContext(ctx, network, s.listenAddr)
if err != nil {
log.Debug("[tcp]: dial to %s error: %s", s.listenAddr, err)
return nil, err
}
return c, nil
}
// DialUDP connects to the given address via the proxy.
func (s *Tcp) DialUDP(network string) (pc plugin.FakeNetPacketConn, err error) {
//Not support
return nil, nil
}
-104
View File
@@ -1,104 +0,0 @@
package tls
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/url"
"strings"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// Tls is a base Tls struct
type Tls struct {
dialer plugin.Dialer
addr string
serverName string
skipVerify bool
tlsConfig *tls.Config
}
func init() {
log.Trace("[tls] registering dialer")
plugin.RegisterDialer("tls", NewTlsDialer)
}
// NewTls returns a Tls infra.
func NewTls(s string, d plugin.Dialer) (*Tls, error) {
u, err := url.Parse(s)
if err != nil {
return nil, fmt.Errorf("NewTls: %w", err)
}
t := &Tls{
dialer: d,
addr: u.Host,
}
query := u.Query()
t.serverName = query.Get("sni")
if t.serverName == "" {
t.serverName = query.Get("host")
}
if t.serverName == "" {
colonPos := strings.LastIndex(t.addr, ":")
if colonPos == -1 {
colonPos = len(t.addr)
}
t.serverName = t.addr[:colonPos]
}
// skipVerify
if query.Get("allowInsecure") == "true" || query.Get("allowInsecure") == "1" ||
query.Get("skipVerify") == "true" || query.Get("skipVerify") == "1" {
t.skipVerify = true
}
t.tlsConfig = &tls.Config{
ServerName: t.serverName,
InsecureSkipVerify: t.skipVerify,
}
return t, nil
}
func NewTlsDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
return NewTls(s, d)
}
// Addr returns forwarder's address.
func (s *Tls) Addr() string {
if s.addr == "" {
return s.dialer.Addr()
}
return s.addr
}
// Dial connects to the address addr on the network net via the infra.
func (s *Tls) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Tls) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
log.Info("[tls] dialing %s (sni=%s)", addr, s.serverName)
rc, err := s.dialer.DialContext(ctx, "tcp", addr)
if err != nil {
return nil, fmt.Errorf("[Tls]: dial to %s: %w", s.addr, err)
}
tlsConn := tls.Client(rc, s.tlsConfig)
if err := tlsConn.HandshakeContext(ctx); err != nil {
rc.Close()
return nil, err
}
return tlsConn, err
}
// DialUDP connects to the given address via the infra.
func (s *Tls) DialUDP(network string) (pc plugin.FakeNetPacketConn, err error) {
//TODO
return nil, nil
}
-82
View File
@@ -1,82 +0,0 @@
package trojan
import (
"context"
"fmt"
"net"
"github.com/daeuniverse/outbound/dialer"
"github.com/daeuniverse/outbound/dialer/trojan"
"github.com/daeuniverse/outbound/netproxy"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
_ "github.com/daeuniverse/outbound/protocol/trojanc"
)
// Trojan is a base trojan struct
type Trojan struct {
dialer netproxy.Dialer
}
func init() {
println("[DEBUG] trojan.init called")
log.Trace("[trojan] registering dialer")
plugin.RegisterDialer("trojan", NewTrojanDialer)
plugin.RegisterDialer("trojan-go", NewTrojanDialer)
}
func NewTrojanDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
dialer, _, err := trojan.NewTrojan(
&dialer.ExtraOption{
TlsImplementation: "tls",
},
&plugin.Converter{
Dialer: d,
},
s,
)
if err != nil {
return nil, err
}
return &Trojan{
dialer: dialer,
}, nil
}
// Addr returns forwarder's address.
func (s *Trojan) Addr() string {
return ""
}
// Dial connects to the address addr on the network net via the infra.
func (s *Trojan) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Trojan) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
magicNetwork := netproxy.MagicNetwork{
Network: "tcp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(ctx, magicNetwork.Encode(), addr)
if err != nil {
return nil, fmt.Errorf("[trojan]: dial to %s: %w", addr, err)
}
return plugin.NewFakeNetConn(rc), nil
}
// DialUDP connects to the given address via the infra.
func (s *Trojan) DialUDP(network string) (plugin.FakeNetPacketConn, error) {
log.Info("[%s] dialing udp", "trojan")
magicNetwork := netproxy.MagicNetwork{
Network: "udp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(context.TODO(), magicNetwork.Encode(), "")
if err != nil {
return nil, fmt.Errorf("[trojan]: dial udp %w", err)
}
return plugin.NewFakeNetPacketConn(rc.(netproxy.PacketConn)), nil
}
-98
View File
@@ -1,98 +0,0 @@
// from https://github.com/nadoo/glider/blob/master/proxy/trojan/trojan.go
// protocol spec:
// https://trojan-gfw.github.io/trojan/protocol
package trojanc
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"net"
"net/url"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/plugin/socks"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// Trojan is a base trojan struct
type Trojan struct {
dialer plugin.Dialer
addr string
pass [56]byte
}
func init() {
log.Trace("[trojanc] registering dialer")
plugin.RegisterDialer("trojanc", NewTrojancDialer)
}
// NewTrojanc returns a trojan-cleartext infra.
func NewTrojanc(s string, d plugin.Dialer) (*Trojan, error) {
u, err := url.Parse(s)
if err != nil {
return nil, fmt.Errorf("NewTrojanc: %w", err)
}
t := &Trojan{
dialer: d,
addr: u.Host,
}
// pass
hash := sha256.New224()
hash.Write([]byte(u.User.Username()))
hex.Encode(t.pass[:], hash.Sum(nil))
return t, nil
}
func NewTrojancDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
return NewTrojanc(s, d)
}
// Addr returns forwarder's address.
func (s *Trojan) Addr() string {
if s.addr == "" {
return s.dialer.Addr()
}
return s.addr
}
// Dial connects to the address addr on the network net via the infra.
func (s *Trojan) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Trojan) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
log.Info("[trojanc] dialing %s via %s", addr, s.addr)
rc, err := s.dialer.DialContext(ctx, "tcp", s.addr)
if err != nil {
return nil, fmt.Errorf("[trojan]: dial to %s: %w", s.addr, err)
}
var buf bytes.Buffer
buf.Write(s.pass[:])
buf.WriteString("\r\n")
cmd := socks.CmdConnect
if network == "udp" {
cmd = socks.CmdUDPAssociate
}
buf.WriteByte(byte(cmd))
buf.Write(socks.ParseAddr(addr))
buf.WriteString("\r\n")
_, err = rc.Write(buf.Bytes())
return rc, err
}
// DialUDP connects to the given address via the infra.
func (s *Trojan) DialUDP(network string) (pc plugin.FakeNetPacketConn, err error) {
//TODO
return nil, nil
}
-78
View File
@@ -1,78 +0,0 @@
package tuic
import (
"context"
"fmt"
"net"
"github.com/daeuniverse/outbound/dialer"
"github.com/daeuniverse/outbound/dialer/tuic"
"github.com/daeuniverse/outbound/netproxy"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
_ "github.com/daeuniverse/outbound/protocol/tuic"
)
// Tuic is a base tuic struct
type Tuic struct {
dialer netproxy.Dialer
}
func init() {
log.Info("[tuic] registering dialer")
plugin.RegisterDialer("tuic", NewTuicDialer)
}
func NewTuicDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
dialer, _, err := tuic.NewTuic(
&dialer.ExtraOption{},
&plugin.Converter{
Dialer: d,
},
s,
)
if err != nil {
return nil, err
}
return &Tuic{
dialer: dialer,
}, nil
}
// Addr returns forwarder's address.
func (s *Tuic) Addr() string {
return ""
}
// Dial connects to the address addr on the network net via the infra.
func (s *Tuic) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Tuic) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
magicNetwork := netproxy.MagicNetwork{
Network: "tcp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(ctx, magicNetwork.Encode(), addr)
if err != nil {
return nil, fmt.Errorf("[tuic]: dial to %s: %w", addr, err)
}
return plugin.NewFakeNetConn(rc), nil
}
// DialUDP connects to the given address via the infra.
func (s *Tuic) DialUDP(network string) (plugin.FakeNetPacketConn, error) {
log.Info("[%s] dialing udp", "tuic")
magicNetwork := netproxy.MagicNetwork{
Network: "udp",
Mark: plugin.ShouldSetMark(),
}
rc, err := s.dialer.DialContext(context.TODO(), magicNetwork.Encode(), "")
if err != nil {
return nil, fmt.Errorf("[tuic]: dial udp %w", err)
}
return plugin.NewFakeNetPacketConn(rc.(netproxy.PacketConn)), nil
}
-60
View File
@@ -1,60 +0,0 @@
package ws
import (
"bytes"
"github.com/gorilla/websocket"
"net"
"time"
)
type conn struct {
conn *websocket.Conn
readBuffer bytes.Buffer
}
func newConn(wsc *websocket.Conn) *conn {
return &conn{
conn: wsc,
}
}
func (c *conn) Read(b []byte) (n int, err error) {
if c.readBuffer.Len() > 0 {
return c.readBuffer.Read(b)
}
_, msg, err := c.conn.ReadMessage()
if err != nil {
return 0, err
}
n = copy(b, msg)
if n < len(msg) {
c.readBuffer.Write(msg[n:])
}
return n, nil
}
func (c *conn) Write(b []byte) (n int, err error) {
return len(b), c.conn.WriteMessage(websocket.BinaryMessage, b)
}
func (c *conn) Close() error {
return c.conn.Close()
}
func (c *conn) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *conn) RemoteAddr() net.Addr {
return c.conn.RemoteAddr()
}
func (c *conn) SetDeadline(t time.Time) error {
err := c.conn.SetReadDeadline(t)
if err != nil {
return err
}
return c.conn.SetWriteDeadline(t)
}
func (c *conn) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
func (c *conn) SetWriteDeadline(t time.Time) error {
return c.conn.SetWriteDeadline(t)
}
-95
View File
@@ -1,95 +0,0 @@
package ws
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"github.com/gorilla/websocket"
"github.com/v2rayA/v2rayA/pkg/plugin"
"github.com/v2rayA/v2rayA/pkg/util/log"
)
// Ws is a base Ws struct
type Ws struct {
dialer plugin.Dialer
addr string
wsAddr string
host string
path string
header http.Header
wsDialer *websocket.Dialer
}
func init() {
log.Trace("[ws] registering dialer")
plugin.RegisterDialer("ws", NewWsDialer)
}
// NewWs returns a Ws infra.
func NewWs(s string, d plugin.Dialer) (*Ws, error) {
u, err := url.Parse(s)
if err != nil {
return nil, fmt.Errorf("NewWs: %w", err)
}
t := &Ws{
dialer: d,
addr: u.Host,
}
query := u.Query()
t.host = query.Get("host")
if t.host == "" {
t.host = strings.Split(t.addr, ":")[0]
}
t.header = http.Header{}
t.header.Set("Host", t.host)
t.path = query.Get("path")
if t.path == "" {
t.path = "/"
}
t.wsAddr = u.Scheme + "://" + t.addr + t.path
t.wsDialer = &websocket.Dialer{
NetDial: d.Dial,
Subprotocols: []string{"binary"},
}
return t, nil
}
func NewWsDialer(s string, d plugin.Dialer) (plugin.Dialer, error) {
return NewWs(s, d)
}
// Addr returns forwarder's address.
func (s *Ws) Addr() string {
if s.addr == "" {
return s.dialer.Addr()
}
return s.addr
}
// Dial connects to the address addr on the network net via the infra.
func (s *Ws) Dial(network, addr string) (net.Conn, error) {
return s.DialContext(context.Background(), network, addr)
}
func (s *Ws) DialContext(ctx context.Context, network, addr string) (net.Conn, error) {
log.Info("[ws] dialing %s via %s (host=%s path=%s)", addr, s.wsAddr, s.host, s.path)
s.wsDialer.NetDialContext = s.dialer.DialContext
rc, _, err := s.wsDialer.DialContext(ctx, s.wsAddr, s.header)
if err != nil {
return nil, fmt.Errorf("[Ws]: dial to %s: %w", s.wsAddr, err)
}
return newConn(rc), err
}
// DialUDP connects to the given address via the infra.
func (s *Ws) DialUDP(network string) (pc plugin.FakeNetPacketConn, err error) {
//TODO
return nil, nil
}