mirror of
https://github.com/shtorm-7/sing-box-extended.git
synced 2026-11-27 03:40:08 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7c96d9d78 | ||
|
|
6a88b05569 | ||
|
|
1e294b1b30 | ||
|
|
8d993fdabb | ||
|
|
ab6db88db8 | ||
|
|
34dbf7656d | ||
|
|
7e84cf4b4f | ||
|
|
fb7abb4822 | ||
|
|
90b63d69b1 | ||
|
|
0528c742c8 | ||
|
|
9d1ecde082 | ||
|
|
f568f5125e | ||
|
|
cd2c18df96 |
@@ -1,83 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/common/srs"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common/json"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var flagRuleSetDecompileOutput string
|
||||
|
||||
const flagRuleSetDecompileDefaultOutput = "<file_name>.json"
|
||||
|
||||
var commandRuleSetDecompile = &cobra.Command{
|
||||
Use: "decompile [binary-path]",
|
||||
Short: "Decompile rule-set binary to json",
|
||||
Args: cobra.ExactArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := decompileRuleSet(args[0])
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
commandRuleSet.AddCommand(commandRuleSetDecompile)
|
||||
commandRuleSetDecompile.Flags().StringVarP(&flagRuleSetDecompileOutput, "output", "o", flagRuleSetDecompileDefaultOutput, "Output file")
|
||||
}
|
||||
|
||||
func decompileRuleSet(sourcePath string) error {
|
||||
var (
|
||||
reader io.Reader
|
||||
err error
|
||||
)
|
||||
if sourcePath == "stdin" {
|
||||
reader = os.Stdin
|
||||
} else {
|
||||
reader, err = os.Open(sourcePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
plainRuleSet, err := srs.Read(reader, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ruleSet := option.PlainRuleSetCompat{
|
||||
Version: C.RuleSetVersion1,
|
||||
Options: plainRuleSet,
|
||||
}
|
||||
var outputPath string
|
||||
if flagRuleSetDecompileOutput == flagRuleSetDecompileDefaultOutput {
|
||||
if strings.HasSuffix(sourcePath, ".srs") {
|
||||
outputPath = sourcePath[:len(sourcePath)-4] + ".json"
|
||||
} else {
|
||||
outputPath = sourcePath + ".json"
|
||||
}
|
||||
} else {
|
||||
outputPath = flagRuleSetDecompileOutput
|
||||
}
|
||||
outputFile, err := os.Create(outputPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
encoder := json.NewEncoder(outputFile)
|
||||
encoder.SetIndent("", " ")
|
||||
err = encoder.Encode(ruleSet)
|
||||
if err != nil {
|
||||
outputFile.Close()
|
||||
os.Remove(outputPath)
|
||||
return err
|
||||
}
|
||||
outputFile.Close()
|
||||
return nil
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
F "github.com/sagernet/sing/common/format"
|
||||
"github.com/sagernet/sing/common/json"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
@@ -22,8 +21,8 @@ import (
|
||||
var flagRuleSetMatchFormat string
|
||||
|
||||
var commandRuleSetMatch = &cobra.Command{
|
||||
Use: "match <rule-set path> <IP address/domain>",
|
||||
Short: "Check if an IP address or a domain matches the rule-set",
|
||||
Use: "match <rule-set path> <domain>",
|
||||
Short: "Check if a domain matches the rule-set",
|
||||
Args: cobra.ExactArgs(2),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := ruleSetMatch(args[0], args[1])
|
||||
@@ -75,20 +74,15 @@ func ruleSetMatch(sourcePath string, domain string) error {
|
||||
default:
|
||||
return E.New("unknown rule-set format: ", flagRuleSetMatchFormat)
|
||||
}
|
||||
ipAddress := M.ParseAddr(domain)
|
||||
var metadata adapter.InboundContext
|
||||
if ipAddress.IsValid() {
|
||||
metadata.Destination = M.SocksaddrFrom(ipAddress, 0)
|
||||
} else {
|
||||
metadata.Domain = domain
|
||||
}
|
||||
for i, ruleOptions := range plainRuleSet.Rules {
|
||||
var currentRule adapter.HeadlessRule
|
||||
currentRule, err = route.NewHeadlessRule(nil, ruleOptions)
|
||||
if err != nil {
|
||||
return E.Cause(err, "parse rule_set.rules.[", i, "]")
|
||||
}
|
||||
if currentRule.Match(&metadata) {
|
||||
if currentRule.Match(&adapter.InboundContext{
|
||||
Domain: domain,
|
||||
}) {
|
||||
println(F.ToString("match rules.[", i, "]: ", currentRule))
|
||||
}
|
||||
}
|
||||
|
||||
+8
-15
@@ -39,7 +39,7 @@ const (
|
||||
ruleItemFinal uint8 = 0xFF
|
||||
)
|
||||
|
||||
func Read(reader io.Reader, recover bool) (ruleSet option.PlainRuleSet, err error) {
|
||||
func Read(reader io.Reader, recovery bool) (ruleSet option.PlainRuleSet, err error) {
|
||||
var magicBytes [3]byte
|
||||
_, err = io.ReadFull(reader, magicBytes[:])
|
||||
if err != nil {
|
||||
@@ -68,7 +68,7 @@ func Read(reader io.Reader, recover bool) (ruleSet option.PlainRuleSet, err erro
|
||||
}
|
||||
ruleSet.Rules = make([]option.HeadlessRule, length)
|
||||
for i := uint64(0); i < length; i++ {
|
||||
ruleSet.Rules[i], err = readRule(bReader, recover)
|
||||
ruleSet.Rules[i], err = readRule(bReader, recovery)
|
||||
if err != nil {
|
||||
err = E.Cause(err, "read rule[", i, "]")
|
||||
return
|
||||
@@ -101,14 +101,10 @@ func Write(writer io.Writer, ruleSet option.PlainRuleSet) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = bWriter.Flush()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return zWriter.Close()
|
||||
}
|
||||
|
||||
func readRule(reader varbin.Reader, recover bool) (rule option.HeadlessRule, err error) {
|
||||
func readRule(reader varbin.Reader, recovery bool) (rule option.HeadlessRule, err error) {
|
||||
var ruleType uint8
|
||||
err = binary.Read(reader, binary.BigEndian, &ruleType)
|
||||
if err != nil {
|
||||
@@ -117,10 +113,10 @@ func readRule(reader varbin.Reader, recover bool) (rule option.HeadlessRule, err
|
||||
switch ruleType {
|
||||
case 0:
|
||||
rule.Type = C.RuleTypeDefault
|
||||
rule.DefaultOptions, err = readDefaultRule(reader, recover)
|
||||
rule.DefaultOptions, err = readDefaultRule(reader, recovery)
|
||||
case 1:
|
||||
rule.Type = C.RuleTypeLogical
|
||||
rule.LogicalOptions, err = readLogicalRule(reader, recover)
|
||||
rule.LogicalOptions, err = readLogicalRule(reader, recovery)
|
||||
default:
|
||||
err = E.New("unknown rule type: ", ruleType)
|
||||
}
|
||||
@@ -138,7 +134,7 @@ func writeRule(writer varbin.Writer, rule option.HeadlessRule) error {
|
||||
}
|
||||
}
|
||||
|
||||
func readDefaultRule(reader varbin.Reader, recover bool) (rule option.DefaultHeadlessRule, err error) {
|
||||
func readDefaultRule(reader varbin.Reader, recovery bool) (rule option.DefaultHeadlessRule, err error) {
|
||||
var lastItemType uint8
|
||||
for {
|
||||
var itemType uint8
|
||||
@@ -165,9 +161,6 @@ func readDefaultRule(reader varbin.Reader, recover bool) (rule option.DefaultHea
|
||||
return
|
||||
}
|
||||
rule.DomainMatcher = matcher
|
||||
if recover {
|
||||
rule.Domain, rule.DomainSuffix = matcher.Dump()
|
||||
}
|
||||
case ruleItemDomainKeyword:
|
||||
rule.DomainKeyword, err = readRuleItemString(reader)
|
||||
case ruleItemDomainRegex:
|
||||
@@ -177,7 +170,7 @@ func readDefaultRule(reader varbin.Reader, recover bool) (rule option.DefaultHea
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if recover {
|
||||
if recovery {
|
||||
rule.SourceIPCIDR = common.Map(rule.SourceIPSet.Prefixes(), netip.Prefix.String)
|
||||
}
|
||||
case ruleItemIPCIDR:
|
||||
@@ -185,7 +178,7 @@ func readDefaultRule(reader varbin.Reader, recover bool) (rule option.DefaultHea
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if recover {
|
||||
if recovery {
|
||||
rule.IPCIDR = common.Map(rule.IPSet.Prefixes(), netip.Prefix.String)
|
||||
}
|
||||
case ruleItemSourcePort:
|
||||
|
||||
+1
-7
@@ -2,17 +2,11 @@
|
||||
icon: material/alert-decagram
|
||||
---
|
||||
|
||||
#### 1.10.0-alpha.19
|
||||
|
||||
* Add `rule-set decompile` command
|
||||
* Add IP address support for `rule-set match` command
|
||||
* Fixes and improvements
|
||||
|
||||
#### 1.10.0-alpha.18
|
||||
|
||||
* Add new `inline` rule-set type **1**
|
||||
* Add auto reload support for local rule-set
|
||||
* Update fsnotify usages **2**
|
||||
* Improve fsnotify usages **2**
|
||||
* Fixes and improvements
|
||||
|
||||
**1**:
|
||||
|
||||
@@ -20,17 +20,13 @@ import (
|
||||
func (c *CommandClient) handleConnectionsConn(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
reader := bufio.NewReader(conn)
|
||||
var (
|
||||
rawConnections []Connection
|
||||
connections Connections
|
||||
)
|
||||
var connections Connections
|
||||
for {
|
||||
err := varbin.Read(reader, binary.BigEndian, &rawConnections)
|
||||
err := varbin.Read(reader, binary.BigEndian, &connections.connections)
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
connections.input = rawConnections
|
||||
c.handler.WriteConnections(&connections)
|
||||
}
|
||||
}
|
||||
@@ -97,32 +93,33 @@ const (
|
||||
)
|
||||
|
||||
type Connections struct {
|
||||
input []Connection
|
||||
filtered []Connection
|
||||
connections []Connection
|
||||
filteredConnections []Connection
|
||||
outConnections *[]Connection
|
||||
}
|
||||
|
||||
func (c *Connections) FilterState(state int32) {
|
||||
c.filtered = c.filtered[:0]
|
||||
c.filteredConnections = c.filteredConnections[:0]
|
||||
switch state {
|
||||
case ConnectionStateAll:
|
||||
c.filtered = append(c.filtered, c.input...)
|
||||
c.filteredConnections = append(c.filteredConnections, c.connections...)
|
||||
case ConnectionStateActive:
|
||||
for _, connection := range c.input {
|
||||
for _, connection := range c.connections {
|
||||
if connection.ClosedAt == 0 {
|
||||
c.filtered = append(c.filtered, connection)
|
||||
c.filteredConnections = append(c.filteredConnections, connection)
|
||||
}
|
||||
}
|
||||
case ConnectionStateClosed:
|
||||
for _, connection := range c.input {
|
||||
for _, connection := range c.connections {
|
||||
if connection.ClosedAt != 0 {
|
||||
c.filtered = append(c.filtered, connection)
|
||||
c.filteredConnections = append(c.filteredConnections, connection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Connections) SortByDate() {
|
||||
slices.SortStableFunc(c.filtered, func(x, y Connection) int {
|
||||
slices.SortStableFunc(c.filteredConnections, func(x, y Connection) int {
|
||||
if x.CreatedAt < y.CreatedAt {
|
||||
return 1
|
||||
} else if x.CreatedAt > y.CreatedAt {
|
||||
@@ -134,7 +131,7 @@ func (c *Connections) SortByDate() {
|
||||
}
|
||||
|
||||
func (c *Connections) SortByTraffic() {
|
||||
slices.SortStableFunc(c.filtered, func(x, y Connection) int {
|
||||
slices.SortStableFunc(c.filteredConnections, func(x, y Connection) int {
|
||||
xTraffic := x.Uplink + x.Downlink
|
||||
yTraffic := y.Uplink + y.Downlink
|
||||
if xTraffic < yTraffic {
|
||||
@@ -148,7 +145,7 @@ func (c *Connections) SortByTraffic() {
|
||||
}
|
||||
|
||||
func (c *Connections) SortByTrafficTotal() {
|
||||
slices.SortStableFunc(c.filtered, func(x, y Connection) int {
|
||||
slices.SortStableFunc(c.filteredConnections, func(x, y Connection) int {
|
||||
xTraffic := x.UplinkTotal + x.DownlinkTotal
|
||||
yTraffic := y.UplinkTotal + y.DownlinkTotal
|
||||
if xTraffic < yTraffic {
|
||||
@@ -162,7 +159,7 @@ func (c *Connections) SortByTrafficTotal() {
|
||||
}
|
||||
|
||||
func (c *Connections) Iterator() ConnectionIterator {
|
||||
return newPtrIterator(c.filtered)
|
||||
return newPtrIterator(c.filteredConnections)
|
||||
}
|
||||
|
||||
type Connection struct {
|
||||
|
||||
@@ -26,15 +26,15 @@ require (
|
||||
github.com/sagernet/gvisor v0.0.0-20240428053021-e691de28565f
|
||||
github.com/sagernet/quic-go v0.45.1-beta.2
|
||||
github.com/sagernet/reality v0.0.0-20230406110435-ee17307e7691
|
||||
github.com/sagernet/sing v0.5.0-alpha.12
|
||||
github.com/sagernet/sing v0.5.0-alpha.11.0.20240625144910-6bd878184516
|
||||
github.com/sagernet/sing-dns v0.3.0-beta.10
|
||||
github.com/sagernet/sing-mux v0.2.0
|
||||
github.com/sagernet/sing-quic v0.2.0-beta.12
|
||||
github.com/sagernet/sing-shadowsocks v0.2.6
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.0
|
||||
github.com/sagernet/sing-shadowtls v0.1.4
|
||||
github.com/sagernet/sing-tun v0.4.0-beta.13.0.20240703164908-1f043289199d
|
||||
github.com/sagernet/sing-vmess v0.1.11
|
||||
github.com/sagernet/sing-tun v0.4.0-beta.13.0.20240626030247-7c4975c41279
|
||||
github.com/sagernet/sing-vmess v0.1.8
|
||||
github.com/sagernet/smux v0.0.0-20231208180855-7041f6ea79e7
|
||||
github.com/sagernet/tfo-go v0.0.0-20231209031829-7b5343ac1dc6
|
||||
github.com/sagernet/utls v1.5.4
|
||||
|
||||
@@ -115,8 +115,8 @@ github.com/sagernet/quic-go v0.45.1-beta.2/go.mod h1:+N3FqM9DAzOWfe64uxXuBejVJwX
|
||||
github.com/sagernet/reality v0.0.0-20230406110435-ee17307e7691 h1:5Th31OC6yj8byLGkEnIYp6grlXfo1QYUfiYFGjewIdc=
|
||||
github.com/sagernet/reality v0.0.0-20230406110435-ee17307e7691/go.mod h1:B8lp4WkQ1PwNnrVMM6KyuFR20pU8jYBD+A4EhJovEXU=
|
||||
github.com/sagernet/sing v0.2.18/go.mod h1:OL6k2F0vHmEzXz2KW19qQzu172FDgSbUSODylighuVo=
|
||||
github.com/sagernet/sing v0.5.0-alpha.12 h1:pjffG3SUpuF9PLDCqPO2fOAUozXItIBmnMVTKQ/QMhM=
|
||||
github.com/sagernet/sing v0.5.0-alpha.12/go.mod h1:ARkL0gM13/Iv5VCZmci/NuoOlePoIsW0m7BWfln/Hak=
|
||||
github.com/sagernet/sing v0.5.0-alpha.11.0.20240625144910-6bd878184516 h1:C5NYqSEQC2CcILDFhT31iZe5Kp5hFNEtdS9mnNWyW5c=
|
||||
github.com/sagernet/sing v0.5.0-alpha.11.0.20240625144910-6bd878184516/go.mod h1:ARkL0gM13/Iv5VCZmci/NuoOlePoIsW0m7BWfln/Hak=
|
||||
github.com/sagernet/sing-dns v0.3.0-beta.10 h1:Js61EjQXVpcu2VDegWEQTH1isCcVwJju8WEHYgG4tQ0=
|
||||
github.com/sagernet/sing-dns v0.3.0-beta.10/go.mod h1:nXE6EYMXahB5DV3AcXYbFfuorqF7tbQ86kxweSxRKM4=
|
||||
github.com/sagernet/sing-mux v0.2.0 h1:4C+vd8HztJCWNYfufvgL49xaOoOHXty2+EAjnzN3IYo=
|
||||
@@ -129,10 +129,10 @@ github.com/sagernet/sing-shadowsocks2 v0.2.0 h1:wpZNs6wKnR7mh1wV9OHwOyUr21VkS3wK
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.0/go.mod h1:RnXS0lExcDAovvDeniJ4IKa2IuChrdipolPYWBv9hWQ=
|
||||
github.com/sagernet/sing-shadowtls v0.1.4 h1:aTgBSJEgnumzFenPvc+kbD9/W0PywzWevnVpEx6Tw3k=
|
||||
github.com/sagernet/sing-shadowtls v0.1.4/go.mod h1:F8NBgsY5YN2beQavdgdm1DPlhaKQlaL6lpDdcBglGK4=
|
||||
github.com/sagernet/sing-tun v0.4.0-beta.13.0.20240703164908-1f043289199d h1:2nBM9W9fOCM45hjlu1Fh9qyzBCgKEkq+SOuRCbCCs7c=
|
||||
github.com/sagernet/sing-tun v0.4.0-beta.13.0.20240703164908-1f043289199d/go.mod h1:81JwnnYw8X9W9XvmZetSTTiPgIE3SbAbnc+EHKwPJ5U=
|
||||
github.com/sagernet/sing-vmess v0.1.11 h1:Kq20MJOBrZzxyHko+/fPHuTszYxe41ClbiNt0TTaqP4=
|
||||
github.com/sagernet/sing-vmess v0.1.11/go.mod h1:luTSsfyBGAc9VhtCqwjR+dt1QgqBhuYBCONB/POhF8I=
|
||||
github.com/sagernet/sing-tun v0.4.0-beta.13.0.20240626030247-7c4975c41279 h1:pkvZfS3PVdSJt30pbJIvYRIiyetwZ3zbxlAwMEetDDU=
|
||||
github.com/sagernet/sing-tun v0.4.0-beta.13.0.20240626030247-7c4975c41279/go.mod h1:81JwnnYw8X9W9XvmZetSTTiPgIE3SbAbnc+EHKwPJ5U=
|
||||
github.com/sagernet/sing-vmess v0.1.8 h1:XVWad1RpTy9b5tPxdm5MCU8cGfrTGdR8qCq6HV2aCNc=
|
||||
github.com/sagernet/sing-vmess v0.1.8/go.mod h1:vhx32UNzTDUkNwOyIjcZQohre1CaytquC5mPplId8uA=
|
||||
github.com/sagernet/smux v0.0.0-20231208180855-7041f6ea79e7 h1:DImB4lELfQhplLTxeq2z31Fpv8CQqqrUwTbrIRumZqQ=
|
||||
github.com/sagernet/smux v0.0.0-20231208180855-7041f6ea79e7/go.mod h1:FP9X2xjT/Az1EsG/orYYoC+5MojWnuI7hrffz8fGwwo=
|
||||
github.com/sagernet/tfo-go v0.0.0-20231209031829-7b5343ac1dc6 h1:z3SJQhVyU63FT26Wn/UByW6b7q8QKB0ZkPqsyqcz2PI=
|
||||
|
||||
+1
-1
@@ -356,7 +356,7 @@ func (t *Tun) PostStart() error {
|
||||
}
|
||||
t.routeExcludeAddressSet = append(t.routeExcludeAddressSet, ipSets...)
|
||||
}
|
||||
monitor.Start("initialize auto-redirect")
|
||||
monitor.Start("initiating auto-redirect")
|
||||
err := t.autoRedirect.Start()
|
||||
monitor.Finish()
|
||||
if err != nil {
|
||||
|
||||
+1
-1
@@ -13,9 +13,9 @@ import (
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-box/transport/v2ray"
|
||||
"github.com/sagernet/sing-box/transport/vless"
|
||||
"github.com/sagernet/sing-vmess"
|
||||
"github.com/sagernet/sing-vmess/packetaddr"
|
||||
"github.com/sagernet/sing-vmess/vless"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/auth"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
|
||||
+1
-1
@@ -12,8 +12,8 @@ import (
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-box/transport/v2ray"
|
||||
"github.com/sagernet/sing-box/transport/vless"
|
||||
"github.com/sagernet/sing-vmess/packetaddr"
|
||||
"github.com/sagernet/sing-vmess/vless"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
|
||||
@@ -100,7 +100,7 @@ func (c *Client) DialContext(ctx context.Context) (net.Conn, error) {
|
||||
conn.setup(nil, err)
|
||||
} else if response.StatusCode != 200 {
|
||||
response.Body.Close()
|
||||
conn.setup(nil, E.New("v2ray-grpc: unexpected status: ", response.Status))
|
||||
conn.setup(nil, E.New("unexpected status: ", response.Status))
|
||||
} else {
|
||||
conn.setup(response.Body, nil)
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ func (c *Client) dialHTTP2(ctx context.Context) (net.Conn, error) {
|
||||
conn.Setup(nil, err)
|
||||
} else if response.StatusCode != 200 {
|
||||
response.Body.Close()
|
||||
conn.Setup(nil, E.New("v2ray-http: unexpected status: ", response.Status))
|
||||
conn.Setup(nil, E.New("unexpected status: ", response.Status))
|
||||
} else {
|
||||
conn.Setup(response.Body, nil)
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func (c *HTTPConn) Read(b []byte) (n int, err error) {
|
||||
return 0, E.Cause(err, "read response")
|
||||
}
|
||||
if response.StatusCode != 200 {
|
||||
return 0, E.New("v2ray-http: unexpected status: ", response.Status)
|
||||
return 0, E.New("unexpected status: ", response.Status)
|
||||
}
|
||||
if cacheLen := reader.Buffered(); cacheLen > 0 {
|
||||
c.responseCache = buf.NewSize(cacheLen)
|
||||
|
||||
@@ -104,7 +104,7 @@ func (c *Client) DialContext(ctx context.Context) (net.Conn, error) {
|
||||
if response.StatusCode != 101 ||
|
||||
!strings.EqualFold(response.Header.Get("Connection"), "upgrade") ||
|
||||
!strings.EqualFold(response.Header.Get("Upgrade"), "websocket") {
|
||||
return nil, E.New("v2ray-http-upgrade: unexpected status: ", response.Status)
|
||||
return nil, E.New("unexpected status: ", response.Status)
|
||||
}
|
||||
if bufReader.Buffered() > 0 {
|
||||
buffer := buf.NewSize(bufReader.Buffered())
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
package vless
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing-vmess"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
key [16]byte
|
||||
flow string
|
||||
logger logger.Logger
|
||||
}
|
||||
|
||||
func NewClient(userId string, flow string, logger logger.Logger) (*Client, error) {
|
||||
user := uuid.FromStringOrNil(userId)
|
||||
if user == uuid.Nil {
|
||||
user = uuid.NewV5(user, userId)
|
||||
}
|
||||
switch flow {
|
||||
case "", "xtls-rprx-vision":
|
||||
default:
|
||||
return nil, E.New("unsupported flow: " + flow)
|
||||
}
|
||||
return &Client{user, flow, logger}, nil
|
||||
}
|
||||
|
||||
func (c *Client) prepareConn(conn net.Conn, tlsConn net.Conn) (net.Conn, error) {
|
||||
if c.flow == FlowVision {
|
||||
protocolConn, err := NewVisionConn(conn, tlsConn, c.key, c.logger)
|
||||
if err != nil {
|
||||
return nil, E.Cause(err, "initialize vision")
|
||||
}
|
||||
conn = protocolConn
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (c *Client) DialConn(conn net.Conn, destination M.Socksaddr) (net.Conn, error) {
|
||||
remoteConn := NewConn(conn, c.key, vmess.CommandTCP, destination, c.flow)
|
||||
protocolConn, err := c.prepareConn(remoteConn, conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return protocolConn, common.Error(remoteConn.Write(nil))
|
||||
}
|
||||
|
||||
func (c *Client) DialEarlyConn(conn net.Conn, destination M.Socksaddr) (net.Conn, error) {
|
||||
return c.prepareConn(NewConn(conn, c.key, vmess.CommandTCP, destination, c.flow), conn)
|
||||
}
|
||||
|
||||
func (c *Client) DialPacketConn(conn net.Conn, destination M.Socksaddr) (*PacketConn, error) {
|
||||
serverConn := &PacketConn{Conn: conn, key: c.key, destination: destination, flow: c.flow}
|
||||
return serverConn, common.Error(serverConn.Write(nil))
|
||||
}
|
||||
|
||||
func (c *Client) DialEarlyPacketConn(conn net.Conn, destination M.Socksaddr) (*PacketConn, error) {
|
||||
return &PacketConn{Conn: conn, key: c.key, destination: destination, flow: c.flow}, nil
|
||||
}
|
||||
|
||||
func (c *Client) DialXUDPPacketConn(conn net.Conn, destination M.Socksaddr) (vmess.PacketConn, error) {
|
||||
remoteConn := NewConn(conn, c.key, vmess.CommandTCP, destination, c.flow)
|
||||
protocolConn, err := c.prepareConn(remoteConn, conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return vmess.NewXUDPConn(protocolConn, destination), common.Error(remoteConn.Write(nil))
|
||||
}
|
||||
|
||||
func (c *Client) DialEarlyXUDPPacketConn(conn net.Conn, destination M.Socksaddr) (vmess.PacketConn, error) {
|
||||
remoteConn := NewConn(conn, c.key, vmess.CommandMux, destination, c.flow)
|
||||
protocolConn, err := c.prepareConn(remoteConn, conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return vmess.NewXUDPConn(protocolConn, destination), common.Error(remoteConn.Write(nil))
|
||||
}
|
||||
|
||||
var (
|
||||
_ N.EarlyConn = (*Conn)(nil)
|
||||
_ N.VectorisedWriter = (*Conn)(nil)
|
||||
)
|
||||
|
||||
type Conn struct {
|
||||
N.ExtendedConn
|
||||
writer N.VectorisedWriter
|
||||
request Request
|
||||
requestWritten bool
|
||||
responseRead bool
|
||||
}
|
||||
|
||||
func NewConn(conn net.Conn, uuid [16]byte, command byte, destination M.Socksaddr, flow string) *Conn {
|
||||
return &Conn{
|
||||
ExtendedConn: bufio.NewExtendedConn(conn),
|
||||
writer: bufio.NewVectorisedWriter(conn),
|
||||
request: Request{
|
||||
UUID: uuid,
|
||||
Command: command,
|
||||
Destination: destination,
|
||||
Flow: flow,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) Read(b []byte) (n int, err error) {
|
||||
if !c.responseRead {
|
||||
err = ReadResponse(c.ExtendedConn)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.responseRead = true
|
||||
}
|
||||
return c.ExtendedConn.Read(b)
|
||||
}
|
||||
|
||||
func (c *Conn) ReadBuffer(buffer *buf.Buffer) error {
|
||||
if !c.responseRead {
|
||||
err := ReadResponse(c.ExtendedConn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.responseRead = true
|
||||
}
|
||||
return c.ExtendedConn.ReadBuffer(buffer)
|
||||
}
|
||||
|
||||
func (c *Conn) Write(b []byte) (n int, err error) {
|
||||
if !c.requestWritten {
|
||||
err = WriteRequest(c.ExtendedConn, c.request, b)
|
||||
if err == nil {
|
||||
n = len(b)
|
||||
}
|
||||
c.requestWritten = true
|
||||
return
|
||||
}
|
||||
return c.ExtendedConn.Write(b)
|
||||
}
|
||||
|
||||
func (c *Conn) WriteBuffer(buffer *buf.Buffer) error {
|
||||
if !c.requestWritten {
|
||||
err := EncodeRequest(c.request, buf.With(buffer.ExtendHeader(RequestLen(c.request))))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.requestWritten = true
|
||||
}
|
||||
return c.ExtendedConn.WriteBuffer(buffer)
|
||||
}
|
||||
|
||||
func (c *Conn) WriteVectorised(buffers []*buf.Buffer) error {
|
||||
if !c.requestWritten {
|
||||
buffer := buf.NewSize(RequestLen(c.request))
|
||||
err := EncodeRequest(c.request, buffer)
|
||||
if err != nil {
|
||||
buffer.Release()
|
||||
return err
|
||||
}
|
||||
c.requestWritten = true
|
||||
return c.writer.WriteVectorised(append([]*buf.Buffer{buffer}, buffers...))
|
||||
}
|
||||
return c.writer.WriteVectorised(buffers)
|
||||
}
|
||||
|
||||
func (c *Conn) ReaderReplaceable() bool {
|
||||
return c.responseRead
|
||||
}
|
||||
|
||||
func (c *Conn) WriterReplaceable() bool {
|
||||
return c.requestWritten
|
||||
}
|
||||
|
||||
func (c *Conn) NeedHandshake() bool {
|
||||
return !c.requestWritten
|
||||
}
|
||||
|
||||
func (c *Conn) FrontHeadroom() int {
|
||||
if c.requestWritten {
|
||||
return 0
|
||||
}
|
||||
return RequestLen(c.request)
|
||||
}
|
||||
|
||||
func (c *Conn) Upstream() any {
|
||||
return c.ExtendedConn
|
||||
}
|
||||
|
||||
type PacketConn struct {
|
||||
net.Conn
|
||||
access sync.Mutex
|
||||
key [16]byte
|
||||
destination M.Socksaddr
|
||||
flow string
|
||||
requestWritten bool
|
||||
responseRead bool
|
||||
}
|
||||
|
||||
func (c *PacketConn) Read(b []byte) (n int, err error) {
|
||||
if !c.responseRead {
|
||||
err = ReadResponse(c.Conn)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.responseRead = true
|
||||
}
|
||||
var length uint16
|
||||
err = binary.Read(c.Conn, binary.BigEndian, &length)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if cap(b) < int(length) {
|
||||
return 0, io.ErrShortBuffer
|
||||
}
|
||||
return io.ReadFull(c.Conn, b[:length])
|
||||
}
|
||||
|
||||
func (c *PacketConn) Write(b []byte) (n int, err error) {
|
||||
if !c.requestWritten {
|
||||
c.access.Lock()
|
||||
if c.requestWritten {
|
||||
c.access.Unlock()
|
||||
} else {
|
||||
err = WritePacketRequest(c.Conn, Request{c.key, vmess.CommandUDP, c.destination, c.flow}, nil)
|
||||
if err == nil {
|
||||
n = len(b)
|
||||
}
|
||||
c.requestWritten = true
|
||||
c.access.Unlock()
|
||||
}
|
||||
}
|
||||
err = binary.Write(c.Conn, binary.BigEndian, uint16(len(b)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return c.Conn.Write(b)
|
||||
}
|
||||
|
||||
func (c *PacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||
defer buffer.Release()
|
||||
dataLen := buffer.Len()
|
||||
binary.BigEndian.PutUint16(buffer.ExtendHeader(2), uint16(dataLen))
|
||||
if !c.requestWritten {
|
||||
c.access.Lock()
|
||||
if c.requestWritten {
|
||||
c.access.Unlock()
|
||||
} else {
|
||||
err := WritePacketRequest(c.Conn, Request{c.key, vmess.CommandUDP, c.destination, c.flow}, buffer.Bytes())
|
||||
c.requestWritten = true
|
||||
c.access.Unlock()
|
||||
return err
|
||||
}
|
||||
}
|
||||
return common.Error(c.Conn.Write(buffer.Bytes()))
|
||||
}
|
||||
|
||||
func (c *PacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||
n, err = c.Read(p)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if c.destination.IsFqdn() {
|
||||
addr = c.destination
|
||||
} else {
|
||||
addr = c.destination.UDPAddr()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *PacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||
return c.Write(p)
|
||||
}
|
||||
|
||||
func (c *PacketConn) FrontHeadroom() int {
|
||||
return 2
|
||||
}
|
||||
|
||||
func (c *PacketConn) NeedAdditionalReadDeadline() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *PacketConn) Upstream() any {
|
||||
return c.Conn
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package vless
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
)
|
||||
|
||||
var (
|
||||
tls13SupportedVersions = []byte{0x00, 0x2b, 0x00, 0x02, 0x03, 0x04}
|
||||
tlsClientHandShakeStart = []byte{0x16, 0x03}
|
||||
tlsServerHandShakeStart = []byte{0x16, 0x03, 0x03}
|
||||
tlsApplicationDataStart = []byte{0x17, 0x03, 0x03}
|
||||
)
|
||||
|
||||
const (
|
||||
commandPaddingContinue byte = iota
|
||||
commandPaddingEnd
|
||||
commandPaddingDirect
|
||||
)
|
||||
|
||||
var tls13CipherSuiteDic = map[uint16]string{
|
||||
0x1301: "TLS_AES_128_GCM_SHA256",
|
||||
0x1302: "TLS_AES_256_GCM_SHA384",
|
||||
0x1303: "TLS_CHACHA20_POLY1305_SHA256",
|
||||
0x1304: "TLS_AES_128_CCM_SHA256",
|
||||
0x1305: "TLS_AES_128_CCM_8_SHA256",
|
||||
}
|
||||
|
||||
func reshapeBuffer(b []byte) []*buf.Buffer {
|
||||
const bufferLimit = 8192 - 21
|
||||
if len(b) < bufferLimit {
|
||||
return []*buf.Buffer{buf.As(b)}
|
||||
}
|
||||
index := int32(bytes.LastIndex(b, tlsApplicationDataStart))
|
||||
if index <= 0 {
|
||||
index = 8192 / 2
|
||||
}
|
||||
return []*buf.Buffer{buf.As(b[:index]), buf.As(b[index:])}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package vless
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
"github.com/sagernet/sing-vmess"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/common/rw"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
)
|
||||
|
||||
const (
|
||||
Version = 0
|
||||
FlowVision = "xtls-rprx-vision"
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
UUID [16]byte
|
||||
Command byte
|
||||
Destination M.Socksaddr
|
||||
Flow string
|
||||
}
|
||||
|
||||
func ReadRequest(reader io.Reader) (*Request, error) {
|
||||
var request Request
|
||||
|
||||
var version uint8
|
||||
err := binary.Read(reader, binary.BigEndian, &version)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if version != Version {
|
||||
return nil, E.New("unknown version: ", version)
|
||||
}
|
||||
|
||||
_, err = io.ReadFull(reader, request.UUID[:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var addonsLen uint8
|
||||
err = binary.Read(reader, binary.BigEndian, &addonsLen)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if addonsLen > 0 {
|
||||
addonsBytes := make([]byte, addonsLen)
|
||||
_, err = io.ReadFull(reader, addonsBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
addons, err := readAddons(bytes.NewReader(addonsBytes))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
request.Flow = addons.Flow
|
||||
}
|
||||
|
||||
err = binary.Read(reader, binary.BigEndian, &request.Command)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if request.Command != vmess.CommandMux {
|
||||
request.Destination, err = vmess.AddressSerializer.ReadAddrPort(reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &request, nil
|
||||
}
|
||||
|
||||
type Addons struct {
|
||||
Flow string
|
||||
Seed string
|
||||
}
|
||||
|
||||
func readAddons(reader varbin.Reader) (*Addons, error) {
|
||||
protoHeader, err := reader.ReadByte()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if protoHeader != 10 {
|
||||
return nil, E.New("unknown protobuf message header: ", protoHeader)
|
||||
}
|
||||
|
||||
var addons Addons
|
||||
|
||||
flowLen, err := binary.ReadUvarint(reader)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return &addons, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
flowBytes := make([]byte, flowLen)
|
||||
_, err = io.ReadFull(reader, flowBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addons.Flow = string(flowBytes)
|
||||
|
||||
seedLen, err := binary.ReadUvarint(reader)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return &addons, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
seedBytes := make([]byte, seedLen)
|
||||
_, err = io.ReadFull(reader, seedBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
addons.Seed = string(seedBytes)
|
||||
|
||||
return &addons, nil
|
||||
}
|
||||
|
||||
func WriteRequest(writer io.Writer, request Request, payload []byte) error {
|
||||
var requestLen int
|
||||
requestLen += 1 // version
|
||||
requestLen += 16 // uuid
|
||||
requestLen += 1 // protobuf length
|
||||
|
||||
var addonsLen int
|
||||
if request.Flow != "" {
|
||||
addonsLen += 1 // protobuf header
|
||||
addonsLen += varbin.UvarintLen(uint64(len(request.Flow)))
|
||||
addonsLen += len(request.Flow)
|
||||
requestLen += addonsLen
|
||||
}
|
||||
requestLen += 1 // command
|
||||
if request.Command != vmess.CommandMux {
|
||||
requestLen += vmess.AddressSerializer.AddrPortLen(request.Destination)
|
||||
}
|
||||
requestLen += len(payload)
|
||||
buffer := buf.NewSize(requestLen)
|
||||
defer buffer.Release()
|
||||
common.Must(
|
||||
buffer.WriteByte(Version),
|
||||
common.Error(buffer.Write(request.UUID[:])),
|
||||
buffer.WriteByte(byte(addonsLen)),
|
||||
)
|
||||
if addonsLen > 0 {
|
||||
common.Must(buffer.WriteByte(10))
|
||||
binary.PutUvarint(buffer.Extend(varbin.UvarintLen(uint64(len(request.Flow)))), uint64(len(request.Flow)))
|
||||
common.Must(common.Error(buffer.WriteString(request.Flow)))
|
||||
}
|
||||
common.Must(
|
||||
buffer.WriteByte(request.Command),
|
||||
)
|
||||
|
||||
if request.Command != vmess.CommandMux {
|
||||
err := vmess.AddressSerializer.WriteAddrPort(buffer, request.Destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
common.Must1(buffer.Write(payload))
|
||||
return common.Error(writer.Write(buffer.Bytes()))
|
||||
}
|
||||
|
||||
func EncodeRequest(request Request, buffer *buf.Buffer) error {
|
||||
var requestLen int
|
||||
requestLen += 1 // version
|
||||
requestLen += 16 // uuid
|
||||
requestLen += 1 // protobuf length
|
||||
|
||||
var addonsLen int
|
||||
if request.Flow != "" {
|
||||
addonsLen += 1 // protobuf header
|
||||
addonsLen += varbin.UvarintLen(uint64(len(request.Flow)))
|
||||
addonsLen += len(request.Flow)
|
||||
requestLen += addonsLen
|
||||
}
|
||||
requestLen += 1 // command
|
||||
if request.Command != vmess.CommandMux {
|
||||
requestLen += vmess.AddressSerializer.AddrPortLen(request.Destination)
|
||||
}
|
||||
common.Must(
|
||||
buffer.WriteByte(Version),
|
||||
common.Error(buffer.Write(request.UUID[:])),
|
||||
buffer.WriteByte(byte(addonsLen)),
|
||||
)
|
||||
if addonsLen > 0 {
|
||||
common.Must(buffer.WriteByte(10))
|
||||
binary.PutUvarint(buffer.Extend(varbin.UvarintLen(uint64(len(request.Flow)))), uint64(len(request.Flow)))
|
||||
common.Must(common.Error(buffer.WriteString(request.Flow)))
|
||||
}
|
||||
common.Must(
|
||||
buffer.WriteByte(request.Command),
|
||||
)
|
||||
|
||||
if request.Command != vmess.CommandMux {
|
||||
err := vmess.AddressSerializer.WriteAddrPort(buffer, request.Destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RequestLen(request Request) int {
|
||||
var requestLen int
|
||||
requestLen += 1 // version
|
||||
requestLen += 16 // uuid
|
||||
requestLen += 1 // protobuf length
|
||||
|
||||
var addonsLen int
|
||||
if request.Flow != "" {
|
||||
addonsLen += 1 // protobuf header
|
||||
addonsLen += varbin.UvarintLen(uint64(len(request.Flow)))
|
||||
addonsLen += len(request.Flow)
|
||||
requestLen += addonsLen
|
||||
}
|
||||
requestLen += 1 // command
|
||||
if request.Command != vmess.CommandMux {
|
||||
requestLen += vmess.AddressSerializer.AddrPortLen(request.Destination)
|
||||
}
|
||||
return requestLen
|
||||
}
|
||||
|
||||
func WritePacketRequest(writer io.Writer, request Request, payload []byte) error {
|
||||
var requestLen int
|
||||
requestLen += 1 // version
|
||||
requestLen += 16 // uuid
|
||||
requestLen += 1 // protobuf length
|
||||
var addonsLen int
|
||||
/*if request.Flow != "" {
|
||||
addonsLen += 1 // protobuf header
|
||||
addonsLen += varbin.UvarintLen(uint64(len(request.Flow)))
|
||||
addonsLen += len(request.Flow)
|
||||
requestLen += addonsLen
|
||||
}*/
|
||||
requestLen += 1 // command
|
||||
requestLen += vmess.AddressSerializer.AddrPortLen(request.Destination)
|
||||
if len(payload) > 0 {
|
||||
requestLen += 2
|
||||
requestLen += len(payload)
|
||||
}
|
||||
buffer := buf.NewSize(requestLen)
|
||||
defer buffer.Release()
|
||||
common.Must(
|
||||
buffer.WriteByte(Version),
|
||||
common.Error(buffer.Write(request.UUID[:])),
|
||||
buffer.WriteByte(byte(addonsLen)),
|
||||
)
|
||||
|
||||
if addonsLen > 0 {
|
||||
common.Must(buffer.WriteByte(10))
|
||||
binary.PutUvarint(buffer.Extend(varbin.UvarintLen(uint64(len(request.Flow)))), uint64(len(request.Flow)))
|
||||
common.Must(common.Error(buffer.WriteString(request.Flow)))
|
||||
}
|
||||
|
||||
common.Must(buffer.WriteByte(vmess.CommandUDP))
|
||||
|
||||
err := vmess.AddressSerializer.WriteAddrPort(buffer, request.Destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(payload) > 0 {
|
||||
common.Must(
|
||||
binary.Write(buffer, binary.BigEndian, uint16(len(payload))),
|
||||
common.Error(buffer.Write(payload)),
|
||||
)
|
||||
}
|
||||
|
||||
return common.Error(writer.Write(buffer.Bytes()))
|
||||
}
|
||||
|
||||
func ReadResponse(reader io.Reader) error {
|
||||
var version byte
|
||||
err := binary.Read(reader, binary.BigEndian, &version)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if version != Version {
|
||||
return E.New("unknown version: ", version)
|
||||
}
|
||||
var protobufLength byte
|
||||
err = binary.Read(reader, binary.BigEndian, &protobufLength)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if protobufLength > 0 {
|
||||
err = rw.SkipN(reader, int(protobufLength))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package vless
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-vmess"
|
||||
"github.com/sagernet/sing/common/auth"
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
)
|
||||
|
||||
type Service[T comparable] struct {
|
||||
userMap map[[16]byte]T
|
||||
userFlow map[T]string
|
||||
logger logger.Logger
|
||||
handler Handler
|
||||
}
|
||||
|
||||
type Handler interface {
|
||||
N.TCPConnectionHandler
|
||||
N.UDPConnectionHandler
|
||||
E.Handler
|
||||
}
|
||||
|
||||
func NewService[T comparable](logger logger.Logger, handler Handler) *Service[T] {
|
||||
return &Service[T]{
|
||||
logger: logger,
|
||||
handler: handler,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service[T]) UpdateUsers(userList []T, userUUIDList []string, userFlowList []string) {
|
||||
userMap := make(map[[16]byte]T)
|
||||
userFlowMap := make(map[T]string)
|
||||
for i, userName := range userList {
|
||||
userID := uuid.FromStringOrNil(userUUIDList[i])
|
||||
if userID == uuid.Nil {
|
||||
userID = uuid.NewV5(uuid.Nil, userUUIDList[i])
|
||||
}
|
||||
userMap[userID] = userName
|
||||
userFlowMap[userName] = userFlowList[i]
|
||||
}
|
||||
s.userMap = userMap
|
||||
s.userFlow = userFlowMap
|
||||
}
|
||||
|
||||
var _ N.TCPConnectionHandler = (*Service[int])(nil)
|
||||
|
||||
func (s *Service[T]) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
||||
request, err := ReadRequest(conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
user, loaded := s.userMap[request.UUID]
|
||||
if !loaded {
|
||||
return E.New("unknown UUID: ", uuid.FromBytesOrNil(request.UUID[:]))
|
||||
}
|
||||
ctx = auth.ContextWithUser(ctx, user)
|
||||
metadata.Destination = request.Destination
|
||||
|
||||
userFlow := s.userFlow[user]
|
||||
if request.Flow == FlowVision && request.Command == vmess.NetworkUDP {
|
||||
return E.New(FlowVision, " flow does not support UDP")
|
||||
} else if request.Flow != userFlow {
|
||||
return E.New("flow mismatch: expected ", flowName(userFlow), ", but got ", flowName(request.Flow))
|
||||
}
|
||||
|
||||
if request.Command == vmess.CommandUDP {
|
||||
return s.handler.NewPacketConnection(ctx, &serverPacketConn{ExtendedConn: bufio.NewExtendedConn(conn), destination: request.Destination}, metadata)
|
||||
}
|
||||
responseConn := &serverConn{ExtendedConn: bufio.NewExtendedConn(conn), writer: bufio.NewVectorisedWriter(conn)}
|
||||
switch userFlow {
|
||||
case FlowVision:
|
||||
conn, err = NewVisionConn(responseConn, conn, request.UUID, s.logger)
|
||||
if err != nil {
|
||||
return E.Cause(err, "initialize vision")
|
||||
}
|
||||
case "":
|
||||
conn = responseConn
|
||||
default:
|
||||
return E.New("unknown flow: ", userFlow)
|
||||
}
|
||||
switch request.Command {
|
||||
case vmess.CommandTCP:
|
||||
return s.handler.NewConnection(ctx, conn, metadata)
|
||||
case vmess.CommandMux:
|
||||
return vmess.HandleMuxConnection(ctx, conn, s.handler)
|
||||
default:
|
||||
return E.New("unknown command: ", request.Command)
|
||||
}
|
||||
}
|
||||
|
||||
func flowName(value string) string {
|
||||
if value == "" {
|
||||
return "none"
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
var _ N.VectorisedWriter = (*serverConn)(nil)
|
||||
|
||||
type serverConn struct {
|
||||
N.ExtendedConn
|
||||
writer N.VectorisedWriter
|
||||
responseWritten bool
|
||||
}
|
||||
|
||||
func (c *serverConn) Read(b []byte) (n int, err error) {
|
||||
return c.ExtendedConn.Read(b)
|
||||
}
|
||||
|
||||
func (c *serverConn) Write(b []byte) (n int, err error) {
|
||||
if !c.responseWritten {
|
||||
_, err = bufio.WriteVectorised(c.writer, [][]byte{{Version, 0}, b})
|
||||
if err == nil {
|
||||
n = len(b)
|
||||
}
|
||||
c.responseWritten = true
|
||||
return
|
||||
}
|
||||
return c.ExtendedConn.Write(b)
|
||||
}
|
||||
|
||||
func (c *serverConn) WriteBuffer(buffer *buf.Buffer) error {
|
||||
if !c.responseWritten {
|
||||
header := buffer.ExtendHeader(2)
|
||||
header[0] = Version
|
||||
header[1] = 0
|
||||
c.responseWritten = true
|
||||
}
|
||||
return c.ExtendedConn.WriteBuffer(buffer)
|
||||
}
|
||||
|
||||
func (c *serverConn) WriteVectorised(buffers []*buf.Buffer) error {
|
||||
if !c.responseWritten {
|
||||
err := c.writer.WriteVectorised(append([]*buf.Buffer{buf.As([]byte{Version, 0})}, buffers...))
|
||||
c.responseWritten = true
|
||||
return err
|
||||
}
|
||||
return c.writer.WriteVectorised(buffers)
|
||||
}
|
||||
|
||||
func (c *serverConn) NeedAdditionalReadDeadline() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *serverConn) FrontHeadroom() int {
|
||||
if c.responseWritten {
|
||||
return 0
|
||||
}
|
||||
return 2
|
||||
}
|
||||
|
||||
func (c *serverConn) ReaderReplaceable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *serverConn) WriterReplaceable() bool {
|
||||
return c.responseWritten
|
||||
}
|
||||
|
||||
func (c *serverConn) Upstream() any {
|
||||
return c.ExtendedConn
|
||||
}
|
||||
|
||||
type serverPacketConn struct {
|
||||
N.ExtendedConn
|
||||
responseWriter io.Writer
|
||||
responseWritten bool
|
||||
destination M.Socksaddr
|
||||
}
|
||||
|
||||
func (c *serverPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||
n, err = c.ExtendedConn.Read(p)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if c.destination.IsFqdn() {
|
||||
addr = c.destination
|
||||
} else {
|
||||
addr = c.destination.UDPAddr()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *serverPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||
if !c.responseWritten {
|
||||
if c.responseWriter == nil {
|
||||
var packetLen [2]byte
|
||||
binary.BigEndian.PutUint16(packetLen[:], uint16(len(p)))
|
||||
_, err = bufio.WriteVectorised(bufio.NewVectorisedWriter(c.ExtendedConn), [][]byte{{Version, 0}, packetLen[:], p})
|
||||
if err == nil {
|
||||
n = len(p)
|
||||
}
|
||||
c.responseWritten = true
|
||||
return
|
||||
} else {
|
||||
_, err = c.responseWriter.Write([]byte{Version, 0})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
c.responseWritten = true
|
||||
}
|
||||
}
|
||||
return c.ExtendedConn.Write(p)
|
||||
}
|
||||
|
||||
func (c *serverPacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error) {
|
||||
var packetLen uint16
|
||||
err = binary.Read(c.ExtendedConn, binary.BigEndian, &packetLen)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, err = buffer.ReadFullFrom(c.ExtendedConn, int(packetLen))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
destination = c.destination
|
||||
return
|
||||
}
|
||||
|
||||
func (c *serverPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
||||
if !c.responseWritten {
|
||||
if c.responseWriter == nil {
|
||||
var packetLen [2]byte
|
||||
binary.BigEndian.PutUint16(packetLen[:], uint16(buffer.Len()))
|
||||
err := bufio.NewVectorisedWriter(c.ExtendedConn).WriteVectorised([]*buf.Buffer{buf.As([]byte{Version, 0}), buf.As(packetLen[:]), buffer})
|
||||
c.responseWritten = true
|
||||
return err
|
||||
} else {
|
||||
_, err := c.responseWriter.Write([]byte{Version, 0})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.responseWritten = true
|
||||
}
|
||||
}
|
||||
packetLen := buffer.Len()
|
||||
binary.BigEndian.PutUint16(buffer.ExtendHeader(2), uint16(packetLen))
|
||||
return c.ExtendedConn.WriteBuffer(buffer)
|
||||
}
|
||||
|
||||
func (c *serverPacketConn) FrontHeadroom() int {
|
||||
return 2
|
||||
}
|
||||
|
||||
func (c *serverPacketConn) Upstream() any {
|
||||
return c.ExtendedConn
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
package vless
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"reflect"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/buf"
|
||||
"github.com/sagernet/sing/common/bufio"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
)
|
||||
|
||||
var tlsRegistry []func(conn net.Conn) (loaded bool, netConn net.Conn, reflectType reflect.Type, reflectPointer uintptr)
|
||||
|
||||
func init() {
|
||||
tlsRegistry = append(tlsRegistry, func(conn net.Conn) (loaded bool, netConn net.Conn, reflectType reflect.Type, reflectPointer uintptr) {
|
||||
tlsConn, loaded := common.Cast[*tls.Conn](conn)
|
||||
if !loaded {
|
||||
return
|
||||
}
|
||||
return true, tlsConn.NetConn(), reflect.TypeOf(tlsConn).Elem(), uintptr(unsafe.Pointer(tlsConn))
|
||||
})
|
||||
}
|
||||
|
||||
const xrayChunkSize = 8192
|
||||
|
||||
type VisionConn struct {
|
||||
net.Conn
|
||||
reader *bufio.ChunkReader
|
||||
writer N.VectorisedWriter
|
||||
input *bytes.Reader
|
||||
rawInput *bytes.Buffer
|
||||
netConn net.Conn
|
||||
logger logger.Logger
|
||||
|
||||
userUUID [16]byte
|
||||
isTLS bool
|
||||
numberOfPacketToFilter int
|
||||
isTLS12orAbove bool
|
||||
remainingServerHello int32
|
||||
cipher uint16
|
||||
enableXTLS bool
|
||||
isPadding bool
|
||||
directWrite bool
|
||||
writeUUID bool
|
||||
withinPaddingBuffers bool
|
||||
remainingContent int
|
||||
remainingPadding int
|
||||
currentCommand byte
|
||||
directRead bool
|
||||
remainingReader io.Reader
|
||||
}
|
||||
|
||||
func NewVisionConn(conn net.Conn, tlsConn net.Conn, userUUID [16]byte, logger logger.Logger) (*VisionConn, error) {
|
||||
var (
|
||||
loaded bool
|
||||
reflectType reflect.Type
|
||||
reflectPointer uintptr
|
||||
netConn net.Conn
|
||||
)
|
||||
for _, tlsCreator := range tlsRegistry {
|
||||
loaded, netConn, reflectType, reflectPointer = tlsCreator(tlsConn)
|
||||
if loaded {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !loaded {
|
||||
return nil, C.ErrTLSRequired
|
||||
}
|
||||
input, _ := reflectType.FieldByName("input")
|
||||
rawInput, _ := reflectType.FieldByName("rawInput")
|
||||
return &VisionConn{
|
||||
Conn: conn,
|
||||
reader: bufio.NewChunkReader(conn, xrayChunkSize),
|
||||
writer: bufio.NewVectorisedWriter(conn),
|
||||
input: (*bytes.Reader)(unsafe.Pointer(reflectPointer + input.Offset)),
|
||||
rawInput: (*bytes.Buffer)(unsafe.Pointer(reflectPointer + rawInput.Offset)),
|
||||
netConn: netConn,
|
||||
logger: logger,
|
||||
|
||||
userUUID: userUUID,
|
||||
numberOfPacketToFilter: 8,
|
||||
remainingServerHello: -1,
|
||||
isPadding: true,
|
||||
writeUUID: true,
|
||||
withinPaddingBuffers: true,
|
||||
remainingContent: -1,
|
||||
remainingPadding: -1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *VisionConn) Read(p []byte) (n int, err error) {
|
||||
if c.remainingReader != nil {
|
||||
n, err = c.remainingReader.Read(p)
|
||||
if err == io.EOF {
|
||||
err = nil
|
||||
c.remainingReader = nil
|
||||
}
|
||||
if n > 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
if c.directRead {
|
||||
return c.netConn.Read(p)
|
||||
}
|
||||
var bufferBytes []byte
|
||||
var chunkBuffer *buf.Buffer
|
||||
if len(p) > xrayChunkSize {
|
||||
n, err = c.Conn.Read(p)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
bufferBytes = p[:n]
|
||||
} else {
|
||||
chunkBuffer, err = c.reader.ReadChunk()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
bufferBytes = chunkBuffer.Bytes()
|
||||
}
|
||||
if c.withinPaddingBuffers || c.numberOfPacketToFilter > 0 {
|
||||
buffers := c.unPadding(bufferBytes)
|
||||
if chunkBuffer != nil {
|
||||
buffers = common.Map(buffers, func(it *buf.Buffer) *buf.Buffer {
|
||||
return it.ToOwned()
|
||||
})
|
||||
chunkBuffer.Reset()
|
||||
}
|
||||
if c.remainingContent == 0 && c.remainingPadding == 0 {
|
||||
if c.currentCommand == commandPaddingEnd {
|
||||
c.withinPaddingBuffers = false
|
||||
c.remainingContent = -1
|
||||
c.remainingPadding = -1
|
||||
} else if c.currentCommand == commandPaddingDirect {
|
||||
c.withinPaddingBuffers = false
|
||||
c.directRead = true
|
||||
|
||||
inputBuffer, err := io.ReadAll(c.input)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
buffers = append(buffers, buf.As(inputBuffer))
|
||||
|
||||
rawInputBuffer, err := io.ReadAll(c.rawInput)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
buffers = append(buffers, buf.As(rawInputBuffer))
|
||||
|
||||
c.logger.Trace("XtlsRead readV")
|
||||
} else if c.currentCommand == commandPaddingContinue {
|
||||
c.withinPaddingBuffers = true
|
||||
} else {
|
||||
return 0, E.New("unknown command ", c.currentCommand)
|
||||
}
|
||||
} else if c.remainingContent > 0 || c.remainingPadding > 0 {
|
||||
c.withinPaddingBuffers = true
|
||||
} else {
|
||||
c.withinPaddingBuffers = false
|
||||
}
|
||||
if c.numberOfPacketToFilter > 0 {
|
||||
c.filterTLS(buf.ToSliceMulti(buffers))
|
||||
}
|
||||
c.remainingReader = io.MultiReader(common.Map(buffers, func(it *buf.Buffer) io.Reader { return it })...)
|
||||
return c.Read(p)
|
||||
} else {
|
||||
if c.numberOfPacketToFilter > 0 {
|
||||
c.filterTLS([][]byte{bufferBytes})
|
||||
}
|
||||
if chunkBuffer != nil {
|
||||
n = copy(p, bufferBytes)
|
||||
chunkBuffer.Advance(n)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (c *VisionConn) Write(p []byte) (n int, err error) {
|
||||
if c.numberOfPacketToFilter > 0 {
|
||||
c.filterTLS([][]byte{p})
|
||||
}
|
||||
if c.isPadding {
|
||||
inputLen := len(p)
|
||||
buffers := reshapeBuffer(p)
|
||||
var specIndex int
|
||||
for i, buffer := range buffers {
|
||||
if c.isTLS && buffer.Len() > 6 && bytes.Equal(tlsApplicationDataStart, buffer.To(3)) {
|
||||
var command byte = commandPaddingEnd
|
||||
if c.enableXTLS {
|
||||
c.directWrite = true
|
||||
specIndex = i
|
||||
command = commandPaddingDirect
|
||||
}
|
||||
c.isPadding = false
|
||||
buffers[i] = c.padding(buffer, command)
|
||||
break
|
||||
} else if !c.isTLS12orAbove && c.numberOfPacketToFilter <= 1 {
|
||||
c.isPadding = false
|
||||
buffers[i] = c.padding(buffer, commandPaddingEnd)
|
||||
break
|
||||
}
|
||||
buffers[i] = c.padding(buffer, commandPaddingContinue)
|
||||
}
|
||||
if c.directWrite {
|
||||
encryptedBuffer := buffers[:specIndex+1]
|
||||
err = c.writer.WriteVectorised(encryptedBuffer)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
buffers = buffers[specIndex+1:]
|
||||
c.writer = bufio.NewVectorisedWriter(c.netConn)
|
||||
c.logger.Trace("XtlsWrite writeV ", specIndex, " ", buf.LenMulti(encryptedBuffer), " ", len(buffers))
|
||||
time.Sleep(5 * time.Millisecond) // wtf
|
||||
}
|
||||
err = c.writer.WriteVectorised(buffers)
|
||||
if err == nil {
|
||||
n = inputLen
|
||||
}
|
||||
return
|
||||
}
|
||||
if c.directWrite {
|
||||
return c.netConn.Write(p)
|
||||
} else {
|
||||
return c.Conn.Write(p)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *VisionConn) filterTLS(buffers [][]byte) {
|
||||
for _, buffer := range buffers {
|
||||
c.numberOfPacketToFilter--
|
||||
if len(buffer) > 6 {
|
||||
if buffer[0] == 22 && buffer[1] == 3 && buffer[2] == 3 {
|
||||
c.isTLS = true
|
||||
if buffer[5] == 2 {
|
||||
c.isTLS12orAbove = true
|
||||
c.remainingServerHello = (int32(buffer[3])<<8 | int32(buffer[4])) + 5
|
||||
if len(buffer) >= 79 && c.remainingServerHello >= 79 {
|
||||
sessionIdLen := int32(buffer[43])
|
||||
cipherSuite := buffer[43+sessionIdLen+1 : 43+sessionIdLen+3]
|
||||
c.cipher = uint16(cipherSuite[0])<<8 | uint16(cipherSuite[1])
|
||||
} else {
|
||||
c.logger.Trace("XtlsFilterTls short server hello, tls 1.2 or older? ", len(buffer), " ", c.remainingServerHello)
|
||||
}
|
||||
}
|
||||
} else if bytes.Equal(tlsClientHandShakeStart, buffer[:2]) && buffer[5] == 1 {
|
||||
c.isTLS = true
|
||||
c.logger.Trace("XtlsFilterTls found tls client hello! ", len(buffer))
|
||||
}
|
||||
}
|
||||
if c.remainingServerHello > 0 {
|
||||
end := int(c.remainingServerHello)
|
||||
if end > len(buffer) {
|
||||
end = len(buffer)
|
||||
}
|
||||
c.remainingServerHello -= int32(end)
|
||||
if bytes.Contains(buffer[:end], tls13SupportedVersions) {
|
||||
cipher, ok := tls13CipherSuiteDic[c.cipher]
|
||||
if ok && cipher != "TLS_AES_128_CCM_8_SHA256" {
|
||||
c.enableXTLS = true
|
||||
}
|
||||
c.logger.Trace("XtlsFilterTls found tls 1.3! ", len(buffer), " ", c.cipher, " ", c.enableXTLS)
|
||||
c.numberOfPacketToFilter = 0
|
||||
return
|
||||
} else if c.remainingServerHello == 0 {
|
||||
c.logger.Trace("XtlsFilterTls found tls 1.2! ", len(buffer))
|
||||
c.numberOfPacketToFilter = 0
|
||||
return
|
||||
}
|
||||
}
|
||||
if c.numberOfPacketToFilter == 0 {
|
||||
c.logger.Trace("XtlsFilterTls stop filtering ", len(buffer))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *VisionConn) padding(buffer *buf.Buffer, command byte) *buf.Buffer {
|
||||
contentLen := 0
|
||||
paddingLen := 0
|
||||
if buffer != nil {
|
||||
contentLen = buffer.Len()
|
||||
}
|
||||
if contentLen < 900 && c.isTLS {
|
||||
l, _ := rand.Int(rand.Reader, big.NewInt(500))
|
||||
paddingLen = int(l.Int64()) + 900 - contentLen
|
||||
} else {
|
||||
l, _ := rand.Int(rand.Reader, big.NewInt(256))
|
||||
paddingLen = int(l.Int64())
|
||||
}
|
||||
var bufferLen int
|
||||
if c.writeUUID {
|
||||
bufferLen += 16
|
||||
}
|
||||
bufferLen += 5
|
||||
if buffer != nil {
|
||||
bufferLen += buffer.Len()
|
||||
}
|
||||
bufferLen += paddingLen
|
||||
newBuffer := buf.NewSize(bufferLen)
|
||||
if c.writeUUID {
|
||||
common.Must1(newBuffer.Write(c.userUUID[:]))
|
||||
c.writeUUID = false
|
||||
}
|
||||
common.Must1(newBuffer.Write([]byte{command, byte(contentLen >> 8), byte(contentLen), byte(paddingLen >> 8), byte(paddingLen)}))
|
||||
if buffer != nil {
|
||||
common.Must1(newBuffer.Write(buffer.Bytes()))
|
||||
buffer.Release()
|
||||
}
|
||||
newBuffer.Extend(paddingLen)
|
||||
c.logger.Trace("XtlsPadding ", contentLen, " ", paddingLen, " ", command)
|
||||
return newBuffer
|
||||
}
|
||||
|
||||
func (c *VisionConn) unPadding(buffer []byte) []*buf.Buffer {
|
||||
var bufferIndex int
|
||||
if c.remainingContent == -1 && c.remainingPadding == -1 {
|
||||
if len(buffer) >= 21 && bytes.Equal(c.userUUID[:], buffer[:16]) {
|
||||
bufferIndex = 16
|
||||
c.remainingContent = 0
|
||||
c.remainingPadding = 0
|
||||
c.currentCommand = 0
|
||||
}
|
||||
}
|
||||
if c.remainingContent == -1 && c.remainingPadding == -1 {
|
||||
return []*buf.Buffer{buf.As(buffer)}
|
||||
}
|
||||
var buffers []*buf.Buffer
|
||||
for bufferIndex < len(buffer) {
|
||||
if c.remainingContent <= 0 && c.remainingPadding <= 0 {
|
||||
if c.currentCommand == 1 {
|
||||
buffers = append(buffers, buf.As(buffer[bufferIndex:]))
|
||||
break
|
||||
} else {
|
||||
paddingInfo := buffer[bufferIndex : bufferIndex+5]
|
||||
c.currentCommand = paddingInfo[0]
|
||||
c.remainingContent = int(paddingInfo[1])<<8 | int(paddingInfo[2])
|
||||
c.remainingPadding = int(paddingInfo[3])<<8 | int(paddingInfo[4])
|
||||
bufferIndex += 5
|
||||
c.logger.Trace("Xtls Unpadding new block ", bufferIndex, " ", c.remainingContent, " padding ", c.remainingPadding, " ", c.currentCommand)
|
||||
}
|
||||
} else if c.remainingContent > 0 {
|
||||
end := c.remainingContent
|
||||
if end > len(buffer)-bufferIndex {
|
||||
end = len(buffer) - bufferIndex
|
||||
}
|
||||
buffers = append(buffers, buf.As(buffer[bufferIndex:bufferIndex+end]))
|
||||
c.remainingContent -= end
|
||||
bufferIndex += end
|
||||
} else {
|
||||
end := c.remainingPadding
|
||||
if end > len(buffer)-bufferIndex {
|
||||
end = len(buffer) - bufferIndex
|
||||
}
|
||||
c.remainingPadding -= end
|
||||
bufferIndex += end
|
||||
}
|
||||
if bufferIndex == len(buffer) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return buffers
|
||||
}
|
||||
|
||||
func (c *VisionConn) NeedAdditionalReadDeadline() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *VisionConn) Upstream() any {
|
||||
return c.Conn
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build with_reality_server
|
||||
|
||||
package vless
|
||||
|
||||
import (
|
||||
"net"
|
||||
"reflect"
|
||||
"unsafe"
|
||||
|
||||
"github.com/sagernet/reality"
|
||||
"github.com/sagernet/sing/common"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tlsRegistry = append(tlsRegistry, func(conn net.Conn) (loaded bool, netConn net.Conn, reflectType reflect.Type, reflectPointer uintptr) {
|
||||
tlsConn, loaded := common.Cast[*reality.Conn](conn)
|
||||
if !loaded {
|
||||
return
|
||||
}
|
||||
return true, tlsConn.NetConn(), reflect.TypeOf(tlsConn).Elem(), uintptr(unsafe.Pointer(tlsConn))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build with_utls
|
||||
|
||||
package vless
|
||||
|
||||
import (
|
||||
"net"
|
||||
"reflect"
|
||||
"unsafe"
|
||||
|
||||
"github.com/sagernet/sing/common"
|
||||
utls "github.com/sagernet/utls"
|
||||
)
|
||||
|
||||
func init() {
|
||||
tlsRegistry = append(tlsRegistry, func(conn net.Conn) (loaded bool, netConn net.Conn, reflectType reflect.Type, reflectPointer uintptr) {
|
||||
tlsConn, loaded := common.Cast[*utls.UConn](conn)
|
||||
if !loaded {
|
||||
return
|
||||
}
|
||||
return true, tlsConn.NetConn(), reflect.TypeOf(tlsConn.Conn).Elem(), uintptr(unsafe.Pointer(tlsConn.Conn))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user