mirror of
https://github.com/SagerNet/sing-box.git
synced 2026-04-13 20:28:32 +10:00
Compare commits
81 Commits
v1.2.2
...
v1.3-beta9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bec606ee88 | ||
|
|
8545e41b2f | ||
|
|
d8810b6e8f | ||
|
|
f568bb9fe3 | ||
|
|
ccb872a41e | ||
|
|
9c287094e2 | ||
|
|
f61c5600e0 | ||
|
|
2e98777f82 | ||
|
|
73e72e9aec | ||
|
|
922acced94 | ||
|
|
988d7331c6 | ||
|
|
c0d6dde95b | ||
|
|
4dbf95875b | ||
|
|
81c4312be8 | ||
|
|
cc94dfaa4b | ||
|
|
c6fc411164 | ||
|
|
be00e19162 | ||
|
|
eb57cbc4ad | ||
|
|
f98cfdf5e4 | ||
|
|
cbf0099681 | ||
|
|
a86afa0e5b | ||
|
|
b5d2062359 | ||
|
|
e8dad1afeb | ||
|
|
6ce4e31fc8 | ||
|
|
d2d4faf520 | ||
|
|
438de36749 | ||
|
|
df0eef770e | ||
|
|
bbdd495ed5 | ||
|
|
d686172854 | ||
|
|
e1d96cb64e | ||
|
|
d5f94b65b7 | ||
|
|
ec2d0b6b3c | ||
|
|
3a92bf993d | ||
|
|
ec13965fd0 | ||
|
|
ddf747006e | ||
|
|
4382093868 | ||
|
|
a5322850b3 | ||
|
|
407b08975c | ||
|
|
c7067ff5e8 | ||
|
|
9b2384b296 | ||
|
|
b498a22972 | ||
|
|
20e9da5c67 | ||
|
|
ec8974673b | ||
|
|
5e6e7923e4 | ||
|
|
de1b5971e1 | ||
|
|
5c20d0b4d5 | ||
|
|
9df96ac7f1 | ||
|
|
87cd925144 | ||
|
|
fecb796000 | ||
|
|
cfb6c804aa | ||
|
|
11c50c7558 | ||
|
|
34cc7f176e | ||
|
|
b54da9c6af | ||
|
|
f44f86b832 | ||
|
|
4ebf40f582 | ||
|
|
53e4302143 | ||
|
|
cf778eda4f | ||
|
|
bb63429079 | ||
|
|
f7f9a7ae20 | ||
|
|
8699412a4c | ||
|
|
0d7aa19cd1 | ||
|
|
50a7295360 | ||
|
|
e57b6ae98d | ||
|
|
6843970536 | ||
|
|
62425ad3e4 | ||
|
|
e1e217854e | ||
|
|
5bf177b021 | ||
|
|
72dbf2e2b4 | ||
|
|
46c318c6fe | ||
|
|
05bb1b88c3 | ||
|
|
5176ea9fe0 | ||
|
|
36d349acd2 | ||
|
|
4feee983b5 | ||
|
|
9b12e3e389 | ||
|
|
afd3464216 | ||
|
|
8b64446274 | ||
|
|
28aa4c4d1f | ||
|
|
0be3cdc8fb | ||
|
|
f8be484019 | ||
|
|
35f03f092d | ||
|
|
c3d7401ead |
12
.github/workflows/debug.yml
vendored
12
.github/workflows/debug.yml
vendored
@@ -31,12 +31,6 @@ jobs:
|
|||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v3
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
~/go/pkg/mod
|
|
||||||
key: go-${{ hashFiles('**/go.sum') }}
|
|
||||||
- name: Add cache to Go proxy
|
- name: Add cache to Go proxy
|
||||||
run: |
|
run: |
|
||||||
version=`git rev-parse HEAD`
|
version=`git rev-parse HEAD`
|
||||||
@@ -196,12 +190,6 @@ jobs:
|
|||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v3
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
~/go/pkg/mod
|
|
||||||
key: go-${{ hashFiles('**/go.sum') }}
|
|
||||||
- name: Build
|
- name: Build
|
||||||
id: build
|
id: build
|
||||||
run: make
|
run: make
|
||||||
|
|||||||
6
.github/workflows/lint.yml
vendored
6
.github/workflows/lint.yml
vendored
@@ -31,12 +31,6 @@ jobs:
|
|||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
go-version: ${{ steps.version.outputs.go_version }}
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v3
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
~/go/pkg/mod
|
|
||||||
key: go-${{ hashFiles('**/go.sum') }}
|
|
||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v3
|
uses: golangci/golangci-lint-action@v3
|
||||||
with:
|
with:
|
||||||
|
|||||||
13
Makefile
13
Makefile
@@ -77,13 +77,20 @@ test_stdio:
|
|||||||
go mod tidy && \
|
go mod tidy && \
|
||||||
go test -v -tags "$(TAGS_TEST),force_stdio" .
|
go test -v -tags "$(TAGS_TEST),force_stdio" .
|
||||||
|
|
||||||
|
android:
|
||||||
|
go run ./cmd/internal/build_libbox -target android
|
||||||
|
|
||||||
|
ios:
|
||||||
|
go run ./cmd/internal/build_libbox -target ios
|
||||||
|
|
||||||
lib:
|
lib:
|
||||||
go run ./cmd/internal/build_libbox
|
go run ./cmd/internal/build_libbox -target android
|
||||||
|
go run ./cmd/internal/build_libbox -target ios
|
||||||
|
|
||||||
lib_install:
|
lib_install:
|
||||||
go get -v -d
|
go get -v -d
|
||||||
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.0.0-20221130124640-349ebaa752ca
|
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.0.0-20230413023804-244d7ff07035
|
||||||
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.0.0-20221130124640-349ebaa752ca
|
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.0.0-20230413023804-244d7ff07035
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf bin dist sing-box
|
rm -rf bin dist sing-box
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ The universal proxy platform.
|
|||||||
|
|
||||||
https://sing-box.sagernet.org
|
https://sing-box.sagernet.org
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
https://community.sagernet.org/c/sing-box/
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ type ClashServer interface {
|
|||||||
PreStarter
|
PreStarter
|
||||||
Mode() string
|
Mode() string
|
||||||
StoreSelected() bool
|
StoreSelected() bool
|
||||||
|
StoreFakeIP() bool
|
||||||
CacheFile() ClashCacheFile
|
CacheFile() ClashCacheFile
|
||||||
HistoryStorage() *urltest.HistoryStorage
|
HistoryStorage() *urltest.HistoryStorage
|
||||||
RoutedConnection(ctx context.Context, conn net.Conn, metadata InboundContext, matchedRule Rule) (net.Conn, Tracker)
|
RoutedConnection(ctx context.Context, conn net.Conn, metadata InboundContext, matchedRule Rule) (net.Conn, Tracker)
|
||||||
@@ -22,6 +23,7 @@ type ClashServer interface {
|
|||||||
type ClashCacheFile interface {
|
type ClashCacheFile interface {
|
||||||
LoadSelected(group string) string
|
LoadSelected(group string) string
|
||||||
StoreSelected(group string, selected string) error
|
StoreSelected(group string, selected string) error
|
||||||
|
FakeIPStorage
|
||||||
}
|
}
|
||||||
|
|
||||||
type Tracker interface {
|
type Tracker interface {
|
||||||
@@ -33,6 +35,11 @@ type OutboundGroup interface {
|
|||||||
All() []string
|
All() []string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type URLTestGroup interface {
|
||||||
|
OutboundGroup
|
||||||
|
URLTest(ctx context.Context, url string) (map[string]uint16, error)
|
||||||
|
}
|
||||||
|
|
||||||
func OutboundTag(detour Outbound) string {
|
func OutboundTag(detour Outbound) string {
|
||||||
if group, isGroup := detour.(OutboundGroup); isGroup {
|
if group, isGroup := detour.(OutboundGroup); isGroup {
|
||||||
return group.Now()
|
return group.Now()
|
||||||
|
|||||||
23
adapter/fakeip.go
Normal file
23
adapter/fakeip.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package adapter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FakeIPStore interface {
|
||||||
|
Service
|
||||||
|
Contains(address netip.Addr) bool
|
||||||
|
Create(domain string, strategy dns.DomainStrategy) (netip.Addr, error)
|
||||||
|
Lookup(address netip.Addr) (string, bool)
|
||||||
|
Reset() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type FakeIPStorage interface {
|
||||||
|
FakeIPMetadata() *FakeIPMetadata
|
||||||
|
FakeIPSaveMetadata(metadata *FakeIPMetadata) error
|
||||||
|
FakeIPStore(address netip.Addr, domain string) error
|
||||||
|
FakeIPLoad(address netip.Addr) (string, bool)
|
||||||
|
FakeIPReset() error
|
||||||
|
}
|
||||||
50
adapter/fakeip_metadata.go
Normal file
50
adapter/fakeip_metadata.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package adapter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding"
|
||||||
|
"encoding/binary"
|
||||||
|
"io"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FakeIPMetadata struct {
|
||||||
|
Inet4Range netip.Prefix
|
||||||
|
Inet6Range netip.Prefix
|
||||||
|
Inet4Current netip.Addr
|
||||||
|
Inet6Current netip.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *FakeIPMetadata) MarshalBinary() (data []byte, err error) {
|
||||||
|
var buffer bytes.Buffer
|
||||||
|
for _, marshaler := range []encoding.BinaryMarshaler{m.Inet4Range, m.Inet6Range, m.Inet4Current, m.Inet6Current} {
|
||||||
|
data, err = marshaler.MarshalBinary()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
common.Must(binary.Write(&buffer, binary.BigEndian, uint16(len(data))))
|
||||||
|
buffer.Write(data)
|
||||||
|
}
|
||||||
|
data = buffer.Bytes()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *FakeIPMetadata) UnmarshalBinary(data []byte) error {
|
||||||
|
reader := bytes.NewReader(data)
|
||||||
|
for _, unmarshaler := range []encoding.BinaryUnmarshaler{&m.Inet4Range, &m.Inet6Range, &m.Inet4Current, &m.Inet6Current} {
|
||||||
|
var length uint16
|
||||||
|
common.Must(binary.Read(reader, binary.BigEndian, &length))
|
||||||
|
element := make([]byte, length)
|
||||||
|
_, err := io.ReadFull(reader, element)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = unmarshaler.UnmarshalBinary(element)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ type InjectableInbound interface {
|
|||||||
type InboundContext struct {
|
type InboundContext struct {
|
||||||
Inbound string
|
Inbound string
|
||||||
InboundType string
|
InboundType string
|
||||||
IPVersion int
|
IPVersion uint8
|
||||||
Network string
|
Network string
|
||||||
Source M.Socksaddr
|
Source M.Socksaddr
|
||||||
Destination M.Socksaddr
|
Destination M.Socksaddr
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-tun"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -17,3 +18,8 @@ type Outbound interface {
|
|||||||
NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
||||||
NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type IPOutbound interface {
|
||||||
|
Outbound
|
||||||
|
NewIPConnection(ctx context.Context, conn tun.RouteContext, metadata InboundContext) (tun.DirectDestination, error)
|
||||||
|
}
|
||||||
|
|||||||
@@ -21,8 +21,13 @@ type Router interface {
|
|||||||
Outbound(tag string) (Outbound, bool)
|
Outbound(tag string) (Outbound, bool)
|
||||||
DefaultOutbound(network string) Outbound
|
DefaultOutbound(network string) Outbound
|
||||||
|
|
||||||
|
FakeIPStore() FakeIPStore
|
||||||
|
|
||||||
RouteConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
RouteConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
||||||
RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
||||||
|
RouteIPConnection(ctx context.Context, conn tun.RouteContext, metadata InboundContext) tun.RouteAction
|
||||||
|
|
||||||
|
NatRequired(outbound string) bool
|
||||||
|
|
||||||
GeoIPReader() *geoip.Reader
|
GeoIPReader() *geoip.Reader
|
||||||
LoadGeosite(code string) (Rule, error)
|
LoadGeosite(code string) (Rule, error)
|
||||||
@@ -32,6 +37,7 @@ type Router interface {
|
|||||||
LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error)
|
LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error)
|
||||||
|
|
||||||
InterfaceFinder() control.InterfaceFinder
|
InterfaceFinder() control.InterfaceFinder
|
||||||
|
UpdateInterfaces() error
|
||||||
DefaultInterface() string
|
DefaultInterface() string
|
||||||
AutoDetectInterface() bool
|
AutoDetectInterface() bool
|
||||||
AutoDetectInterfaceFunc() control.Func
|
AutoDetectInterfaceFunc() control.Func
|
||||||
@@ -39,7 +45,9 @@ type Router interface {
|
|||||||
NetworkMonitor() tun.NetworkUpdateMonitor
|
NetworkMonitor() tun.NetworkUpdateMonitor
|
||||||
InterfaceMonitor() tun.DefaultInterfaceMonitor
|
InterfaceMonitor() tun.DefaultInterfaceMonitor
|
||||||
PackageManager() tun.PackageManager
|
PackageManager() tun.PackageManager
|
||||||
|
|
||||||
Rules() []Rule
|
Rules() []Rule
|
||||||
|
IPRules() []IPRule
|
||||||
|
|
||||||
TimeService
|
TimeService
|
||||||
|
|
||||||
@@ -76,6 +84,12 @@ type Rule interface {
|
|||||||
type DNSRule interface {
|
type DNSRule interface {
|
||||||
Rule
|
Rule
|
||||||
DisableCache() bool
|
DisableCache() bool
|
||||||
|
RewriteTTL() *uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
type IPRule interface {
|
||||||
|
Rule
|
||||||
|
Action() tun.ActionType
|
||||||
}
|
}
|
||||||
|
|
||||||
type InterfaceUpdateListener interface {
|
type InterfaceUpdateListener interface {
|
||||||
|
|||||||
143
box.go
143
box.go
@@ -9,7 +9,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing-box/experimental"
|
"github.com/sagernet/sing-box/experimental"
|
||||||
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
||||||
"github.com/sagernet/sing-box/inbound"
|
"github.com/sagernet/sing-box/inbound"
|
||||||
@@ -31,18 +30,25 @@ type Box struct {
|
|||||||
outbounds []adapter.Outbound
|
outbounds []adapter.Outbound
|
||||||
logFactory log.Factory
|
logFactory log.Factory
|
||||||
logger log.ContextLogger
|
logger log.ContextLogger
|
||||||
logFile *os.File
|
|
||||||
preServices map[string]adapter.Service
|
preServices map[string]adapter.Service
|
||||||
postServices map[string]adapter.Service
|
postServices map[string]adapter.Service
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(ctx context.Context, options option.Options, platformInterface platform.Interface) (*Box, error) {
|
type Options struct {
|
||||||
createdAt := time.Now()
|
option.Options
|
||||||
|
Context context.Context
|
||||||
|
PlatformInterface platform.Interface
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(options Options) (*Box, error) {
|
||||||
|
ctx := options.Context
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
createdAt := time.Now()
|
||||||
experimentalOptions := common.PtrValueOrDefault(options.Experimental)
|
experimentalOptions := common.PtrValueOrDefault(options.Experimental)
|
||||||
applyDebugOptions(common.PtrValueOrDefault(experimentalOptions.Debug))
|
applyDebugOptions(common.PtrValueOrDefault(experimentalOptions.Debug))
|
||||||
|
|
||||||
var needClashAPI bool
|
var needClashAPI bool
|
||||||
var needV2RayAPI bool
|
var needV2RayAPI bool
|
||||||
if experimentalOptions.ClashAPI != nil && experimentalOptions.ClashAPI.ExternalController != "" {
|
if experimentalOptions.ClashAPI != nil && experimentalOptions.ClashAPI.ExternalController != "" {
|
||||||
@@ -51,60 +57,21 @@ func New(ctx context.Context, options option.Options, platformInterface platform
|
|||||||
if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" {
|
if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" {
|
||||||
needV2RayAPI = true
|
needV2RayAPI = true
|
||||||
}
|
}
|
||||||
|
var defaultLogWriter io.Writer
|
||||||
logOptions := common.PtrValueOrDefault(options.Log)
|
if options.PlatformInterface != nil {
|
||||||
|
defaultLogWriter = io.Discard
|
||||||
var logFactory log.Factory
|
}
|
||||||
var observableLogFactory log.ObservableFactory
|
logFactory, err := log.New(log.Options{
|
||||||
var logFile *os.File
|
Context: ctx,
|
||||||
var logWriter io.Writer
|
Options: common.PtrValueOrDefault(options.Log),
|
||||||
if logOptions.Disabled {
|
Observable: needClashAPI,
|
||||||
observableLogFactory = log.NewNOPFactory()
|
DefaultWriter: defaultLogWriter,
|
||||||
logFactory = observableLogFactory
|
BaseTime: createdAt,
|
||||||
} else {
|
PlatformWriter: options.PlatformInterface,
|
||||||
switch logOptions.Output {
|
})
|
||||||
case "":
|
if err != nil {
|
||||||
if platformInterface != nil {
|
return nil, E.Cause(err, "create log factory")
|
||||||
logWriter = io.Discard
|
|
||||||
} else {
|
|
||||||
logWriter = os.Stdout
|
|
||||||
}
|
|
||||||
case "stderr":
|
|
||||||
logWriter = os.Stderr
|
|
||||||
case "stdout":
|
|
||||||
logWriter = os.Stdout
|
|
||||||
default:
|
|
||||||
var err error
|
|
||||||
logFile, err = os.OpenFile(C.BasePath(logOptions.Output), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
logWriter = logFile
|
|
||||||
}
|
|
||||||
logFormatter := log.Formatter{
|
|
||||||
BaseTime: createdAt,
|
|
||||||
DisableColors: logOptions.DisableColor || logFile != nil,
|
|
||||||
DisableTimestamp: !logOptions.Timestamp && logFile != nil,
|
|
||||||
FullTimestamp: logOptions.Timestamp,
|
|
||||||
TimestampFormat: "-0700 2006-01-02 15:04:05",
|
|
||||||
}
|
|
||||||
if needClashAPI {
|
|
||||||
observableLogFactory = log.NewObservableFactory(logFormatter, logWriter, platformInterface)
|
|
||||||
logFactory = observableLogFactory
|
|
||||||
} else {
|
|
||||||
logFactory = log.NewFactory(logFormatter, logWriter, platformInterface)
|
|
||||||
}
|
|
||||||
if logOptions.Level != "" {
|
|
||||||
logLevel, err := log.ParseLevel(logOptions.Level)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "parse log level")
|
|
||||||
}
|
|
||||||
logFactory.SetLevel(logLevel)
|
|
||||||
} else {
|
|
||||||
logFactory.SetLevel(log.LevelTrace)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
router, err := route.NewRouter(
|
router, err := route.NewRouter(
|
||||||
ctx,
|
ctx,
|
||||||
logFactory,
|
logFactory,
|
||||||
@@ -112,7 +79,7 @@ func New(ctx context.Context, options option.Options, platformInterface platform
|
|||||||
common.PtrValueOrDefault(options.DNS),
|
common.PtrValueOrDefault(options.DNS),
|
||||||
common.PtrValueOrDefault(options.NTP),
|
common.PtrValueOrDefault(options.NTP),
|
||||||
options.Inbounds,
|
options.Inbounds,
|
||||||
platformInterface,
|
options.PlatformInterface,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "parse route options")
|
return nil, E.Cause(err, "parse route options")
|
||||||
@@ -132,7 +99,7 @@ func New(ctx context.Context, options option.Options, platformInterface platform
|
|||||||
router,
|
router,
|
||||||
logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
|
logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
|
||||||
inboundOptions,
|
inboundOptions,
|
||||||
platformInterface,
|
options.PlatformInterface,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "parse inbound[", i, "]")
|
return nil, E.Cause(err, "parse inbound[", i, "]")
|
||||||
@@ -151,6 +118,7 @@ func New(ctx context.Context, options option.Options, platformInterface platform
|
|||||||
ctx,
|
ctx,
|
||||||
router,
|
router,
|
||||||
logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
|
logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
|
||||||
|
tag,
|
||||||
outboundOptions)
|
outboundOptions)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "parse outbound[", i, "]")
|
return nil, E.Cause(err, "parse outbound[", i, "]")
|
||||||
@@ -158,7 +126,7 @@ func New(ctx context.Context, options option.Options, platformInterface platform
|
|||||||
outbounds = append(outbounds, out)
|
outbounds = append(outbounds, out)
|
||||||
}
|
}
|
||||||
err = router.Initialize(inbounds, outbounds, func() adapter.Outbound {
|
err = router.Initialize(inbounds, outbounds, func() adapter.Outbound {
|
||||||
out, oErr := outbound.New(ctx, router, logFactory.NewLogger("outbound/direct"), option.Outbound{Type: "direct", Tag: "default"})
|
out, oErr := outbound.New(ctx, router, logFactory.NewLogger("outbound/direct"), "direct", option.Outbound{Type: "direct", Tag: "default"})
|
||||||
common.Must(oErr)
|
common.Must(oErr)
|
||||||
outbounds = append(outbounds, out)
|
outbounds = append(outbounds, out)
|
||||||
return out
|
return out
|
||||||
@@ -166,10 +134,16 @@ func New(ctx context.Context, options option.Options, platformInterface platform
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if options.PlatformInterface != nil {
|
||||||
|
err = options.PlatformInterface.Initialize(ctx, router)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "initialize platform interface")
|
||||||
|
}
|
||||||
|
}
|
||||||
preServices := make(map[string]adapter.Service)
|
preServices := make(map[string]adapter.Service)
|
||||||
postServices := make(map[string]adapter.Service)
|
postServices := make(map[string]adapter.Service)
|
||||||
if needClashAPI {
|
if needClashAPI {
|
||||||
clashServer, err := experimental.NewClashServer(router, observableLogFactory, common.PtrValueOrDefault(options.Experimental.ClashAPI))
|
clashServer, err := experimental.NewClashServer(ctx, router, logFactory.(log.ObservableFactory), common.PtrValueOrDefault(options.Experimental.ClashAPI))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "create clash api server")
|
return nil, E.Cause(err, "create clash api server")
|
||||||
}
|
}
|
||||||
@@ -191,7 +165,6 @@ func New(ctx context.Context, options option.Options, platformInterface platform
|
|||||||
createdAt: createdAt,
|
createdAt: createdAt,
|
||||||
logFactory: logFactory,
|
logFactory: logFactory,
|
||||||
logger: logFactory.Logger(),
|
logger: logFactory.Logger(),
|
||||||
logFile: logFile,
|
|
||||||
preServices: preServices,
|
preServices: preServices,
|
||||||
postServices: postServices,
|
postServices: postServices,
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}),
|
||||||
@@ -238,21 +211,23 @@ func (s *Box) Start() error {
|
|||||||
|
|
||||||
func (s *Box) preStart() error {
|
func (s *Box) preStart() error {
|
||||||
for serviceName, service := range s.preServices {
|
for serviceName, service := range s.preServices {
|
||||||
|
s.logger.Trace("pre-start ", serviceName)
|
||||||
err := adapter.PreStart(service)
|
err := adapter.PreStart(service)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return E.Cause(err, "pre-start ", serviceName)
|
return E.Cause(err, "pre-starting ", serviceName)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for i, out := range s.outbounds {
|
for i, out := range s.outbounds {
|
||||||
|
var tag string
|
||||||
|
if out.Tag() == "" {
|
||||||
|
tag = F.ToString(i)
|
||||||
|
} else {
|
||||||
|
tag = out.Tag()
|
||||||
|
}
|
||||||
if starter, isStarter := out.(common.Starter); isStarter {
|
if starter, isStarter := out.(common.Starter); isStarter {
|
||||||
|
s.logger.Trace("initializing outbound/", out.Type(), "[", tag, "]")
|
||||||
err := starter.Start()
|
err := starter.Start()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var tag string
|
|
||||||
if out.Tag() == "" {
|
|
||||||
tag = F.ToString(i)
|
|
||||||
} else {
|
|
||||||
tag = out.Tag()
|
|
||||||
}
|
|
||||||
return E.Cause(err, "initialize outbound/", out.Type(), "[", tag, "]")
|
return E.Cause(err, "initialize outbound/", out.Type(), "[", tag, "]")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,24 +241,27 @@ func (s *Box) start() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
for serviceName, service := range s.preServices {
|
for serviceName, service := range s.preServices {
|
||||||
|
s.logger.Trace("starting ", serviceName)
|
||||||
err = service.Start()
|
err = service.Start()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return E.Cause(err, "start ", serviceName)
|
return E.Cause(err, "start ", serviceName)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for i, in := range s.inbounds {
|
for i, in := range s.inbounds {
|
||||||
|
var tag string
|
||||||
|
if in.Tag() == "" {
|
||||||
|
tag = F.ToString(i)
|
||||||
|
} else {
|
||||||
|
tag = in.Tag()
|
||||||
|
}
|
||||||
|
s.logger.Trace("initializing inbound/", in.Type(), "[", tag, "]")
|
||||||
err = in.Start()
|
err = in.Start()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var tag string
|
|
||||||
if in.Tag() == "" {
|
|
||||||
tag = F.ToString(i)
|
|
||||||
} else {
|
|
||||||
tag = in.Tag()
|
|
||||||
}
|
|
||||||
return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]")
|
return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for serviceName, service := range s.postServices {
|
for serviceName, service := range s.postServices {
|
||||||
|
s.logger.Trace("starting ", service)
|
||||||
err = service.Start()
|
err = service.Start()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return E.Cause(err, "start ", serviceName)
|
return E.Cause(err, "start ", serviceName)
|
||||||
@@ -301,40 +279,41 @@ func (s *Box) Close() error {
|
|||||||
}
|
}
|
||||||
var errors error
|
var errors error
|
||||||
for serviceName, service := range s.postServices {
|
for serviceName, service := range s.postServices {
|
||||||
|
s.logger.Trace("closing ", serviceName)
|
||||||
errors = E.Append(errors, service.Close(), func(err error) error {
|
errors = E.Append(errors, service.Close(), func(err error) error {
|
||||||
return E.Cause(err, "close ", serviceName)
|
return E.Cause(err, "close ", serviceName)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
for i, in := range s.inbounds {
|
for i, in := range s.inbounds {
|
||||||
|
s.logger.Trace("closing inbound/", in.Type(), "[", i, "]")
|
||||||
errors = E.Append(errors, in.Close(), func(err error) error {
|
errors = E.Append(errors, in.Close(), func(err error) error {
|
||||||
return E.Cause(err, "close inbound/", in.Type(), "[", i, "]")
|
return E.Cause(err, "close inbound/", in.Type(), "[", i, "]")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
for i, out := range s.outbounds {
|
for i, out := range s.outbounds {
|
||||||
|
s.logger.Trace("closing outbound/", out.Type(), "[", i, "]")
|
||||||
errors = E.Append(errors, common.Close(out), func(err error) error {
|
errors = E.Append(errors, common.Close(out), func(err error) error {
|
||||||
return E.Cause(err, "close inbound/", out.Type(), "[", i, "]")
|
return E.Cause(err, "close outbound/", out.Type(), "[", i, "]")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
s.logger.Trace("closing router")
|
||||||
if err := common.Close(s.router); err != nil {
|
if err := common.Close(s.router); err != nil {
|
||||||
errors = E.Append(errors, err, func(err error) error {
|
errors = E.Append(errors, err, func(err error) error {
|
||||||
return E.Cause(err, "close router")
|
return E.Cause(err, "close router")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
for serviceName, service := range s.preServices {
|
for serviceName, service := range s.preServices {
|
||||||
|
s.logger.Trace("closing ", serviceName)
|
||||||
errors = E.Append(errors, service.Close(), func(err error) error {
|
errors = E.Append(errors, service.Close(), func(err error) error {
|
||||||
return E.Cause(err, "close ", serviceName)
|
return E.Cause(err, "close ", serviceName)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
s.logger.Trace("closing log factory")
|
||||||
if err := common.Close(s.logFactory); err != nil {
|
if err := common.Close(s.logFactory); err != nil {
|
||||||
errors = E.Append(errors, err, func(err error) error {
|
errors = E.Append(errors, err, func(err error) error {
|
||||||
return E.Cause(err, "close log factory")
|
return E.Cause(err, "close log factory")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
if s.logFile != nil {
|
|
||||||
errors = E.Append(errors, s.logFile.Close(), func(err error) error {
|
|
||||||
return E.Cause(err, "close log file")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return errors
|
return errors
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,10 @@ func check() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
instance, err := box.New(ctx, options, nil)
|
instance, err := box.New(box.Options{
|
||||||
|
Context: ctx,
|
||||||
|
Options: options,
|
||||||
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
instance.Close()
|
instance.Close()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
|
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
"github.com/gofrs/uuid/v5"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box"
|
"github.com/sagernet/sing-box"
|
||||||
"github.com/sagernet/sing-box/common/badjsonmerge"
|
"github.com/sagernet/sing-box/common/badjsonmerge"
|
||||||
@@ -127,7 +128,10 @@ func create() (*box.Box, context.CancelFunc, error) {
|
|||||||
options.Log.DisableColor = true
|
options.Log.DisableColor = true
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
instance, err := box.New(ctx, options, nil)
|
instance, err := box.New(box.Options{
|
||||||
|
Context: ctx,
|
||||||
|
Options: options,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
cancel()
|
cancel()
|
||||||
return nil, nil, E.Cause(err, "create service")
|
return nil, nil, E.Cause(err, "create service")
|
||||||
@@ -174,7 +178,10 @@ func run() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
cancel()
|
cancel()
|
||||||
|
closeCtx, closed := context.WithCancel(context.Background())
|
||||||
|
go closeMonitor(closeCtx)
|
||||||
instance.Close()
|
instance.Close()
|
||||||
|
closed()
|
||||||
if osSignal != syscall.SIGHUP {
|
if osSignal != syscall.SIGHUP {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -182,3 +189,13 @@ func run() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func closeMonitor(ctx context.Context) {
|
||||||
|
time.Sleep(3 * time.Second)
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
log.Fatal("sing-box did not close!")
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box"
|
"github.com/sagernet/sing-box"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
@@ -27,7 +25,7 @@ func createPreStartedClient() (*box.Box, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
instance, err := box.New(context.Background(), options, nil)
|
instance, err := box.New(box.Options{Options: options})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "create service")
|
return nil, E.Cause(err, "create service")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
//go:build debug
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
_ "net/http/pprof"
|
|
||||||
"runtime"
|
|
||||||
"runtime/debug"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/common/badjson"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
|
|
||||||
"github.com/dustin/go-humanize"
|
|
||||||
)
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
http.HandleFunc("/debug/gc", func(writer http.ResponseWriter, request *http.Request) {
|
|
||||||
writer.WriteHeader(http.StatusNoContent)
|
|
||||||
go debug.FreeOSMemory()
|
|
||||||
})
|
|
||||||
http.HandleFunc("/debug/memory", func(writer http.ResponseWriter, request *http.Request) {
|
|
||||||
var memStats runtime.MemStats
|
|
||||||
runtime.ReadMemStats(&memStats)
|
|
||||||
|
|
||||||
var memObject badjson.JSONObject
|
|
||||||
memObject.Put("heap", humanize.IBytes(memStats.HeapInuse))
|
|
||||||
memObject.Put("stack", humanize.IBytes(memStats.StackInuse))
|
|
||||||
memObject.Put("idle", humanize.IBytes(memStats.HeapIdle-memStats.HeapReleased))
|
|
||||||
memObject.Put("goroutines", runtime.NumGoroutine())
|
|
||||||
memObject.Put("rss", rusageMaxRSS())
|
|
||||||
|
|
||||||
encoder := json.NewEncoder(writer)
|
|
||||||
encoder.SetIndent("", " ")
|
|
||||||
encoder.Encode(memObject)
|
|
||||||
})
|
|
||||||
go func() {
|
|
||||||
err := http.ListenAndServe("0.0.0.0:8964", nil)
|
|
||||||
if err != nil {
|
|
||||||
log.Debug(err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
@@ -21,7 +21,7 @@ func TestMergeJSON(t *testing.T) {
|
|||||||
{
|
{
|
||||||
Type: C.RuleTypeDefault,
|
Type: C.RuleTypeDefault,
|
||||||
DefaultOptions: option.DefaultRule{
|
DefaultOptions: option.DefaultRule{
|
||||||
Network: N.NetworkTCP,
|
Network: []string{N.NetworkTCP},
|
||||||
Outbound: "direct",
|
Outbound: "direct",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -42,7 +42,7 @@ func TestMergeJSON(t *testing.T) {
|
|||||||
{
|
{
|
||||||
Type: C.RuleTypeDefault,
|
Type: C.RuleTypeDefault,
|
||||||
DefaultOptions: option.DefaultRule{
|
DefaultOptions: option.DefaultRule{
|
||||||
Network: N.NetworkUDP,
|
Network: []string{N.NetworkUDP},
|
||||||
Outbound: "direct",
|
Outbound: "direct",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//go:build go1.19 && !go1.20
|
//go:build go1.20 && !go1.21
|
||||||
|
|
||||||
package badtls
|
package badtls
|
||||||
|
|
||||||
@@ -14,39 +14,60 @@ import (
|
|||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/log"
|
||||||
"github.com/sagernet/sing/common"
|
"github.com/sagernet/sing/common"
|
||||||
"github.com/sagernet/sing/common/buf"
|
"github.com/sagernet/sing/common/buf"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
aTLS "github.com/sagernet/sing/common/tls"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Conn struct {
|
type Conn struct {
|
||||||
*tls.Conn
|
*tls.Conn
|
||||||
writer N.ExtendedWriter
|
writer N.ExtendedWriter
|
||||||
activeCall *int32
|
isHandshakeComplete *atomic.Bool
|
||||||
closeNotifySent *bool
|
activeCall *atomic.Int32
|
||||||
version *uint16
|
closeNotifySent *bool
|
||||||
rand io.Reader
|
version *uint16
|
||||||
halfAccess *sync.Mutex
|
rand io.Reader
|
||||||
halfError *error
|
halfAccess *sync.Mutex
|
||||||
cipher cipher.AEAD
|
halfError *error
|
||||||
explicitNonceLen int
|
cipher cipher.AEAD
|
||||||
halfPtr uintptr
|
explicitNonceLen int
|
||||||
halfSeq []byte
|
halfPtr uintptr
|
||||||
halfScratchBuf []byte
|
halfSeq []byte
|
||||||
|
halfScratchBuf []byte
|
||||||
}
|
}
|
||||||
|
|
||||||
func Create(conn *tls.Conn) (TLSConn, error) {
|
func TryCreate(conn aTLS.Conn) aTLS.Conn {
|
||||||
if !handshakeComplete(conn) {
|
tlsConn, ok := conn.(*tls.Conn)
|
||||||
|
if !ok {
|
||||||
|
return conn
|
||||||
|
}
|
||||||
|
badConn, err := Create(tlsConn)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn("initialize badtls: ", err)
|
||||||
|
return conn
|
||||||
|
}
|
||||||
|
return badConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func Create(conn *tls.Conn) (aTLS.Conn, error) {
|
||||||
|
rawConn := reflect.Indirect(reflect.ValueOf(conn))
|
||||||
|
rawIsHandshakeComplete := rawConn.FieldByName("isHandshakeComplete")
|
||||||
|
if !rawIsHandshakeComplete.IsValid() || rawIsHandshakeComplete.Kind() != reflect.Struct {
|
||||||
|
return nil, E.New("badtls: invalid isHandshakeComplete")
|
||||||
|
}
|
||||||
|
isHandshakeComplete := (*atomic.Bool)(unsafe.Pointer(rawIsHandshakeComplete.UnsafeAddr()))
|
||||||
|
if !isHandshakeComplete.Load() {
|
||||||
return nil, E.New("handshake not finished")
|
return nil, E.New("handshake not finished")
|
||||||
}
|
}
|
||||||
rawConn := reflect.Indirect(reflect.ValueOf(conn))
|
|
||||||
rawActiveCall := rawConn.FieldByName("activeCall")
|
rawActiveCall := rawConn.FieldByName("activeCall")
|
||||||
if !rawActiveCall.IsValid() || rawActiveCall.Kind() != reflect.Int32 {
|
if !rawActiveCall.IsValid() || rawActiveCall.Kind() != reflect.Struct {
|
||||||
return nil, E.New("badtls: invalid active call")
|
return nil, E.New("badtls: invalid active call")
|
||||||
}
|
}
|
||||||
activeCall := (*int32)(unsafe.Pointer(rawActiveCall.UnsafeAddr()))
|
activeCall := (*atomic.Int32)(unsafe.Pointer(rawActiveCall.UnsafeAddr()))
|
||||||
rawHalfConn := rawConn.FieldByName("out")
|
rawHalfConn := rawConn.FieldByName("out")
|
||||||
if !rawHalfConn.IsValid() || rawHalfConn.Kind() != reflect.Struct {
|
if !rawHalfConn.IsValid() || rawHalfConn.Kind() != reflect.Struct {
|
||||||
return nil, E.New("badtls: invalid half conn")
|
return nil, E.New("badtls: invalid half conn")
|
||||||
@@ -108,19 +129,20 @@ func Create(conn *tls.Conn) (TLSConn, error) {
|
|||||||
}
|
}
|
||||||
halfScratchBuf := rawHalfScratchBuf.Bytes()
|
halfScratchBuf := rawHalfScratchBuf.Bytes()
|
||||||
return &Conn{
|
return &Conn{
|
||||||
Conn: conn,
|
Conn: conn,
|
||||||
writer: bufio.NewExtendedWriter(conn.NetConn()),
|
writer: bufio.NewExtendedWriter(conn.NetConn()),
|
||||||
activeCall: activeCall,
|
isHandshakeComplete: isHandshakeComplete,
|
||||||
closeNotifySent: closeNotifySent,
|
activeCall: activeCall,
|
||||||
version: version,
|
closeNotifySent: closeNotifySent,
|
||||||
halfAccess: halfAccess,
|
version: version,
|
||||||
halfError: halfError,
|
halfAccess: halfAccess,
|
||||||
cipher: aeadCipher,
|
halfError: halfError,
|
||||||
explicitNonceLen: explicitNonceLen,
|
cipher: aeadCipher,
|
||||||
rand: randReader,
|
explicitNonceLen: explicitNonceLen,
|
||||||
halfPtr: rawHalfConn.UnsafeAddr(),
|
rand: randReader,
|
||||||
halfSeq: halfSeq,
|
halfPtr: rawHalfConn.UnsafeAddr(),
|
||||||
halfScratchBuf: halfScratchBuf,
|
halfSeq: halfSeq,
|
||||||
|
halfScratchBuf: halfScratchBuf,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,15 +152,15 @@ func (c *Conn) WriteBuffer(buffer *buf.Buffer) error {
|
|||||||
return common.Error(c.Write(buffer.Bytes()))
|
return common.Error(c.Write(buffer.Bytes()))
|
||||||
}
|
}
|
||||||
for {
|
for {
|
||||||
x := atomic.LoadInt32(c.activeCall)
|
x := c.activeCall.Load()
|
||||||
if x&1 != 0 {
|
if x&1 != 0 {
|
||||||
return net.ErrClosed
|
return net.ErrClosed
|
||||||
}
|
}
|
||||||
if atomic.CompareAndSwapInt32(c.activeCall, x, x+2) {
|
if c.activeCall.CompareAndSwap(x, x+2) {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
defer atomic.AddInt32(c.activeCall, -2)
|
defer c.activeCall.Add(-2)
|
||||||
c.halfAccess.Lock()
|
c.halfAccess.Lock()
|
||||||
defer c.halfAccess.Unlock()
|
defer c.halfAccess.Unlock()
|
||||||
if err := *c.halfError; err != nil {
|
if err := *c.halfError; err != nil {
|
||||||
@@ -186,6 +208,7 @@ func (c *Conn) WriteBuffer(buffer *buf.Buffer) error {
|
|||||||
binary.BigEndian.PutUint16(outBuf[3:], uint16(dataLen+c.explicitNonceLen+c.cipher.Overhead()))
|
binary.BigEndian.PutUint16(outBuf[3:], uint16(dataLen+c.explicitNonceLen+c.cipher.Overhead()))
|
||||||
}
|
}
|
||||||
incSeq(c.halfPtr)
|
incSeq(c.halfPtr)
|
||||||
|
log.Trace("badtls write ", buffer.Len())
|
||||||
return c.writer.WriteBuffer(buffer)
|
return c.writer.WriteBuffer(buffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//go:build !go1.19 || go1.20
|
//go:build !go1.19 || go1.21
|
||||||
|
|
||||||
package badtls
|
package badtls
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
package badtls
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"net"
|
|
||||||
)
|
|
||||||
|
|
||||||
type TLSConn interface {
|
|
||||||
net.Conn
|
|
||||||
HandshakeContext(ctx context.Context) error
|
|
||||||
ConnectionState() tls.ConnectionState
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
//go:build go1.19 && !go.1.20
|
//go:build go1.20 && !go.1.21
|
||||||
|
|
||||||
package badtls
|
package badtls
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
|
||||||
"reflect"
|
"reflect"
|
||||||
_ "unsafe"
|
_ "unsafe"
|
||||||
)
|
)
|
||||||
@@ -16,9 +15,6 @@ const (
|
|||||||
//go:linkname errShutdown crypto/tls.errShutdown
|
//go:linkname errShutdown crypto/tls.errShutdown
|
||||||
var errShutdown error
|
var errShutdown error
|
||||||
|
|
||||||
//go:linkname handshakeComplete crypto/tls.(*Conn).handshakeComplete
|
|
||||||
func handshakeComplete(conn *tls.Conn) bool
|
|
||||||
|
|
||||||
//go:linkname incSeq crypto/tls.(*halfConn).incSeq
|
//go:linkname incSeq crypto/tls.(*halfConn).incSeq
|
||||||
func incSeq(conn uintptr)
|
func incSeq(conn uintptr)
|
||||||
|
|
||||||
|
|||||||
114
common/badversion/version.go
Normal file
114
common/badversion/version.go
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
package badversion
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
F "github.com/sagernet/sing/common/format"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Version struct {
|
||||||
|
Major int
|
||||||
|
Minor int
|
||||||
|
Patch int
|
||||||
|
PreReleaseIdentifier string
|
||||||
|
PreReleaseVersion int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v Version) After(anotherVersion Version) bool {
|
||||||
|
if v.Major > anotherVersion.Major {
|
||||||
|
return true
|
||||||
|
} else if v.Major < anotherVersion.Major {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if v.Minor > anotherVersion.Minor {
|
||||||
|
return true
|
||||||
|
} else if v.Minor < anotherVersion.Minor {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if v.Patch > anotherVersion.Patch {
|
||||||
|
return true
|
||||||
|
} else if v.Patch < anotherVersion.Patch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if v.PreReleaseIdentifier == "" && anotherVersion.PreReleaseIdentifier != "" {
|
||||||
|
return true
|
||||||
|
} else if v.PreReleaseIdentifier != "" && anotherVersion.PreReleaseIdentifier == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if v.PreReleaseIdentifier != "" && anotherVersion.PreReleaseIdentifier != "" {
|
||||||
|
if v.PreReleaseIdentifier == "beta" && anotherVersion.PreReleaseIdentifier == "alpha" {
|
||||||
|
return true
|
||||||
|
} else if v.PreReleaseIdentifier == "alpha" && anotherVersion.PreReleaseIdentifier == "beta" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if v.PreReleaseVersion > anotherVersion.PreReleaseVersion {
|
||||||
|
return true
|
||||||
|
} else if v.PreReleaseVersion < anotherVersion.PreReleaseVersion {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v Version) String() string {
|
||||||
|
version := F.ToString(v.Major, ".", v.Minor, ".", v.Patch)
|
||||||
|
if v.PreReleaseIdentifier != "" {
|
||||||
|
version = F.ToString(version, "-", v.PreReleaseIdentifier, ".", v.PreReleaseVersion)
|
||||||
|
}
|
||||||
|
return version
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v Version) BadString() string {
|
||||||
|
version := F.ToString(v.Major, ".", v.Minor)
|
||||||
|
if v.Patch > 0 {
|
||||||
|
version = F.ToString(version, ".", v.Patch)
|
||||||
|
}
|
||||||
|
if v.PreReleaseIdentifier != "" {
|
||||||
|
version = F.ToString(version, "-", v.PreReleaseIdentifier)
|
||||||
|
if v.PreReleaseVersion > 0 {
|
||||||
|
version = F.ToString(version, v.PreReleaseVersion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return version
|
||||||
|
}
|
||||||
|
|
||||||
|
func Parse(versionName string) (version Version) {
|
||||||
|
if strings.HasPrefix(versionName, "v") {
|
||||||
|
versionName = versionName[1:]
|
||||||
|
}
|
||||||
|
if strings.Contains(versionName, "-") {
|
||||||
|
parts := strings.Split(versionName, "-")
|
||||||
|
versionName = parts[0]
|
||||||
|
identifier := parts[1]
|
||||||
|
if strings.Contains(identifier, ".") {
|
||||||
|
identifierParts := strings.Split(identifier, ".")
|
||||||
|
version.PreReleaseIdentifier = identifierParts[0]
|
||||||
|
if len(identifierParts) >= 2 {
|
||||||
|
version.PreReleaseVersion, _ = strconv.Atoi(identifierParts[1])
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if strings.HasPrefix(identifier, "alpha") {
|
||||||
|
version.PreReleaseIdentifier = "alpha"
|
||||||
|
version.PreReleaseVersion, _ = strconv.Atoi(identifier[5:])
|
||||||
|
} else if strings.HasPrefix(identifier, "beta") {
|
||||||
|
version.PreReleaseIdentifier = "beta"
|
||||||
|
version.PreReleaseVersion, _ = strconv.Atoi(identifier[4:])
|
||||||
|
} else {
|
||||||
|
version.PreReleaseIdentifier = identifier
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
versionElements := strings.Split(versionName, ".")
|
||||||
|
versionLen := len(versionElements)
|
||||||
|
if versionLen >= 1 {
|
||||||
|
version.Major, _ = strconv.Atoi(versionElements[0])
|
||||||
|
}
|
||||||
|
if versionLen >= 2 {
|
||||||
|
version.Minor, _ = strconv.Atoi(versionElements[1])
|
||||||
|
}
|
||||||
|
if versionLen >= 3 {
|
||||||
|
version.Patch, _ = strconv.Atoi(versionElements[2])
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
17
common/badversion/version_json.go
Normal file
17
common/badversion/version_json.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package badversion
|
||||||
|
|
||||||
|
import "github.com/sagernet/sing-box/common/json"
|
||||||
|
|
||||||
|
func (v Version) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(v.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (v *Version) UnmarshalJSON(data []byte) error {
|
||||||
|
var version string
|
||||||
|
err := json.Unmarshal(data, &version)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*v = Parse(version)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
18
common/badversion/version_test.go
Normal file
18
common/badversion/version_test.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package badversion
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCompareVersion(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
require.Equal(t, "1.3.0-beta.1", Parse("v1.3.0-beta1").String())
|
||||||
|
require.Equal(t, "1.3-beta1", Parse("v1.3.0-beta.1").BadString())
|
||||||
|
require.True(t, Parse("1.3.0").After(Parse("1.3-beta1")))
|
||||||
|
require.True(t, Parse("1.3.0").After(Parse("1.3.0-beta1")))
|
||||||
|
require.True(t, Parse("1.3.0-beta1").After(Parse("1.3.0-alpha1")))
|
||||||
|
require.True(t, Parse("1.3.1").After(Parse("1.3.0")))
|
||||||
|
require.True(t, Parse("1.4").After(Parse("1.3")))
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ type Conn struct {
|
|||||||
element *list.Element[io.Closer]
|
element *list.Element[io.Closer]
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewConn(conn net.Conn) (*Conn, error) {
|
func NewConn(conn net.Conn) (net.Conn, error) {
|
||||||
connAccess.Lock()
|
connAccess.Lock()
|
||||||
element := openConnection.PushBack(conn)
|
element := openConnection.PushBack(conn)
|
||||||
connAccess.Unlock()
|
connAccess.Unlock()
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ type PacketConn struct {
|
|||||||
element *list.Element[io.Closer]
|
element *list.Element[io.Closer]
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPacketConn(conn net.PacketConn) (*PacketConn, error) {
|
func NewPacketConn(conn net.PacketConn) (net.PacketConn, error) {
|
||||||
connAccess.Lock()
|
connAccess.Lock()
|
||||||
element := openConnection.PushBack(conn)
|
element := openConnection.PushBack(conn)
|
||||||
connAccess.Unlock()
|
connAccess.Unlock()
|
||||||
|
|||||||
@@ -14,10 +14,16 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func Count() int {
|
func Count() int {
|
||||||
|
if !Enabled {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
return openConnection.Len()
|
return openConnection.Len()
|
||||||
}
|
}
|
||||||
|
|
||||||
func List() []io.Closer {
|
func List() []io.Closer {
|
||||||
|
if !Enabled {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
connAccess.RLock()
|
connAccess.RLock()
|
||||||
defer connAccess.RUnlock()
|
defer connAccess.RUnlock()
|
||||||
connList := make([]io.Closer, 0, openConnection.Len())
|
connList := make([]io.Closer, 0, openConnection.Len())
|
||||||
@@ -28,6 +34,9 @@ func List() []io.Closer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Close() {
|
func Close() {
|
||||||
|
if !Enabled {
|
||||||
|
return
|
||||||
|
}
|
||||||
connAccess.Lock()
|
connAccess.Lock()
|
||||||
defer connAccess.Unlock()
|
defer connAccess.Unlock()
|
||||||
for element := openConnection.Front(); element != nil; element = element.Next() {
|
for element := openConnection.Front(); element != nil; element = element.Next() {
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
"github.com/sagernet/sing-box/common/dialer/conntrack"
|
"github.com/sagernet/sing-box/common/dialer/conntrack"
|
||||||
"github.com/sagernet/sing-box/common/warning"
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
C "github.com/sagernet/sing-box/constant"
|
||||||
"github.com/sagernet/sing-box/option"
|
"github.com/sagernet/sing-box/option"
|
||||||
"github.com/sagernet/sing/common/control"
|
"github.com/sagernet/sing/common/control"
|
||||||
@@ -17,41 +16,6 @@ import (
|
|||||||
"github.com/sagernet/tfo-go"
|
"github.com/sagernet/tfo-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
var warnBindInterfaceOnUnsupportedPlatform = warning.New(
|
|
||||||
func() bool {
|
|
||||||
return !(C.IsLinux || C.IsWindows || C.IsDarwin)
|
|
||||||
},
|
|
||||||
"outbound option `bind_interface` is only supported on Linux and Windows",
|
|
||||||
)
|
|
||||||
|
|
||||||
var warnRoutingMarkOnUnsupportedPlatform = warning.New(
|
|
||||||
func() bool {
|
|
||||||
return !C.IsLinux
|
|
||||||
},
|
|
||||||
"outbound option `routing_mark` is only supported on Linux",
|
|
||||||
)
|
|
||||||
|
|
||||||
var warnReuseAdderOnUnsupportedPlatform = warning.New(
|
|
||||||
func() bool {
|
|
||||||
return !(C.IsDarwin || C.IsDragonfly || C.IsFreebsd || C.IsLinux || C.IsNetbsd || C.IsOpenbsd || C.IsSolaris || C.IsWindows)
|
|
||||||
},
|
|
||||||
"outbound option `reuse_addr` is unsupported on current platform",
|
|
||||||
)
|
|
||||||
|
|
||||||
var warnProtectPathOnNonAndroid = warning.New(
|
|
||||||
func() bool {
|
|
||||||
return !C.IsAndroid
|
|
||||||
},
|
|
||||||
"outbound option `protect_path` is only supported on Android",
|
|
||||||
)
|
|
||||||
|
|
||||||
var warnTFOOnUnsupportedPlatform = warning.New(
|
|
||||||
func() bool {
|
|
||||||
return !(C.IsDarwin || C.IsFreebsd || C.IsLinux || C.IsWindows)
|
|
||||||
},
|
|
||||||
"outbound option `tcp_fast_open` is unsupported on current platform",
|
|
||||||
)
|
|
||||||
|
|
||||||
type DefaultDialer struct {
|
type DefaultDialer struct {
|
||||||
dialer4 tfo.Dialer
|
dialer4 tfo.Dialer
|
||||||
dialer6 tfo.Dialer
|
dialer6 tfo.Dialer
|
||||||
@@ -66,7 +30,6 @@ func NewDefault(router adapter.Router, options option.DialerOptions) *DefaultDia
|
|||||||
var dialer net.Dialer
|
var dialer net.Dialer
|
||||||
var listener net.ListenConfig
|
var listener net.ListenConfig
|
||||||
if options.BindInterface != "" {
|
if options.BindInterface != "" {
|
||||||
warnBindInterfaceOnUnsupportedPlatform.Check()
|
|
||||||
bindFunc := control.BindToInterface(router.InterfaceFinder(), options.BindInterface, -1)
|
bindFunc := control.BindToInterface(router.InterfaceFinder(), options.BindInterface, -1)
|
||||||
dialer.Control = control.Append(dialer.Control, bindFunc)
|
dialer.Control = control.Append(dialer.Control, bindFunc)
|
||||||
listener.Control = control.Append(listener.Control, bindFunc)
|
listener.Control = control.Append(listener.Control, bindFunc)
|
||||||
@@ -80,7 +43,6 @@ func NewDefault(router adapter.Router, options option.DialerOptions) *DefaultDia
|
|||||||
listener.Control = control.Append(listener.Control, bindFunc)
|
listener.Control = control.Append(listener.Control, bindFunc)
|
||||||
}
|
}
|
||||||
if options.RoutingMark != 0 {
|
if options.RoutingMark != 0 {
|
||||||
warnRoutingMarkOnUnsupportedPlatform.Check()
|
|
||||||
dialer.Control = control.Append(dialer.Control, control.RoutingMark(options.RoutingMark))
|
dialer.Control = control.Append(dialer.Control, control.RoutingMark(options.RoutingMark))
|
||||||
listener.Control = control.Append(listener.Control, control.RoutingMark(options.RoutingMark))
|
listener.Control = control.Append(listener.Control, control.RoutingMark(options.RoutingMark))
|
||||||
} else if router.DefaultMark() != 0 {
|
} else if router.DefaultMark() != 0 {
|
||||||
@@ -88,11 +50,9 @@ func NewDefault(router adapter.Router, options option.DialerOptions) *DefaultDia
|
|||||||
listener.Control = control.Append(listener.Control, control.RoutingMark(router.DefaultMark()))
|
listener.Control = control.Append(listener.Control, control.RoutingMark(router.DefaultMark()))
|
||||||
}
|
}
|
||||||
if options.ReuseAddr {
|
if options.ReuseAddr {
|
||||||
warnReuseAdderOnUnsupportedPlatform.Check()
|
|
||||||
listener.Control = control.Append(listener.Control, control.ReuseAddr())
|
listener.Control = control.Append(listener.Control, control.ReuseAddr())
|
||||||
}
|
}
|
||||||
if options.ProtectPath != "" {
|
if options.ProtectPath != "" {
|
||||||
warnProtectPathOnNonAndroid.Check()
|
|
||||||
dialer.Control = control.Append(dialer.Control, control.ProtectPath(options.ProtectPath))
|
dialer.Control = control.Append(dialer.Control, control.ProtectPath(options.ProtectPath))
|
||||||
listener.Control = control.Append(listener.Control, control.ProtectPath(options.ProtectPath))
|
listener.Control = control.Append(listener.Control, control.ProtectPath(options.ProtectPath))
|
||||||
}
|
}
|
||||||
@@ -101,9 +61,6 @@ func NewDefault(router adapter.Router, options option.DialerOptions) *DefaultDia
|
|||||||
} else {
|
} else {
|
||||||
dialer.Timeout = C.TCPTimeout
|
dialer.Timeout = C.TCPTimeout
|
||||||
}
|
}
|
||||||
if options.TCPFastOpen {
|
|
||||||
warnTFOOnUnsupportedPlatform.Check()
|
|
||||||
}
|
|
||||||
var udpFragment bool
|
var udpFragment bool
|
||||||
if options.UDPFragment != nil {
|
if options.UDPFragment != nil {
|
||||||
udpFragment = *options.UDPFragment
|
udpFragment = *options.UDPFragment
|
||||||
@@ -154,9 +111,9 @@ func (d *DefaultDialer) DialContext(ctx context.Context, network string, address
|
|||||||
switch N.NetworkName(network) {
|
switch N.NetworkName(network) {
|
||||||
case N.NetworkUDP:
|
case N.NetworkUDP:
|
||||||
if !address.IsIPv6() {
|
if !address.IsIPv6() {
|
||||||
return d.udpDialer4.DialContext(ctx, network, address.String())
|
return trackConn(d.udpDialer4.DialContext(ctx, network, address.String()))
|
||||||
} else {
|
} else {
|
||||||
return d.udpDialer6.DialContext(ctx, network, address.String())
|
return trackConn(d.udpDialer6.DialContext(ctx, network, address.String()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !address.IsIPv6() {
|
if !address.IsIPv6() {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
"github.com/sagernet/sing-dns"
|
"github.com/sagernet/sing-dns"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
@@ -68,11 +69,11 @@ func (d *ResolveDialer) ListenPacket(ctx context.Context, destination M.Socksadd
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
conn, err := N.ListenSerial(ctx, d.dialer, destination, addresses)
|
conn, destinationAddress, err := N.ListenSerial(ctx, d.dialer, destination, addresses)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return NewResolvePacketConn(ctx, d.router, d.strategy, conn), nil
|
return bufio.NewNATPacketConn(bufio.NewPacketConn(conn), M.SocksaddrFrom(destinationAddress, destination.Port), destination), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *ResolveDialer) Upstream() any {
|
func (d *ResolveDialer) Upstream() any {
|
||||||
|
|||||||
@@ -1,84 +0,0 @@
|
|||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
|
||||||
"github.com/sagernet/sing-dns"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
func NewResolvePacketConn(ctx context.Context, router adapter.Router, strategy dns.DomainStrategy, conn net.PacketConn) N.NetPacketConn {
|
|
||||||
if udpConn, ok := conn.(*net.UDPConn); ok {
|
|
||||||
return &ResolveUDPConn{udpConn, ctx, router, strategy}
|
|
||||||
} else {
|
|
||||||
return &ResolvePacketConn{conn, ctx, router, strategy}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type ResolveUDPConn struct {
|
|
||||||
*net.UDPConn
|
|
||||||
ctx context.Context
|
|
||||||
router adapter.Router
|
|
||||||
strategy dns.DomainStrategy
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *ResolveUDPConn) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) {
|
|
||||||
n, addr, err := w.ReadFromUDPAddrPort(buffer.FreeBytes())
|
|
||||||
if err != nil {
|
|
||||||
return M.Socksaddr{}, err
|
|
||||||
}
|
|
||||||
buffer.Truncate(n)
|
|
||||||
return M.SocksaddrFromNetIP(addr), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *ResolveUDPConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
|
||||||
defer buffer.Release()
|
|
||||||
if destination.IsFqdn() {
|
|
||||||
addresses, err := w.router.Lookup(w.ctx, destination.Fqdn, w.strategy)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return common.Error(w.UDPConn.WriteToUDPAddrPort(buffer.Bytes(), M.SocksaddrFrom(addresses[0], destination.Port).AddrPort()))
|
|
||||||
}
|
|
||||||
return common.Error(w.UDPConn.WriteToUDPAddrPort(buffer.Bytes(), destination.AddrPort()))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *ResolveUDPConn) Upstream() any {
|
|
||||||
return w.UDPConn
|
|
||||||
}
|
|
||||||
|
|
||||||
type ResolvePacketConn struct {
|
|
||||||
net.PacketConn
|
|
||||||
ctx context.Context
|
|
||||||
router adapter.Router
|
|
||||||
strategy dns.DomainStrategy
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *ResolvePacketConn) ReadPacket(buffer *buf.Buffer) (M.Socksaddr, error) {
|
|
||||||
_, addr, err := buffer.ReadPacketFrom(w)
|
|
||||||
if err != nil {
|
|
||||||
return M.Socksaddr{}, err
|
|
||||||
}
|
|
||||||
return M.SocksaddrFromNet(addr), err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *ResolvePacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error {
|
|
||||||
defer buffer.Release()
|
|
||||||
if destination.IsFqdn() {
|
|
||||||
addresses, err := w.router.Lookup(w.ctx, destination.Fqdn, w.strategy)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return common.Error(w.WriteTo(buffer.Bytes(), M.SocksaddrFrom(addresses[0], destination.Port).UDPAddr()))
|
|
||||||
}
|
|
||||||
return common.Error(w.WriteTo(buffer.Bytes(), destination.UDPAddr()))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *ResolvePacketConn) Upstream() any {
|
|
||||||
return w.PacketConn
|
|
||||||
}
|
|
||||||
@@ -27,7 +27,12 @@ type slowOpenConn struct {
|
|||||||
|
|
||||||
func DialSlowContext(dialer *tfo.Dialer, ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
func DialSlowContext(dialer *tfo.Dialer, ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
if dialer.DisableTFO || N.NetworkName(network) != N.NetworkTCP {
|
if dialer.DisableTFO || N.NetworkName(network) != N.NetworkTCP {
|
||||||
return dialer.DialContext(ctx, network, destination.String(), nil)
|
switch N.NetworkName(network) {
|
||||||
|
case N.NetworkTCP, N.NetworkUDP:
|
||||||
|
return dialer.Dialer.DialContext(ctx, network, destination.String())
|
||||||
|
default:
|
||||||
|
return dialer.Dialer.DialContext(ctx, network, destination.AddrString())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return &slowOpenConn{
|
return &slowOpenConn{
|
||||||
dialer: dialer,
|
dialer: dialer,
|
||||||
|
|||||||
@@ -28,9 +28,10 @@ type Client struct {
|
|||||||
maxConnections int
|
maxConnections int
|
||||||
minStreams int
|
minStreams int
|
||||||
maxStreams int
|
maxStreams int
|
||||||
|
paddingEnabled bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewClient(ctx context.Context, dialer N.Dialer, protocol Protocol, maxConnections int, minStreams int, maxStreams int) *Client {
|
func NewClient(ctx context.Context, dialer N.Dialer, protocol Protocol, maxConnections int, minStreams int, maxStreams int, paddingEnabled bool) (*Client, error) {
|
||||||
return &Client{
|
return &Client{
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
dialer: dialer,
|
dialer: dialer,
|
||||||
@@ -38,10 +39,11 @@ func NewClient(ctx context.Context, dialer N.Dialer, protocol Protocol, maxConne
|
|||||||
maxConnections: maxConnections,
|
maxConnections: maxConnections,
|
||||||
minStreams: minStreams,
|
minStreams: minStreams,
|
||||||
maxStreams: maxStreams,
|
maxStreams: maxStreams,
|
||||||
}
|
paddingEnabled: paddingEnabled,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewClientWithOptions(ctx context.Context, dialer N.Dialer, options option.MultiplexOptions) (N.Dialer, error) {
|
func NewClientWithOptions(ctx context.Context, dialer N.Dialer, options option.MultiplexOptions) (*Client, error) {
|
||||||
if !options.Enabled {
|
if !options.Enabled {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -52,7 +54,7 @@ func NewClientWithOptions(ctx context.Context, dialer N.Dialer, options option.M
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return NewClient(ctx, dialer, protocol, options.MaxConnections, options.MinStreams, options.MaxStreams), nil
|
return NewClient(ctx, dialer, protocol, options.MaxConnections, options.MinStreams, options.MaxStreams, options.Padding)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
func (c *Client) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
@@ -120,17 +122,16 @@ func (c *Client) offer() (abstractSession, error) {
|
|||||||
sessions = append(sessions, element.Value)
|
sessions = append(sessions, element.Value)
|
||||||
element = element.Next()
|
element = element.Next()
|
||||||
}
|
}
|
||||||
sLen := len(sessions)
|
session := common.MinBy(common.Filter(sessions, abstractSession.CanTakeNewRequest), abstractSession.NumStreams)
|
||||||
if sLen == 0 {
|
if session == nil {
|
||||||
return c.offerNew()
|
return c.offerNew()
|
||||||
}
|
}
|
||||||
session := common.MinBy(sessions, abstractSession.NumStreams)
|
|
||||||
numStreams := session.NumStreams()
|
numStreams := session.NumStreams()
|
||||||
if numStreams == 0 {
|
if numStreams == 0 {
|
||||||
return session, nil
|
return session, nil
|
||||||
}
|
}
|
||||||
if c.maxConnections > 0 {
|
if c.maxConnections > 0 {
|
||||||
if sLen >= c.maxConnections || numStreams < c.minStreams {
|
if len(sessions) >= c.maxConnections || numStreams < c.minStreams {
|
||||||
return session, nil
|
return session, nil
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -146,10 +147,19 @@ func (c *Client) offerNew() (abstractSession, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if vectorisedWriter, isVectorised := bufio.CreateVectorisedWriter(conn); isVectorised {
|
var version byte
|
||||||
conn = &vectorisedProtocolConn{protocolConn{Conn: conn, protocol: c.protocol}, vectorisedWriter}
|
if c.paddingEnabled {
|
||||||
|
version = Version1
|
||||||
} else {
|
} else {
|
||||||
conn = &protocolConn{Conn: conn, protocol: c.protocol}
|
version = Version0
|
||||||
|
}
|
||||||
|
conn = newProtocolConn(conn, Request{
|
||||||
|
Version: version,
|
||||||
|
Protocol: c.protocol,
|
||||||
|
PaddingEnabled: c.paddingEnabled,
|
||||||
|
})
|
||||||
|
if c.paddingEnabled {
|
||||||
|
conn = newPaddingConn(conn)
|
||||||
}
|
}
|
||||||
session, err := c.protocol.newClient(conn)
|
session, err := c.protocol.newClient(conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -159,6 +169,15 @@ func (c *Client) offerNew() (abstractSession, error) {
|
|||||||
return session, nil
|
return session, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *Client) Reset() {
|
||||||
|
c.access.Lock()
|
||||||
|
defer c.access.Unlock()
|
||||||
|
for _, session := range c.connections.Array() {
|
||||||
|
session.Close()
|
||||||
|
}
|
||||||
|
c.connections.Init()
|
||||||
|
}
|
||||||
|
|
||||||
func (c *Client) Close() error {
|
func (c *Client) Close() error {
|
||||||
c.access.Lock()
|
c.access.Lock()
|
||||||
defer c.access.Unlock()
|
defer c.access.Unlock()
|
||||||
@@ -205,7 +224,7 @@ func (c *ClientConn) Write(b []byte) (n int, err error) {
|
|||||||
Network: N.NetworkTCP,
|
Network: N.NetworkTCP,
|
||||||
Destination: c.destination,
|
Destination: c.destination,
|
||||||
}
|
}
|
||||||
_buffer := buf.StackNewSize(requestLen(request) + len(b))
|
_buffer := buf.StackNewSize(streamRequestLen(request) + len(b))
|
||||||
defer common.KeepAlive(_buffer)
|
defer common.KeepAlive(_buffer)
|
||||||
buffer := common.Dup(_buffer)
|
buffer := common.Dup(_buffer)
|
||||||
defer buffer.Release()
|
defer buffer.Release()
|
||||||
@@ -249,6 +268,10 @@ func (c *ClientConn) WriterReplaceable() bool {
|
|||||||
return c.requestWrite
|
return c.requestWrite
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *ClientConn) NeedAdditionalReadDeadline() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (c *ClientConn) Upstream() any {
|
func (c *ClientConn) Upstream() any {
|
||||||
return c.Conn
|
return c.Conn
|
||||||
}
|
}
|
||||||
@@ -295,7 +318,7 @@ func (c *ClientPacketConn) writeRequest(payload []byte) (n int, err error) {
|
|||||||
Network: N.NetworkUDP,
|
Network: N.NetworkUDP,
|
||||||
Destination: c.destination,
|
Destination: c.destination,
|
||||||
}
|
}
|
||||||
rLen := requestLen(request)
|
rLen := streamRequestLen(request)
|
||||||
if len(payload) > 0 {
|
if len(payload) > 0 {
|
||||||
rLen += 2 + len(payload)
|
rLen += 2 + len(payload)
|
||||||
}
|
}
|
||||||
@@ -377,6 +400,10 @@ func (c *ClientPacketConn) RemoteAddr() net.Addr {
|
|||||||
return c.destination.UDPAddr()
|
return c.destination.UDPAddr()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *ClientPacketConn) NeedAdditionalReadDeadline() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (c *ClientPacketConn) Upstream() any {
|
func (c *ClientPacketConn) Upstream() any {
|
||||||
return c.ExtendedConn
|
return c.ExtendedConn
|
||||||
}
|
}
|
||||||
@@ -413,7 +440,11 @@ func (c *ClientPacketAddrConn) ReadFrom(p []byte) (n int, addr net.Addr, err err
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
addr = destination.UDPAddr()
|
if destination.IsFqdn() {
|
||||||
|
addr = destination
|
||||||
|
} else {
|
||||||
|
addr = destination.UDPAddr()
|
||||||
|
}
|
||||||
var length uint16
|
var length uint16
|
||||||
err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
|
err = binary.Read(c.ExtendedConn, binary.BigEndian, &length)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -432,7 +463,7 @@ func (c *ClientPacketAddrConn) writeRequest(payload []byte, destination M.Socksa
|
|||||||
Destination: c.destination,
|
Destination: c.destination,
|
||||||
PacketAddr: true,
|
PacketAddr: true,
|
||||||
}
|
}
|
||||||
rLen := requestLen(request)
|
rLen := streamRequestLen(request)
|
||||||
if len(payload) > 0 {
|
if len(payload) > 0 {
|
||||||
rLen += M.SocksaddrSerializer.AddrPortLen(destination) + 2 + len(payload)
|
rLen += M.SocksaddrSerializer.AddrPortLen(destination) + 2 + len(payload)
|
||||||
}
|
}
|
||||||
@@ -514,6 +545,10 @@ func (c *ClientPacketAddrConn) FrontHeadroom() int {
|
|||||||
return 2 + M.MaxSocksaddrLength
|
return 2 + M.MaxSocksaddrLength
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *ClientPacketAddrConn) NeedAdditionalReadDeadline() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (c *ClientPacketAddrConn) Upstream() any {
|
func (c *ClientPacketAddrConn) Upstream() any {
|
||||||
return c.ExtendedConn
|
return c.ExtendedConn
|
||||||
}
|
}
|
||||||
|
|||||||
235
common/mux/h2mux.go
Normal file
235
common/mux/h2mux.go
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
package mux
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/transport/v2rayhttp"
|
||||||
|
"github.com/sagernet/sing/common/atomic"
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
|
||||||
|
"golang.org/x/net/http2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const idleTimeout = 30 * time.Second
|
||||||
|
|
||||||
|
var _ abstractSession = (*H2MuxServerSession)(nil)
|
||||||
|
|
||||||
|
type H2MuxServerSession struct {
|
||||||
|
server http2.Server
|
||||||
|
active atomic.Int32
|
||||||
|
conn net.Conn
|
||||||
|
inbound chan net.Conn
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewH2MuxServer(conn net.Conn) *H2MuxServerSession {
|
||||||
|
session := &H2MuxServerSession{
|
||||||
|
conn: conn,
|
||||||
|
inbound: make(chan net.Conn),
|
||||||
|
done: make(chan struct{}),
|
||||||
|
server: http2.Server{
|
||||||
|
IdleTimeout: idleTimeout,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
session.server.ServeConn(conn, &http2.ServeConnOpts{
|
||||||
|
Handler: session,
|
||||||
|
})
|
||||||
|
_ = session.Close()
|
||||||
|
}()
|
||||||
|
return session
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxServerSession) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||||
|
s.active.Add(1)
|
||||||
|
defer s.active.Add(-1)
|
||||||
|
writer.WriteHeader(http.StatusOK)
|
||||||
|
conn := newHTTP2Wrapper(&v2rayhttp.ServerHTTPConn{
|
||||||
|
HTTP2Conn: v2rayhttp.NewHTTPConn(request.Body, writer),
|
||||||
|
Flusher: writer.(http.Flusher),
|
||||||
|
})
|
||||||
|
s.inbound <- conn
|
||||||
|
select {
|
||||||
|
case <-conn.done:
|
||||||
|
case <-s.done:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxServerSession) Open() (net.Conn, error) {
|
||||||
|
return nil, os.ErrInvalid
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxServerSession) Accept() (net.Conn, error) {
|
||||||
|
select {
|
||||||
|
case conn := <-s.inbound:
|
||||||
|
return conn, nil
|
||||||
|
case <-s.done:
|
||||||
|
return nil, os.ErrClosed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxServerSession) NumStreams() int {
|
||||||
|
return int(s.active.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxServerSession) Close() error {
|
||||||
|
select {
|
||||||
|
case <-s.done:
|
||||||
|
default:
|
||||||
|
close(s.done)
|
||||||
|
}
|
||||||
|
return s.conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxServerSession) IsClosed() bool {
|
||||||
|
select {
|
||||||
|
case <-s.done:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxServerSession) CanTakeNewRequest() bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
type h2MuxConnWrapper struct {
|
||||||
|
N.ExtendedConn
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newHTTP2Wrapper(conn net.Conn) *h2MuxConnWrapper {
|
||||||
|
return &h2MuxConnWrapper{
|
||||||
|
ExtendedConn: bufio.NewExtendedConn(conn),
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *h2MuxConnWrapper) Write(p []byte) (n int, err error) {
|
||||||
|
select {
|
||||||
|
case <-w.done:
|
||||||
|
return 0, net.ErrClosed
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return w.ExtendedConn.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *h2MuxConnWrapper) WriteBuffer(buffer *buf.Buffer) error {
|
||||||
|
select {
|
||||||
|
case <-w.done:
|
||||||
|
return net.ErrClosed
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return w.ExtendedConn.WriteBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *h2MuxConnWrapper) Close() error {
|
||||||
|
select {
|
||||||
|
case <-w.done:
|
||||||
|
default:
|
||||||
|
close(w.done)
|
||||||
|
}
|
||||||
|
return w.ExtendedConn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *h2MuxConnWrapper) Upstream() any {
|
||||||
|
return w.ExtendedConn
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ abstractSession = (*H2MuxClientSession)(nil)
|
||||||
|
|
||||||
|
type H2MuxClientSession struct {
|
||||||
|
transport *http2.Transport
|
||||||
|
clientConn *http2.ClientConn
|
||||||
|
done chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewH2MuxClient(conn net.Conn) (*H2MuxClientSession, error) {
|
||||||
|
session := &H2MuxClientSession{
|
||||||
|
transport: &http2.Transport{
|
||||||
|
DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
|
||||||
|
return conn, nil
|
||||||
|
},
|
||||||
|
ReadIdleTimeout: idleTimeout,
|
||||||
|
},
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
session.transport.ConnPool = session
|
||||||
|
clientConn, err := session.transport.NewClientConn(conn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
session.clientConn = clientConn
|
||||||
|
return session, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxClientSession) GetClientConn(req *http.Request, addr string) (*http2.ClientConn, error) {
|
||||||
|
return s.clientConn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxClientSession) MarkDead(conn *http2.ClientConn) {
|
||||||
|
s.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxClientSession) Open() (net.Conn, error) {
|
||||||
|
pipeInReader, pipeInWriter := io.Pipe()
|
||||||
|
request := &http.Request{
|
||||||
|
Method: http.MethodConnect,
|
||||||
|
Body: pipeInReader,
|
||||||
|
URL: &url.URL{Scheme: "https", Host: "localhost"},
|
||||||
|
}
|
||||||
|
conn := v2rayhttp.NewLateHTTPConn(pipeInWriter)
|
||||||
|
go func() {
|
||||||
|
response, err := s.transport.RoundTrip(request)
|
||||||
|
if err != nil {
|
||||||
|
conn.Setup(nil, err)
|
||||||
|
} else if response.StatusCode != 200 {
|
||||||
|
response.Body.Close()
|
||||||
|
conn.Setup(nil, E.New("unexpected status: ", response.StatusCode, " ", response.Status))
|
||||||
|
} else {
|
||||||
|
conn.Setup(response.Body, nil)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxClientSession) Accept() (net.Conn, error) {
|
||||||
|
return nil, os.ErrInvalid
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxClientSession) NumStreams() int {
|
||||||
|
return s.clientConn.State().StreamsActive
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxClientSession) Close() error {
|
||||||
|
select {
|
||||||
|
case <-s.done:
|
||||||
|
default:
|
||||||
|
close(s.done)
|
||||||
|
}
|
||||||
|
return s.clientConn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxClientSession) IsClosed() bool {
|
||||||
|
select {
|
||||||
|
case <-s.done:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return s.clientConn.State().Closed
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *H2MuxClientSession) CanTakeNewRequest() bool {
|
||||||
|
return s.clientConn.CanTakeNewRequest()
|
||||||
|
}
|
||||||
240
common/mux/padding.go
Normal file
240
common/mux/padding.go
Normal file
@@ -0,0 +1,240 @@
|
|||||||
|
package mux
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"io"
|
||||||
|
"math/rand"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
"github.com/sagernet/sing/common/rw"
|
||||||
|
)
|
||||||
|
|
||||||
|
const kFirstPaddings = 16
|
||||||
|
|
||||||
|
type paddingConn struct {
|
||||||
|
N.ExtendedConn
|
||||||
|
writer N.VectorisedWriter
|
||||||
|
readPadding int
|
||||||
|
writePadding int
|
||||||
|
readRemaining int
|
||||||
|
paddingRemaining int
|
||||||
|
}
|
||||||
|
|
||||||
|
func newPaddingConn(conn net.Conn) net.Conn {
|
||||||
|
writer, isVectorised := bufio.CreateVectorisedWriter(conn)
|
||||||
|
if isVectorised {
|
||||||
|
return &vectorisedPaddingConn{
|
||||||
|
paddingConn{
|
||||||
|
ExtendedConn: bufio.NewExtendedConn(conn),
|
||||||
|
writer: bufio.NewVectorisedWriter(conn),
|
||||||
|
},
|
||||||
|
writer,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return &paddingConn{
|
||||||
|
ExtendedConn: bufio.NewExtendedConn(conn),
|
||||||
|
writer: bufio.NewVectorisedWriter(conn),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *paddingConn) Read(p []byte) (n int, err error) {
|
||||||
|
if c.readRemaining > 0 {
|
||||||
|
if len(p) > c.readRemaining {
|
||||||
|
p = p[:c.readRemaining]
|
||||||
|
}
|
||||||
|
n, err = c.ExtendedConn.Read(p)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.readRemaining -= n
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if c.paddingRemaining > 0 {
|
||||||
|
err = rw.SkipN(c.ExtendedConn, c.paddingRemaining)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.paddingRemaining = 0
|
||||||
|
}
|
||||||
|
if c.readPadding < kFirstPaddings {
|
||||||
|
var paddingHdr []byte
|
||||||
|
if len(p) >= 4 {
|
||||||
|
paddingHdr = p[:4]
|
||||||
|
} else {
|
||||||
|
_paddingHdr := make([]byte, 4)
|
||||||
|
defer common.KeepAlive(_paddingHdr)
|
||||||
|
paddingHdr = common.Dup(_paddingHdr)
|
||||||
|
}
|
||||||
|
_, err = io.ReadFull(c.ExtendedConn, paddingHdr)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
originalDataSize := int(binary.BigEndian.Uint16(paddingHdr[:2]))
|
||||||
|
paddingLen := int(binary.BigEndian.Uint16(paddingHdr[2:]))
|
||||||
|
if len(p) > originalDataSize {
|
||||||
|
p = p[:originalDataSize]
|
||||||
|
}
|
||||||
|
n, err = c.ExtendedConn.Read(p)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.readPadding++
|
||||||
|
c.readRemaining = originalDataSize - n
|
||||||
|
c.paddingRemaining = paddingLen
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return c.ExtendedConn.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *paddingConn) Write(p []byte) (n int, err error) {
|
||||||
|
for pLen := len(p); pLen > 0; {
|
||||||
|
var data []byte
|
||||||
|
if pLen > 65535 {
|
||||||
|
data = p[:65535]
|
||||||
|
p = p[65535:]
|
||||||
|
pLen -= 65535
|
||||||
|
} else {
|
||||||
|
data = p
|
||||||
|
pLen = 0
|
||||||
|
}
|
||||||
|
var writeN int
|
||||||
|
writeN, err = c.write(data)
|
||||||
|
n += writeN
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *paddingConn) write(p []byte) (n int, err error) {
|
||||||
|
if c.writePadding < kFirstPaddings {
|
||||||
|
paddingLen := 256 + rand.Intn(512)
|
||||||
|
_buffer := buf.StackNewSize(4 + len(p) + paddingLen)
|
||||||
|
defer common.KeepAlive(_buffer)
|
||||||
|
buffer := common.Dup(_buffer)
|
||||||
|
defer buffer.Release()
|
||||||
|
header := buffer.Extend(4)
|
||||||
|
binary.BigEndian.PutUint16(header[:2], uint16(len(p)))
|
||||||
|
binary.BigEndian.PutUint16(header[2:], uint16(paddingLen))
|
||||||
|
common.Must1(buffer.Write(p))
|
||||||
|
buffer.Extend(paddingLen)
|
||||||
|
_, err = c.ExtendedConn.Write(buffer.Bytes())
|
||||||
|
if err == nil {
|
||||||
|
n = len(p)
|
||||||
|
}
|
||||||
|
c.writePadding++
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return c.ExtendedConn.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *paddingConn) ReadBuffer(buffer *buf.Buffer) error {
|
||||||
|
p := buffer.FreeBytes()
|
||||||
|
if c.readRemaining > 0 {
|
||||||
|
if len(p) > c.readRemaining {
|
||||||
|
p = p[:c.readRemaining]
|
||||||
|
}
|
||||||
|
n, err := c.ExtendedConn.Read(p)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.readRemaining -= n
|
||||||
|
buffer.Truncate(n)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if c.paddingRemaining > 0 {
|
||||||
|
err := rw.SkipN(c.ExtendedConn, c.paddingRemaining)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.paddingRemaining = 0
|
||||||
|
}
|
||||||
|
if c.readPadding < kFirstPaddings {
|
||||||
|
var paddingHdr []byte
|
||||||
|
if len(p) >= 4 {
|
||||||
|
paddingHdr = p[:4]
|
||||||
|
} else {
|
||||||
|
_paddingHdr := make([]byte, 4)
|
||||||
|
defer common.KeepAlive(_paddingHdr)
|
||||||
|
paddingHdr = common.Dup(_paddingHdr)
|
||||||
|
}
|
||||||
|
_, err := io.ReadFull(c.ExtendedConn, paddingHdr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
originalDataSize := int(binary.BigEndian.Uint16(paddingHdr[:2]))
|
||||||
|
paddingLen := int(binary.BigEndian.Uint16(paddingHdr[2:]))
|
||||||
|
|
||||||
|
if len(p) > originalDataSize {
|
||||||
|
p = p[:originalDataSize]
|
||||||
|
}
|
||||||
|
n, err := c.ExtendedConn.Read(p)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.readPadding++
|
||||||
|
c.readRemaining = originalDataSize - n
|
||||||
|
c.paddingRemaining = paddingLen
|
||||||
|
buffer.Truncate(n)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.ExtendedConn.ReadBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *paddingConn) WriteBuffer(buffer *buf.Buffer) error {
|
||||||
|
if c.writePadding < kFirstPaddings {
|
||||||
|
bufferLen := buffer.Len()
|
||||||
|
if bufferLen > 65535 {
|
||||||
|
return common.Error(c.Write(buffer.Bytes()))
|
||||||
|
}
|
||||||
|
paddingLen := 256 + rand.Intn(512)
|
||||||
|
header := buffer.ExtendHeader(4)
|
||||||
|
binary.BigEndian.PutUint16(header[:2], uint16(bufferLen))
|
||||||
|
binary.BigEndian.PutUint16(header[2:], uint16(paddingLen))
|
||||||
|
buffer.Extend(paddingLen)
|
||||||
|
c.writePadding++
|
||||||
|
}
|
||||||
|
return c.ExtendedConn.WriteBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *paddingConn) FrontHeadroom() int {
|
||||||
|
return 4 + 256 + 1024
|
||||||
|
}
|
||||||
|
|
||||||
|
type vectorisedPaddingConn struct {
|
||||||
|
paddingConn
|
||||||
|
writer N.VectorisedWriter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *vectorisedPaddingConn) WriteVectorised(buffers []*buf.Buffer) error {
|
||||||
|
if c.writePadding < kFirstPaddings {
|
||||||
|
bufferLen := buf.LenMulti(buffers)
|
||||||
|
if bufferLen > 65535 {
|
||||||
|
defer buf.ReleaseMulti(buffers)
|
||||||
|
for _, buffer := range buffers {
|
||||||
|
_, err := c.Write(buffer.Bytes())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
paddingLen := 256 + rand.Intn(512)
|
||||||
|
header := buf.NewSize(4)
|
||||||
|
common.Must(
|
||||||
|
binary.Write(header, binary.BigEndian, uint16(bufferLen)),
|
||||||
|
binary.Write(header, binary.BigEndian, uint16(paddingLen)),
|
||||||
|
)
|
||||||
|
c.writePadding++
|
||||||
|
padding := buf.NewSize(paddingLen)
|
||||||
|
padding.Extend(paddingLen)
|
||||||
|
buffers = append(append([]*buf.Buffer{header}, buffers...), padding)
|
||||||
|
}
|
||||||
|
return c.writer.WriteVectorised(buffers)
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package mux
|
|||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"io"
|
"io"
|
||||||
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
C "github.com/sagernet/sing-box/constant"
|
||||||
@@ -25,6 +26,7 @@ var Destination = M.Socksaddr{
|
|||||||
const (
|
const (
|
||||||
ProtocolSMux Protocol = iota
|
ProtocolSMux Protocol = iota
|
||||||
ProtocolYAMux
|
ProtocolYAMux
|
||||||
|
ProtocolH2Mux
|
||||||
)
|
)
|
||||||
|
|
||||||
type Protocol byte
|
type Protocol byte
|
||||||
@@ -35,8 +37,10 @@ func ParseProtocol(name string) (Protocol, error) {
|
|||||||
return ProtocolSMux, nil
|
return ProtocolSMux, nil
|
||||||
case "yamux":
|
case "yamux":
|
||||||
return ProtocolYAMux, nil
|
return ProtocolYAMux, nil
|
||||||
|
case "h2mux":
|
||||||
|
return ProtocolH2Mux, nil
|
||||||
default:
|
default:
|
||||||
return ProtocolYAMux, E.New("unknown multiplex protocol: ", name)
|
return ProtocolSMux, E.New("unknown multiplex protocol: ", name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,7 +53,13 @@ func (p Protocol) newServer(conn net.Conn) (abstractSession, error) {
|
|||||||
}
|
}
|
||||||
return &smuxSession{session}, nil
|
return &smuxSession{session}, nil
|
||||||
case ProtocolYAMux:
|
case ProtocolYAMux:
|
||||||
return yamux.Server(conn, yaMuxConfig())
|
session, err := yamux.Server(conn, yaMuxConfig())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &yamuxSession{session}, nil
|
||||||
|
case ProtocolH2Mux:
|
||||||
|
return NewH2MuxServer(conn), nil
|
||||||
default:
|
default:
|
||||||
panic("unknown protocol")
|
panic("unknown protocol")
|
||||||
}
|
}
|
||||||
@@ -64,7 +74,13 @@ func (p Protocol) newClient(conn net.Conn) (abstractSession, error) {
|
|||||||
}
|
}
|
||||||
return &smuxSession{session}, nil
|
return &smuxSession{session}, nil
|
||||||
case ProtocolYAMux:
|
case ProtocolYAMux:
|
||||||
return yamux.Client(conn, yaMuxConfig())
|
session, err := yamux.Client(conn, yaMuxConfig())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &yamuxSession{session}, nil
|
||||||
|
case ProtocolH2Mux:
|
||||||
|
return NewH2MuxClient(conn)
|
||||||
default:
|
default:
|
||||||
panic("unknown protocol")
|
panic("unknown protocol")
|
||||||
}
|
}
|
||||||
@@ -90,17 +106,22 @@ func (p Protocol) String() string {
|
|||||||
return "smux"
|
return "smux"
|
||||||
case ProtocolYAMux:
|
case ProtocolYAMux:
|
||||||
return "yamux"
|
return "yamux"
|
||||||
|
case ProtocolH2Mux:
|
||||||
|
return "h2mux"
|
||||||
default:
|
default:
|
||||||
return "unknown"
|
return "unknown"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
version0 = 0
|
Version0 = iota
|
||||||
|
Version1
|
||||||
)
|
)
|
||||||
|
|
||||||
type Request struct {
|
type Request struct {
|
||||||
Protocol Protocol
|
Version byte
|
||||||
|
Protocol Protocol
|
||||||
|
PaddingEnabled bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func ReadRequest(reader io.Reader) (*Request, error) {
|
func ReadRequest(reader io.Reader) (*Request, error) {
|
||||||
@@ -108,22 +129,60 @@ func ReadRequest(reader io.Reader) (*Request, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if version != version0 {
|
if version < Version0 || version > Version1 {
|
||||||
return nil, E.New("unsupported version: ", version)
|
return nil, E.New("unsupported version: ", version)
|
||||||
}
|
}
|
||||||
protocol, err := rw.ReadByte(reader)
|
protocol, err := rw.ReadByte(reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if protocol > byte(ProtocolYAMux) {
|
var paddingEnabled bool
|
||||||
return nil, E.New("unsupported protocol: ", protocol)
|
if version == Version1 {
|
||||||
|
err = binary.Read(reader, binary.BigEndian, &paddingEnabled)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if paddingEnabled {
|
||||||
|
var paddingLen uint16
|
||||||
|
err = binary.Read(reader, binary.BigEndian, &paddingLen)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err = rw.SkipN(reader, int(paddingLen))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return &Request{Protocol: Protocol(protocol)}, nil
|
return &Request{Version: version, Protocol: Protocol(protocol), PaddingEnabled: paddingEnabled}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func EncodeRequest(buffer *buf.Buffer, request Request) {
|
func EncodeRequest(request Request, payload []byte) *buf.Buffer {
|
||||||
buffer.WriteByte(version0)
|
var requestLen int
|
||||||
buffer.WriteByte(byte(request.Protocol))
|
requestLen += 2
|
||||||
|
var paddingLen uint16
|
||||||
|
if request.Version == Version1 {
|
||||||
|
requestLen += 1
|
||||||
|
if request.PaddingEnabled {
|
||||||
|
requestLen += 2
|
||||||
|
paddingLen = uint16(256 + rand.Intn(512))
|
||||||
|
requestLen += int(paddingLen)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buffer := buf.NewSize(requestLen + len(payload))
|
||||||
|
common.Must(
|
||||||
|
buffer.WriteByte(request.Version),
|
||||||
|
buffer.WriteByte(byte(request.Protocol)),
|
||||||
|
)
|
||||||
|
if request.Version == Version1 {
|
||||||
|
common.Must(binary.Write(buffer, binary.BigEndian, request.PaddingEnabled))
|
||||||
|
if request.PaddingEnabled {
|
||||||
|
common.Must(binary.Write(buffer, binary.BigEndian, paddingLen))
|
||||||
|
buffer.Extend(int(paddingLen))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
common.Must1(buffer.Write(payload))
|
||||||
|
return buffer
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -160,7 +219,7 @@ func ReadStreamRequest(reader io.Reader) (*StreamRequest, error) {
|
|||||||
return &StreamRequest{network, destination, udpAddr}, nil
|
return &StreamRequest{network, destination, udpAddr}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func requestLen(request StreamRequest) int {
|
func streamRequestLen(request StreamRequest) int {
|
||||||
var rLen int
|
var rLen int
|
||||||
rLen += 1 // version
|
rLen += 1 // version
|
||||||
rLen += 2 // flags
|
rLen += 2 // flags
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ func NewConnection(ctx context.Context, router adapter.Router, errorHandler E.Ha
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if request.PaddingEnabled {
|
||||||
|
conn = newPaddingConn(conn)
|
||||||
|
}
|
||||||
session, err := request.Protocol.newServer(conn)
|
session, err := request.Protocol.newServer(conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -131,6 +134,10 @@ func (c *ServerConn) FrontHeadroom() int {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *ServerConn) NeedAdditionalReadDeadline() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (c *ServerConn) Upstream() any {
|
func (c *ServerConn) Upstream() any {
|
||||||
return c.ExtendedConn
|
return c.ExtendedConn
|
||||||
}
|
}
|
||||||
@@ -183,6 +190,10 @@ func (c *ServerPacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksad
|
|||||||
return c.ExtendedConn.WriteBuffer(buffer)
|
return c.ExtendedConn.WriteBuffer(buffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *ServerPacketConn) NeedAdditionalReadDeadline() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (c *ServerPacketConn) Upstream() any {
|
func (c *ServerPacketConn) Upstream() any {
|
||||||
return c.ExtendedConn
|
return c.ExtendedConn
|
||||||
}
|
}
|
||||||
@@ -245,6 +256,10 @@ func (c *ServerPacketAddrConn) WritePacket(buffer *buf.Buffer, destination M.Soc
|
|||||||
return c.ExtendedConn.WriteBuffer(buffer)
|
return c.ExtendedConn.WriteBuffer(buffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *ServerPacketAddrConn) NeedAdditionalReadDeadline() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (c *ServerPacketAddrConn) Upstream() any {
|
func (c *ServerPacketAddrConn) Upstream() any {
|
||||||
return c.ExtendedConn
|
return c.ExtendedConn
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,11 +4,12 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
"github.com/sagernet/sing/common/buf"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
"github.com/sagernet/smux"
|
"github.com/sagernet/smux"
|
||||||
|
|
||||||
|
"github.com/hashicorp/yamux"
|
||||||
)
|
)
|
||||||
|
|
||||||
type abstractSession interface {
|
type abstractSession interface {
|
||||||
@@ -17,6 +18,7 @@ type abstractSession interface {
|
|||||||
NumStreams() int
|
NumStreams() int
|
||||||
Close() error
|
Close() error
|
||||||
IsClosed() bool
|
IsClosed() bool
|
||||||
|
CanTakeNewRequest() bool
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ abstractSession = (*smuxSession)(nil)
|
var _ abstractSession = (*smuxSession)(nil)
|
||||||
@@ -33,25 +35,49 @@ func (s *smuxSession) Accept() (net.Conn, error) {
|
|||||||
return s.AcceptStream()
|
return s.AcceptStream()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *smuxSession) CanTakeNewRequest() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
type yamuxSession struct {
|
||||||
|
*yamux.Session
|
||||||
|
}
|
||||||
|
|
||||||
|
func (y *yamuxSession) CanTakeNewRequest() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
type protocolConn struct {
|
type protocolConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
protocol Protocol
|
request Request
|
||||||
protocolWritten bool
|
protocolWritten bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newProtocolConn(conn net.Conn, request Request) net.Conn {
|
||||||
|
writer, isVectorised := bufio.CreateVectorisedWriter(conn)
|
||||||
|
if isVectorised {
|
||||||
|
return &vectorisedProtocolConn{
|
||||||
|
protocolConn{
|
||||||
|
Conn: conn,
|
||||||
|
request: request,
|
||||||
|
},
|
||||||
|
writer,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return &protocolConn{
|
||||||
|
Conn: conn,
|
||||||
|
request: request,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (c *protocolConn) Write(p []byte) (n int, err error) {
|
func (c *protocolConn) Write(p []byte) (n int, err error) {
|
||||||
if c.protocolWritten {
|
if c.protocolWritten {
|
||||||
return c.Conn.Write(p)
|
return c.Conn.Write(p)
|
||||||
}
|
}
|
||||||
_buffer := buf.StackNewSize(2 + len(p))
|
buffer := EncodeRequest(c.request, p)
|
||||||
defer common.KeepAlive(_buffer)
|
|
||||||
buffer := common.Dup(_buffer)
|
|
||||||
defer buffer.Release()
|
|
||||||
EncodeRequest(buffer, Request{
|
|
||||||
Protocol: c.protocol,
|
|
||||||
})
|
|
||||||
common.Must(common.Error(buffer.Write(p)))
|
|
||||||
n, err = c.Conn.Write(buffer.Bytes())
|
n, err = c.Conn.Write(buffer.Bytes())
|
||||||
|
buffer.Release()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
n--
|
n--
|
||||||
}
|
}
|
||||||
@@ -72,20 +98,14 @@ func (c *protocolConn) Upstream() any {
|
|||||||
|
|
||||||
type vectorisedProtocolConn struct {
|
type vectorisedProtocolConn struct {
|
||||||
protocolConn
|
protocolConn
|
||||||
N.VectorisedWriter
|
writer N.VectorisedWriter
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *vectorisedProtocolConn) WriteVectorised(buffers []*buf.Buffer) error {
|
func (c *vectorisedProtocolConn) WriteVectorised(buffers []*buf.Buffer) error {
|
||||||
if c.protocolWritten {
|
if c.protocolWritten {
|
||||||
return c.VectorisedWriter.WriteVectorised(buffers)
|
return c.writer.WriteVectorised(buffers)
|
||||||
}
|
}
|
||||||
c.protocolWritten = true
|
c.protocolWritten = true
|
||||||
_buffer := buf.StackNewSize(2)
|
buffer := EncodeRequest(c.request, nil)
|
||||||
defer common.KeepAlive(_buffer)
|
return c.writer.WriteVectorised(append([]*buf.Buffer{buffer}, buffers...))
|
||||||
buffer := common.Dup(_buffer)
|
|
||||||
defer buffer.Release()
|
|
||||||
EncodeRequest(buffer, Request{
|
|
||||||
Protocol: c.protocol,
|
|
||||||
})
|
|
||||||
return c.VectorisedWriter.WriteVectorised(append([]*buf.Buffer{buffer}, buffers...))
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,10 +3,12 @@ package process
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"os/user"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
"github.com/sagernet/sing-tun"
|
"github.com/sagernet/sing-tun"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
F "github.com/sagernet/sing/common/format"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Searcher interface {
|
type Searcher interface {
|
||||||
@@ -28,5 +30,15 @@ type Info struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func FindProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
|
func FindProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
|
||||||
return findProcessInfo(searcher, ctx, network, source, destination)
|
info, err := searcher.FindProcessInfo(ctx, network, source, destination)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if info.UserId != -1 {
|
||||||
|
osUser, _ := user.LookupId(F.ToString(info.UserId))
|
||||||
|
if osUser != nil {
|
||||||
|
info.User = osUser.Username
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return info, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
//go:build linux && !android
|
|
||||||
|
|
||||||
package process
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/netip"
|
|
||||||
"os/user"
|
|
||||||
|
|
||||||
F "github.com/sagernet/sing/common/format"
|
|
||||||
)
|
|
||||||
|
|
||||||
func findProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
|
|
||||||
info, err := searcher.FindProcessInfo(ctx, network, source, destination)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if info.UserId != -1 {
|
|
||||||
osUser, _ := user.LookupId(F.ToString(info.UserId))
|
|
||||||
if osUser != nil {
|
|
||||||
info.User = osUser.Username
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return info, nil
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
//go:build !linux || android
|
|
||||||
|
|
||||||
package process
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/netip"
|
|
||||||
)
|
|
||||||
|
|
||||||
func findProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
|
|
||||||
return searcher.FindProcessInfo(ctx, network, source, destination)
|
|
||||||
}
|
|
||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
C "github.com/sagernet/sing-box/constant"
|
C "github.com/sagernet/sing-box/constant"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
"github.com/sagernet/sing/protocol/http"
|
"github.com/sagernet/sing/protocol/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -15,5 +16,5 @@ func HTTPHost(ctx context.Context, reader io.Reader) (*adapter.InboundContext, e
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &adapter.InboundContext{Protocol: C.ProtocolHTTP, Domain: request.Host}, nil
|
return &adapter.InboundContext{Protocol: C.ProtocolHTTP, Domain: M.ParseSocksaddr(request.Host).AddrString()}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
27
common/sniff/http_test.go
Normal file
27
common/sniff/http_test.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package sniff_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/common/sniff"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSniffHTTP1(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
pkt := "GET / HTTP/1.1\r\nHost: www.google.com\r\nAccept: */*\r\n\r\n"
|
||||||
|
metadata, err := sniff.HTTPHost(context.Background(), strings.NewReader(pkt))
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, metadata.Domain, "www.google.com")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSniffHTTP1WithPort(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
pkt := "GET / HTTP/1.1\r\nHost: www.gov.cn:8080\r\nAccept: */*\r\n\r\n"
|
||||||
|
metadata, err := sniff.HTTPHost(context.Background(), strings.NewReader(pkt))
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Equal(t, metadata.Domain, "www.gov.cn")
|
||||||
|
}
|
||||||
@@ -24,12 +24,12 @@ func PeekStream(ctx context.Context, conn net.Conn, buffer *buf.Buffer, timeout
|
|||||||
}
|
}
|
||||||
err := conn.SetReadDeadline(time.Now().Add(timeout))
|
err := conn.SetReadDeadline(time.Now().Add(timeout))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, E.Cause(err, "set read deadline")
|
||||||
}
|
}
|
||||||
_, err = buffer.ReadOnceFrom(conn)
|
_, err = buffer.ReadOnceFrom(conn)
|
||||||
err = E.Errors(err, conn.SetReadDeadline(time.Time{}))
|
err = E.Errors(err, conn.SetReadDeadline(time.Time{}))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, E.Cause(err, "read payload")
|
||||||
}
|
}
|
||||||
var metadata *adapter.InboundContext
|
var metadata *adapter.InboundContext
|
||||||
var errors []error
|
var errors []error
|
||||||
|
|||||||
@@ -124,8 +124,9 @@ func (e *RealityClientConfig) ClientHandshake(ctx context.Context, conn net.Conn
|
|||||||
binary.BigEndian.PutUint64(hello.SessionId, uint64(nowTime.Unix()))
|
binary.BigEndian.PutUint64(hello.SessionId, uint64(nowTime.Unix()))
|
||||||
|
|
||||||
hello.SessionId[0] = 1
|
hello.SessionId[0] = 1
|
||||||
hello.SessionId[1] = 7
|
hello.SessionId[1] = 8
|
||||||
hello.SessionId[2] = 5
|
hello.SessionId[2] = 1
|
||||||
|
binary.BigEndian.PutUint32(hello.SessionId[4:], uint32(time.Now().Unix()))
|
||||||
copy(hello.SessionId[8:], e.shortID[:])
|
copy(hello.SessionId[8:], e.shortID[:])
|
||||||
|
|
||||||
if debug.Enabled {
|
if debug.Enabled {
|
||||||
|
|||||||
@@ -180,7 +180,7 @@ func NewSTDServer(ctx context.Context, router adapter.Router, logger log.Logger,
|
|||||||
tlsConfig.ServerName = options.ServerName
|
tlsConfig.ServerName = options.ServerName
|
||||||
}
|
}
|
||||||
if len(options.ALPN) > 0 {
|
if len(options.ALPN) > 0 {
|
||||||
tlsConfig.NextProtos = append(tlsConfig.NextProtos, options.ALPN...)
|
tlsConfig.NextProtos = append(options.ALPN, tlsConfig.NextProtos...)
|
||||||
}
|
}
|
||||||
if options.MinVersion != "" {
|
if options.MinVersion != "" {
|
||||||
minVersion, err := ParseTLSVersion(options.MinVersion)
|
minVersion, err := ParseTLSVersion(options.MinVersion)
|
||||||
|
|||||||
@@ -50,6 +50,9 @@ func (s *HistoryStorage) StoreURLTestHistory(tag string, history *History) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func URLTest(ctx context.Context, link string, detour N.Dialer) (t uint16, err error) {
|
func URLTest(ctx context.Context, link string, detour N.Dialer) (t uint16, err error) {
|
||||||
|
if link == "" {
|
||||||
|
link = "https://www.gstatic.com/generate_204"
|
||||||
|
}
|
||||||
linkURL, err := url.Parse(link)
|
linkURL, err := url.Parse(link)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
package warning
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Warning struct {
|
|
||||||
logger log.Logger
|
|
||||||
check CheckFunc
|
|
||||||
message string
|
|
||||||
checkOnce sync.Once
|
|
||||||
}
|
|
||||||
|
|
||||||
type CheckFunc = func() bool
|
|
||||||
|
|
||||||
func New(checkFunc CheckFunc, message string) Warning {
|
|
||||||
return Warning{
|
|
||||||
check: checkFunc,
|
|
||||||
message: message,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *Warning) Check() {
|
|
||||||
w.checkOnce.Do(func() {
|
|
||||||
if w.check() {
|
|
||||||
log.Warn(w.message)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -3,28 +3,13 @@ package constant
|
|||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/rw"
|
"github.com/sagernet/sing/common/rw"
|
||||||
)
|
)
|
||||||
|
|
||||||
const dirName = "sing-box"
|
const dirName = "sing-box"
|
||||||
|
|
||||||
var (
|
var resourcePaths []string
|
||||||
basePath string
|
|
||||||
resourcePaths []string
|
|
||||||
)
|
|
||||||
|
|
||||||
func BasePath(name string) string {
|
|
||||||
if basePath == "" || strings.HasPrefix(name, "/") {
|
|
||||||
return name
|
|
||||||
}
|
|
||||||
return filepath.Join(basePath, name)
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetBasePath(path string) {
|
|
||||||
basePath = path
|
|
||||||
}
|
|
||||||
|
|
||||||
func FindPath(name string) (string, bool) {
|
func FindPath(name string) (string, bool) {
|
||||||
name = os.ExpandEnv(name)
|
name = os.ExpandEnv(name)
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func applyDebugOptions(options option.DebugOptions) {
|
func applyDebugOptions(options option.DebugOptions) {
|
||||||
|
applyDebugListenOption(options)
|
||||||
if options.GCPercent != nil {
|
if options.GCPercent != nil {
|
||||||
debug.SetGCPercent(*options.GCPercent)
|
debug.SetGCPercent(*options.GCPercent)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func applyDebugOptions(options option.DebugOptions) {
|
func applyDebugOptions(options option.DebugOptions) {
|
||||||
|
applyDebugListenOption(options)
|
||||||
if options.GCPercent != nil {
|
if options.GCPercent != nil {
|
||||||
debug.SetGCPercent(*options.GCPercent)
|
debug.SetGCPercent(*options.GCPercent)
|
||||||
}
|
}
|
||||||
67
debug_http.go
Normal file
67
debug_http.go
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
package box
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/pprof"
|
||||||
|
"runtime"
|
||||||
|
"runtime/debug"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/common/badjson"
|
||||||
|
"github.com/sagernet/sing-box/common/json"
|
||||||
|
"github.com/sagernet/sing-box/log"
|
||||||
|
"github.com/sagernet/sing-box/option"
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
|
||||||
|
"github.com/dustin/go-humanize"
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
var debugHTTPServer *http.Server
|
||||||
|
|
||||||
|
func applyDebugListenOption(options option.DebugOptions) {
|
||||||
|
if debugHTTPServer != nil {
|
||||||
|
debugHTTPServer.Close()
|
||||||
|
debugHTTPServer = nil
|
||||||
|
}
|
||||||
|
if options.Listen == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r := chi.NewMux()
|
||||||
|
r.Route("/debug", func(r chi.Router) {
|
||||||
|
r.Get("/gc", func(writer http.ResponseWriter, request *http.Request) {
|
||||||
|
writer.WriteHeader(http.StatusNoContent)
|
||||||
|
go debug.FreeOSMemory()
|
||||||
|
})
|
||||||
|
r.Get("/memory", func(writer http.ResponseWriter, request *http.Request) {
|
||||||
|
var memStats runtime.MemStats
|
||||||
|
runtime.ReadMemStats(&memStats)
|
||||||
|
|
||||||
|
var memObject badjson.JSONObject
|
||||||
|
memObject.Put("heap", humanize.IBytes(memStats.HeapInuse))
|
||||||
|
memObject.Put("stack", humanize.IBytes(memStats.StackInuse))
|
||||||
|
memObject.Put("idle", humanize.IBytes(memStats.HeapIdle-memStats.HeapReleased))
|
||||||
|
memObject.Put("goroutines", runtime.NumGoroutine())
|
||||||
|
memObject.Put("rss", rusageMaxRSS())
|
||||||
|
|
||||||
|
encoder := json.NewEncoder(writer)
|
||||||
|
encoder.SetIndent("", " ")
|
||||||
|
encoder.Encode(memObject)
|
||||||
|
})
|
||||||
|
r.HandleFunc("/pprof", pprof.Index)
|
||||||
|
r.HandleFunc("/pprof/*", pprof.Index)
|
||||||
|
r.HandleFunc("/pprof/cmdline", pprof.Cmdline)
|
||||||
|
r.HandleFunc("/pprof/profile", pprof.Profile)
|
||||||
|
r.HandleFunc("/pprof/symbol", pprof.Symbol)
|
||||||
|
r.HandleFunc("/pprof/trace", pprof.Trace)
|
||||||
|
})
|
||||||
|
debugHTTPServer = &http.Server{
|
||||||
|
Addr: options.Listen,
|
||||||
|
Handler: r,
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
err := debugHTTPServer.ListenAndServe()
|
||||||
|
if err != nil && !E.IsClosed(err) {
|
||||||
|
log.Error(E.Cause(err, "serve debug HTTP server"))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
//go:build debug
|
package box
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"runtime"
|
"runtime"
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
//go:build debug && !linux
|
//go:build !linux
|
||||||
|
|
||||||
package main
|
package box
|
||||||
|
|
||||||
func rusageMaxRSS() float64 {
|
func rusageMaxRSS() float64 {
|
||||||
return -1
|
return -1
|
||||||
@@ -1,3 +1,87 @@
|
|||||||
|
#### 1.3-beta9
|
||||||
|
|
||||||
|
* Improve multiplex **1**
|
||||||
|
* Fixes and improvements
|
||||||
|
|
||||||
|
*1*:
|
||||||
|
|
||||||
|
Added new `h2mux` multiplex protocol and `padding` multiplex option, see [Multiplex](/configuration/shared/multiplex).
|
||||||
|
|
||||||
|
#### 1.2.6
|
||||||
|
|
||||||
|
* Fix bugs and update dependencies
|
||||||
|
|
||||||
|
#### 1.3-beta8
|
||||||
|
|
||||||
|
* Fix `system` tun stack for ios
|
||||||
|
* Fix network monitor for android/ios
|
||||||
|
* Update VLESS and XUDP protocol **1**
|
||||||
|
* Fixes and improvements
|
||||||
|
|
||||||
|
*1:
|
||||||
|
|
||||||
|
This is an incompatible update for XUDP in VLESS if vision flow is enabled.
|
||||||
|
|
||||||
|
#### 1.3-beta7
|
||||||
|
|
||||||
|
* Add `path` and `headers` options for HTTP outbound
|
||||||
|
* Add multi-user support for Shadowsocks legacy AEAD inbound
|
||||||
|
* Fixes and improvements
|
||||||
|
|
||||||
|
#### 1.2.4
|
||||||
|
|
||||||
|
* Fixes and improvements
|
||||||
|
|
||||||
|
#### 1.3-beta6
|
||||||
|
|
||||||
|
* Fix WireGuard reconnect
|
||||||
|
* Perform URLTest recheck after network changes
|
||||||
|
* Fix bugs and update dependencies
|
||||||
|
|
||||||
|
#### 1.3-beta5
|
||||||
|
|
||||||
|
* Add Clash.Meta API compatibility for Clash API
|
||||||
|
* Download Yacd-meta by default if the specified Clash `external_ui` directory is empty
|
||||||
|
* Add path and headers option for HTTP outbound
|
||||||
|
* Fixes and improvements
|
||||||
|
|
||||||
|
#### 1.3-beta4
|
||||||
|
|
||||||
|
* Fix bugs
|
||||||
|
|
||||||
|
#### 1.3-beta2
|
||||||
|
|
||||||
|
* Download clash-dashboard if the specified Clash `external_ui` directory is empty
|
||||||
|
* Fix bugs and update dependencies
|
||||||
|
|
||||||
|
#### 1.3-beta1
|
||||||
|
|
||||||
|
* Add [DNS reverse mapping](/configuration/dns#reverse_mapping) support
|
||||||
|
* Add [L3 routing](/configuration/route/ip-rule) support **1**
|
||||||
|
* Add `rewrite_ttl` DNS rule action
|
||||||
|
* Add [FakeIP](/configuration/dns/fakeip) support **2**
|
||||||
|
* Add `store_fakeip` Clash API option
|
||||||
|
* Add multi-peer support for [WireGuard](/configuration/outbound/wireguard#peers) outbound
|
||||||
|
* Add loopback detect
|
||||||
|
|
||||||
|
*1*:
|
||||||
|
|
||||||
|
It can currently be used to [route connections directly to WireGuard](/examples/wireguard-direct) or block connections
|
||||||
|
at the IP layer.
|
||||||
|
|
||||||
|
*2*:
|
||||||
|
|
||||||
|
See [FAQ](/faq/fakeip) for more information.
|
||||||
|
|
||||||
|
#### 1.2.3
|
||||||
|
|
||||||
|
* Introducing our [new Android client application](/installation/clients/sfa)
|
||||||
|
* Improve UDP domain destination NAT
|
||||||
|
* Update reality protocol
|
||||||
|
* Fix TTL calculation for DNS response
|
||||||
|
* Fix v2ray HTTP transport compatibility
|
||||||
|
* Fix bugs and update dependencies
|
||||||
|
|
||||||
#### 1.2.2
|
#### 1.2.2
|
||||||
|
|
||||||
* Accept `any` outbound in dns rule **1**
|
* Accept `any` outbound in dns rule **1**
|
||||||
@@ -5,7 +89,8 @@
|
|||||||
|
|
||||||
*1*:
|
*1*:
|
||||||
|
|
||||||
Now you can use the `any` outbound rule to match server address queries instead of filling in all server domains to `domain` rule.
|
Now you can use the `any` outbound rule to match server address queries instead of filling in all server domains
|
||||||
|
to `domain` rule.
|
||||||
|
|
||||||
#### 1.2.1
|
#### 1.2.1
|
||||||
|
|
||||||
|
|||||||
25
docs/configuration/dns/fakeip.md
Normal file
25
docs/configuration/dns/fakeip.md
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# FakeIP
|
||||||
|
|
||||||
|
### Structure
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"enabled": true,
|
||||||
|
"inet4_range": "198.18.0.0/15",
|
||||||
|
"inet6_range": "fc00::/18"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Fields
|
||||||
|
|
||||||
|
#### enabled
|
||||||
|
|
||||||
|
Enable FakeIP service.
|
||||||
|
|
||||||
|
#### inet4_range
|
||||||
|
|
||||||
|
IPv4 address range for FakeIP.
|
||||||
|
|
||||||
|
#### inet6_address
|
||||||
|
|
||||||
|
IPv6 address range for FakeIP.
|
||||||
25
docs/configuration/dns/fakeip.zh.md
Normal file
25
docs/configuration/dns/fakeip.zh.md
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# FakeIP
|
||||||
|
|
||||||
|
### 结构
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"enabled": true,
|
||||||
|
"inet4_range": "198.18.0.0/15",
|
||||||
|
"inet6_range": "fc00::/18"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 字段
|
||||||
|
|
||||||
|
#### enabled
|
||||||
|
|
||||||
|
启用 FakeIP 服务。
|
||||||
|
|
||||||
|
#### inet4_range
|
||||||
|
|
||||||
|
用于 FakeIP 的 IPv4 地址范围。
|
||||||
|
|
||||||
|
#### inet6_range
|
||||||
|
|
||||||
|
用于 FakeIP 的 IPv6 地址范围。
|
||||||
@@ -10,7 +10,9 @@
|
|||||||
"final": "",
|
"final": "",
|
||||||
"strategy": "",
|
"strategy": "",
|
||||||
"disable_cache": false,
|
"disable_cache": false,
|
||||||
"disable_expire": false
|
"disable_expire": false,
|
||||||
|
"reverse_mapping": false,
|
||||||
|
"fakeip": {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -22,6 +24,7 @@
|
|||||||
|----------|--------------------------------|
|
|----------|--------------------------------|
|
||||||
| `server` | List of [DNS Server](./server) |
|
| `server` | List of [DNS Server](./server) |
|
||||||
| `rules` | List of [DNS Rule](./rule) |
|
| `rules` | List of [DNS Rule](./rule) |
|
||||||
|
| `fakeip` | [FakeIP](./fakeip) |
|
||||||
|
|
||||||
#### final
|
#### final
|
||||||
|
|
||||||
@@ -43,4 +46,15 @@ Disable dns cache.
|
|||||||
|
|
||||||
#### disable_expire
|
#### disable_expire
|
||||||
|
|
||||||
Disable dns cache expire.
|
Disable dns cache expire.
|
||||||
|
|
||||||
|
#### reverse_mapping
|
||||||
|
|
||||||
|
Stores a reverse mapping of IP addresses after responding to a DNS query in order to provide domain names when routing.
|
||||||
|
|
||||||
|
Since this process relies on the act of resolving domain names by an application before making a request, it can be
|
||||||
|
problematic in environments such as macOS, where DNS is proxied and cached by the system.
|
||||||
|
|
||||||
|
#### fakeip
|
||||||
|
|
||||||
|
[FakeIP](./fakeip) settings.
|
||||||
|
|||||||
@@ -10,7 +10,9 @@
|
|||||||
"final": "",
|
"final": "",
|
||||||
"strategy": "",
|
"strategy": "",
|
||||||
"disable_cache": false,
|
"disable_cache": false,
|
||||||
"disable_expire": false
|
"disable_expire": false,
|
||||||
|
"reverse_mapping": false,
|
||||||
|
"fakeip": {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,4 +45,14 @@
|
|||||||
|
|
||||||
#### disable_expire
|
#### disable_expire
|
||||||
|
|
||||||
禁用 DNS 缓存过期。
|
禁用 DNS 缓存过期。
|
||||||
|
|
||||||
|
#### reverse_mapping
|
||||||
|
|
||||||
|
在响应 DNS 查询后存储 IP 地址的反向映射以为路由目的提供域名。
|
||||||
|
|
||||||
|
由于此过程依赖于应用程序在发出请求之前解析域名的行为,因此在 macOS 等 DNS 由系统代理和缓存的环境中可能会出现问题。
|
||||||
|
|
||||||
|
#### fakeip
|
||||||
|
|
||||||
|
[FakeIP](./fakeip) 设置。
|
||||||
|
|||||||
@@ -84,14 +84,16 @@
|
|||||||
"direct"
|
"direct"
|
||||||
],
|
],
|
||||||
"server": "local",
|
"server": "local",
|
||||||
"disable_cache": false
|
"disable_cache": false,
|
||||||
|
"rewrite_ttl": 100
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "logical",
|
"type": "logical",
|
||||||
"mode": "and",
|
"mode": "and",
|
||||||
"rules": [],
|
"rules": [],
|
||||||
"server": "local",
|
"server": "local",
|
||||||
"disable_cache": false
|
"disable_cache": false,
|
||||||
|
"rewrite_ttl": 100
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -244,6 +246,10 @@ Tag of the target dns server.
|
|||||||
|
|
||||||
Disable cache and save cache in this query.
|
Disable cache and save cache in this query.
|
||||||
|
|
||||||
|
#### rewrite_ttl
|
||||||
|
|
||||||
|
Rewrite TTL in DNS responses.
|
||||||
|
|
||||||
### Logical Fields
|
### Logical Fields
|
||||||
|
|
||||||
#### type
|
#### type
|
||||||
|
|||||||
@@ -243,6 +243,10 @@ DNS 查询类型。值可以为整数或者类型名称字符串。
|
|||||||
|
|
||||||
在此查询中禁用缓存。
|
在此查询中禁用缓存。
|
||||||
|
|
||||||
|
#### rewrite_ttl
|
||||||
|
|
||||||
|
重写 DNS 回应中的 TTL。
|
||||||
|
|
||||||
### 逻辑字段
|
### 逻辑字段
|
||||||
|
|
||||||
#### type
|
#### type
|
||||||
|
|||||||
@@ -30,17 +30,18 @@ The tag of the dns server.
|
|||||||
|
|
||||||
The address of the dns server.
|
The address of the dns server.
|
||||||
|
|
||||||
| Protocol | Format |
|
| Protocol | Format |
|
||||||
|----------|-------------------------------|
|
|---------------------|-------------------------------|
|
||||||
| `System` | `local` |
|
| `System` | `local` |
|
||||||
| `TCP` | `tcp://1.0.0.1` |
|
| `TCP` | `tcp://1.0.0.1` |
|
||||||
| `UDP` | `8.8.8.8` `udp://8.8.4.4` |
|
| `UDP` | `8.8.8.8` `udp://8.8.4.4` |
|
||||||
| `TLS` | `tls://dns.google` |
|
| `TLS` | `tls://dns.google` |
|
||||||
| `HTTPS` | `https://1.1.1.1/dns-query` |
|
| `HTTPS` | `https://1.1.1.1/dns-query` |
|
||||||
| `QUIC` | `quic://dns.adguard.com` |
|
| `QUIC` | `quic://dns.adguard.com` |
|
||||||
| `HTTP3` | `h3://8.8.8.8/dns-query` |
|
| `HTTP3` | `h3://8.8.8.8/dns-query` |
|
||||||
| `RCode` | `rcode://refused` |
|
| `RCode` | `rcode://refused` |
|
||||||
| `DHCP` | `dhcp://auto` or `dhcp://en0` |
|
| `DHCP` | `dhcp://auto` or `dhcp://en0` |
|
||||||
|
| [FakeIP](./fakeip) | `fakeip` |
|
||||||
|
|
||||||
!!! warning ""
|
!!! warning ""
|
||||||
|
|
||||||
|
|||||||
@@ -30,17 +30,18 @@ DNS 服务器的标签。
|
|||||||
|
|
||||||
DNS 服务器的地址。
|
DNS 服务器的地址。
|
||||||
|
|
||||||
| 协议 | 格式 |
|
| 协议 | 格式 |
|
||||||
|----------|------------------------------|
|
|--------------------|------------------------------|
|
||||||
| `System` | `local` |
|
| `System` | `local` |
|
||||||
| `TCP` | `tcp://1.0.0.1` |
|
| `TCP` | `tcp://1.0.0.1` |
|
||||||
| `UDP` | `8.8.8.8` `udp://8.8.4.4` |
|
| `UDP` | `8.8.8.8` `udp://8.8.4.4` |
|
||||||
| `TLS` | `tls://dns.google` |
|
| `TLS` | `tls://dns.google` |
|
||||||
| `HTTPS` | `https://1.1.1.1/dns-query` |
|
| `HTTPS` | `https://1.1.1.1/dns-query` |
|
||||||
| `QUIC` | `quic://dns.adguard.com` |
|
| `QUIC` | `quic://dns.adguard.com` |
|
||||||
| `HTTP3` | `h3://8.8.8.8/dns-query` |
|
| `HTTP3` | `h3://8.8.8.8/dns-query` |
|
||||||
| `RCode` | `rcode://refused` |
|
| `RCode` | `rcode://refused` |
|
||||||
| `DHCP` | `dhcp://auto` 或 `dhcp://en0` |
|
| `DHCP` | `dhcp://auto` 或 `dhcp://en0` |
|
||||||
|
| [FakeIP](./fakeip) | `fakeip` |
|
||||||
|
|
||||||
!!! warning ""
|
!!! warning ""
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,8 @@
|
|||||||
"clash_api": {
|
"clash_api": {
|
||||||
"external_controller": "127.0.0.1:9090",
|
"external_controller": "127.0.0.1:9090",
|
||||||
"external_ui": "folder",
|
"external_ui": "folder",
|
||||||
|
"external_ui_download_url": "",
|
||||||
|
"external_ui_download_detour": "",
|
||||||
"secret": "",
|
"secret": "",
|
||||||
"default_mode": "rule",
|
"default_mode": "rule",
|
||||||
"store_selected": false,
|
"store_selected": false,
|
||||||
@@ -53,6 +55,18 @@ A relative path to the configuration directory or an absolute path to a
|
|||||||
directory in which you put some static web resource. sing-box will then
|
directory in which you put some static web resource. sing-box will then
|
||||||
serve it at `http://{{external-controller}}/ui`.
|
serve it at `http://{{external-controller}}/ui`.
|
||||||
|
|
||||||
|
#### external_ui_download_url
|
||||||
|
|
||||||
|
ZIP download URL for the external UI, will be used if the specified `external_ui` directory is empty.
|
||||||
|
|
||||||
|
`https://github.com/MetaCubeX/Yacd-meta/archive/gh-pages.zip` will be used if empty.
|
||||||
|
|
||||||
|
#### external_ui_download_detour
|
||||||
|
|
||||||
|
The tag of the outbound to download the external UI.
|
||||||
|
|
||||||
|
Default outbound will be used if empty.
|
||||||
|
|
||||||
#### secret
|
#### secret
|
||||||
|
|
||||||
Secret for the RESTful API (optional)
|
Secret for the RESTful API (optional)
|
||||||
|
|||||||
@@ -8,6 +8,8 @@
|
|||||||
"clash_api": {
|
"clash_api": {
|
||||||
"external_controller": "127.0.0.1:9090",
|
"external_controller": "127.0.0.1:9090",
|
||||||
"external_ui": "folder",
|
"external_ui": "folder",
|
||||||
|
"external_ui_download_url": "",
|
||||||
|
"external_ui_download_detour": "",
|
||||||
"secret": "",
|
"secret": "",
|
||||||
"default_mode": "rule",
|
"default_mode": "rule",
|
||||||
"store_selected": false,
|
"store_selected": false,
|
||||||
@@ -51,6 +53,18 @@ RESTful web API 监听地址。如果为空,则禁用 Clash API。
|
|||||||
|
|
||||||
到静态网页资源目录的相对路径或绝对路径。sing-box 会在 `http://{{external-controller}}/ui` 下提供它。
|
到静态网页资源目录的相对路径或绝对路径。sing-box 会在 `http://{{external-controller}}/ui` 下提供它。
|
||||||
|
|
||||||
|
#### external_ui_download_url
|
||||||
|
|
||||||
|
静态网页资源的 ZIP 下载 URL,如果指定的 `external_ui` 目录为空,将使用。
|
||||||
|
|
||||||
|
默认使用 `https://github.com/MetaCubeX/Yacd-meta/archive/gh-pages.zip`。
|
||||||
|
|
||||||
|
#### external_ui_download_detour
|
||||||
|
|
||||||
|
用于下载静态网页资源的出站的标签。
|
||||||
|
|
||||||
|
如果为空,将使用默认出站。
|
||||||
|
|
||||||
#### secret
|
#### secret
|
||||||
|
|
||||||
RESTful API 的密钥(可选)
|
RESTful API 的密钥(可选)
|
||||||
|
|||||||
@@ -11,6 +11,8 @@
|
|||||||
"server_port": 1080,
|
"server_port": 1080,
|
||||||
"username": "sekai",
|
"username": "sekai",
|
||||||
"password": "admin",
|
"password": "admin",
|
||||||
|
"path": "",
|
||||||
|
"headers": {},
|
||||||
"tls": {},
|
"tls": {},
|
||||||
|
|
||||||
... // Dial Fields
|
... // Dial Fields
|
||||||
@@ -39,6 +41,14 @@ Basic authorization username.
|
|||||||
|
|
||||||
Basic authorization password.
|
Basic authorization password.
|
||||||
|
|
||||||
|
#### path
|
||||||
|
|
||||||
|
Path of HTTP request.
|
||||||
|
|
||||||
|
#### headers
|
||||||
|
|
||||||
|
Extra headers of HTTP request.
|
||||||
|
|
||||||
#### tls
|
#### tls
|
||||||
|
|
||||||
TLS configuration, see [TLS](/configuration/shared/tls/#outbound).
|
TLS configuration, see [TLS](/configuration/shared/tls/#outbound).
|
||||||
|
|||||||
@@ -11,6 +11,8 @@
|
|||||||
"server_port": 1080,
|
"server_port": 1080,
|
||||||
"username": "sekai",
|
"username": "sekai",
|
||||||
"password": "admin",
|
"password": "admin",
|
||||||
|
"path": "",
|
||||||
|
"headers": {},
|
||||||
"tls": {},
|
"tls": {},
|
||||||
|
|
||||||
... // 拨号字段
|
... // 拨号字段
|
||||||
@@ -39,6 +41,14 @@ Basic 认证用户名。
|
|||||||
|
|
||||||
Basic 认证密码。
|
Basic 认证密码。
|
||||||
|
|
||||||
|
#### path
|
||||||
|
|
||||||
|
HTTP 请求路径。
|
||||||
|
|
||||||
|
#### headers
|
||||||
|
|
||||||
|
HTTP 请求的额外标头。
|
||||||
|
|
||||||
#### tls
|
#### tls
|
||||||
|
|
||||||
TLS 配置, 参阅 [TLS](/zh/configuration/shared/tls/#outbound)。
|
TLS 配置, 参阅 [TLS](/zh/configuration/shared/tls/#outbound)。
|
||||||
|
|||||||
@@ -37,4 +37,10 @@
|
|||||||
|
|
||||||
#### tag
|
#### tag
|
||||||
|
|
||||||
The tag of the outbound.
|
The tag of the outbound.
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
#### Outbounds that support IP connection
|
||||||
|
|
||||||
|
* `WireGuard`
|
||||||
|
|||||||
@@ -36,4 +36,10 @@
|
|||||||
|
|
||||||
#### tag
|
#### tag
|
||||||
|
|
||||||
出站的标签。
|
出站的标签。
|
||||||
|
|
||||||
|
### 特性
|
||||||
|
|
||||||
|
#### 支持 IP 连接的出站
|
||||||
|
|
||||||
|
* `WireGuard`
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
"proxy-b",
|
"proxy-b",
|
||||||
"proxy-c"
|
"proxy-c"
|
||||||
],
|
],
|
||||||
"url": "http://www.gstatic.com/generate_204",
|
"url": "https://www.gstatic.com/generate_204",
|
||||||
"interval": "1m",
|
"interval": "1m",
|
||||||
"tolerance": 50
|
"tolerance": 50
|
||||||
}
|
}
|
||||||
@@ -26,7 +26,7 @@ List of outbound tags to test.
|
|||||||
|
|
||||||
#### url
|
#### url
|
||||||
|
|
||||||
The URL to test. `http://www.gstatic.com/generate_204` will be used if empty.
|
The URL to test. `https://www.gstatic.com/generate_204` will be used if empty.
|
||||||
|
|
||||||
#### interval
|
#### interval
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
"proxy-b",
|
"proxy-b",
|
||||||
"proxy-c"
|
"proxy-c"
|
||||||
],
|
],
|
||||||
"url": "http://www.gstatic.com/generate_204",
|
"url": "https://www.gstatic.com/generate_204",
|
||||||
"interval": "1m",
|
"interval": "1m",
|
||||||
"tolerance": 50
|
"tolerance": 50
|
||||||
}
|
}
|
||||||
@@ -26,7 +26,7 @@
|
|||||||
|
|
||||||
#### url
|
#### url
|
||||||
|
|
||||||
用于测试的链接。默认使用 `http://www.gstatic.com/generate_204`。
|
用于测试的链接。默认使用 `https://www.gstatic.com/generate_204`。
|
||||||
|
|
||||||
#### interval
|
#### interval
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,18 @@
|
|||||||
"10.0.0.2/32"
|
"10.0.0.2/32"
|
||||||
],
|
],
|
||||||
"private_key": "YNXtAzepDqRv9H52osJVDQnznT5AM11eCK3ESpwSt04=",
|
"private_key": "YNXtAzepDqRv9H52osJVDQnznT5AM11eCK3ESpwSt04=",
|
||||||
|
"peers": [
|
||||||
|
{
|
||||||
|
"server": "127.0.0.1",
|
||||||
|
"server_port": 1080,
|
||||||
|
"public_key": "Z1XXLsKYkYxuiYjJIkRvtIKFepCYHTgON+GwPq7SOV4=",
|
||||||
|
"pre_shared_key": "31aIhAPwktDGpH4JDhA8GNvjFXEf/a6+UaQRyOAiyfM=",
|
||||||
|
"allowed_ips": [
|
||||||
|
"0.0.0.0/0"
|
||||||
|
],
|
||||||
|
"reserved": [0, 0, 0]
|
||||||
|
}
|
||||||
|
],
|
||||||
"peer_public_key": "Z1XXLsKYkYxuiYjJIkRvtIKFepCYHTgON+GwPq7SOV4=",
|
"peer_public_key": "Z1XXLsKYkYxuiYjJIkRvtIKFepCYHTgON+GwPq7SOV4=",
|
||||||
"pre_shared_key": "31aIhAPwktDGpH4JDhA8GNvjFXEf/a6+UaQRyOAiyfM=",
|
"pre_shared_key": "31aIhAPwktDGpH4JDhA8GNvjFXEf/a6+UaQRyOAiyfM=",
|
||||||
"reserved": [0, 0, 0],
|
"reserved": [0, 0, 0],
|
||||||
@@ -36,13 +48,13 @@
|
|||||||
|
|
||||||
#### server
|
#### server
|
||||||
|
|
||||||
==Required==
|
==Required if multi-peer disabled==
|
||||||
|
|
||||||
The server address.
|
The server address.
|
||||||
|
|
||||||
#### server_port
|
#### server_port
|
||||||
|
|
||||||
==Required==
|
==Required if multi-peer disabled==
|
||||||
|
|
||||||
The server port.
|
The server port.
|
||||||
|
|
||||||
@@ -75,9 +87,25 @@ wg genkey
|
|||||||
echo "private key" || wg pubkey
|
echo "private key" || wg pubkey
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### peers
|
||||||
|
|
||||||
|
Multi-peer support.
|
||||||
|
|
||||||
|
If enabled, `server, server_port, peer_public_key, pre_shared_key` will be ignored.
|
||||||
|
|
||||||
|
#### peers.allowed_ips
|
||||||
|
|
||||||
|
WireGuard allowed IPs.
|
||||||
|
|
||||||
|
#### peers.reserved
|
||||||
|
|
||||||
|
WireGuard reserved field bytes.
|
||||||
|
|
||||||
|
`$outbound.reserved` will be used if empty.
|
||||||
|
|
||||||
#### peer_public_key
|
#### peer_public_key
|
||||||
|
|
||||||
==Required==
|
==Required if multi-peer disabled==
|
||||||
|
|
||||||
WireGuard peer public key.
|
WireGuard peer public key.
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
"route": {
|
"route": {
|
||||||
"geoip": {},
|
"geoip": {},
|
||||||
"geosite": {},
|
"geosite": {},
|
||||||
|
"ip_rules": [],
|
||||||
"rules": [],
|
"rules": [],
|
||||||
"final": "",
|
"final": "",
|
||||||
"auto_detect_interface": false,
|
"auto_detect_interface": false,
|
||||||
@@ -19,11 +20,12 @@
|
|||||||
|
|
||||||
### Fields
|
### Fields
|
||||||
|
|
||||||
| Key | Format |
|
| Key | Format |
|
||||||
|-----------|------------------------------|
|
|------------|------------------------------------|
|
||||||
| `geoip` | [GeoIP](./geoip) |
|
| `geoip` | [GeoIP](./geoip) |
|
||||||
| `geosite` | [Geosite](./geosite) |
|
| `geosite` | [Geosite](./geosite) |
|
||||||
| `rules` | List of [Route Rule](./rule) |
|
| `ip_rules` | List of [IP Route Rule](./ip-rule) |
|
||||||
|
| `rules` | List of [Route Rule](./rule) |
|
||||||
|
|
||||||
#### final
|
#### final
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
"route": {
|
"route": {
|
||||||
"geoip": {},
|
"geoip": {},
|
||||||
"geosite": {},
|
"geosite": {},
|
||||||
|
"ip_rules": [],
|
||||||
"rules": [],
|
"rules": [],
|
||||||
"final": "",
|
"final": "",
|
||||||
"auto_detect_interface": false,
|
"auto_detect_interface": false,
|
||||||
@@ -19,11 +20,12 @@
|
|||||||
|
|
||||||
### 字段
|
### 字段
|
||||||
|
|
||||||
| 键 | 格式 |
|
| 键 | 格式 |
|
||||||
|-----------|----------------------|
|
|------------|-------------------------|
|
||||||
| `geoip` | [GeoIP](./geoip) |
|
| `geoip` | [GeoIP](./geoip) |
|
||||||
| `geosite` | [GeoSite](./geosite) |
|
| `geosite` | [GeoSite](./geosite) |
|
||||||
| `rules` | 一组 [路由规则](./rule) |
|
| `ip_rules` | 一组 [IP 路由规则](./ip-rule) |
|
||||||
|
| `rules` | 一组 [路由规则](./rule) |
|
||||||
|
|
||||||
#### final
|
#### final
|
||||||
|
|
||||||
@@ -65,4 +67,4 @@
|
|||||||
|
|
||||||
默认为出站连接设置路由标记。
|
默认为出站连接设置路由标记。
|
||||||
|
|
||||||
如果设置了 `outbound.routing_mark` 设置,则不生效。
|
如果设置了 `outbound.routing_mark` 设置,则不生效。
|
||||||
205
docs/configuration/route/ip-rule.md
Normal file
205
docs/configuration/route/ip-rule.md
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
### Structure
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"route": {
|
||||||
|
"ip_rules": [
|
||||||
|
{
|
||||||
|
"inbound": [
|
||||||
|
"mixed-in"
|
||||||
|
],
|
||||||
|
"ip_version": 6,
|
||||||
|
"network": [
|
||||||
|
"tcp"
|
||||||
|
],
|
||||||
|
"domain": [
|
||||||
|
"test.com"
|
||||||
|
],
|
||||||
|
"domain_suffix": [
|
||||||
|
".cn"
|
||||||
|
],
|
||||||
|
"domain_keyword": [
|
||||||
|
"test"
|
||||||
|
],
|
||||||
|
"domain_regex": [
|
||||||
|
"^stun\\..+"
|
||||||
|
],
|
||||||
|
"geosite": [
|
||||||
|
"cn"
|
||||||
|
],
|
||||||
|
"source_geoip": [
|
||||||
|
"private"
|
||||||
|
],
|
||||||
|
"geoip": [
|
||||||
|
"cn"
|
||||||
|
],
|
||||||
|
"source_ip_cidr": [
|
||||||
|
"10.0.0.0/24",
|
||||||
|
"192.168.0.1"
|
||||||
|
],
|
||||||
|
"ip_cidr": [
|
||||||
|
"10.0.0.0/24",
|
||||||
|
"192.168.0.1"
|
||||||
|
],
|
||||||
|
"source_port": [
|
||||||
|
12345
|
||||||
|
],
|
||||||
|
"source_port_range": [
|
||||||
|
"1000:2000",
|
||||||
|
":3000",
|
||||||
|
"4000:"
|
||||||
|
],
|
||||||
|
"port": [
|
||||||
|
80,
|
||||||
|
443
|
||||||
|
],
|
||||||
|
"port_range": [
|
||||||
|
"1000:2000",
|
||||||
|
":3000",
|
||||||
|
"4000:"
|
||||||
|
],
|
||||||
|
"invert": false,
|
||||||
|
"action": "direct",
|
||||||
|
"outbound": "wireguard"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "logical",
|
||||||
|
"mode": "and",
|
||||||
|
"rules": [],
|
||||||
|
"invert": false,
|
||||||
|
"action": "direct",
|
||||||
|
"outbound": "wireguard"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! note ""
|
||||||
|
|
||||||
|
You can ignore the JSON Array [] tag when the content is only one item
|
||||||
|
|
||||||
|
### Default Fields
|
||||||
|
|
||||||
|
!!! note ""
|
||||||
|
|
||||||
|
The default rule uses the following matching logic:
|
||||||
|
(`domain` || `domain_suffix` || `domain_keyword` || `domain_regex` || `geosite` || `geoip` || `ip_cidr`) &&
|
||||||
|
(`port` || `port_range`) &&
|
||||||
|
(`source_geoip` || `source_ip_cidr`) &&
|
||||||
|
(`source_port` || `source_port_range`) &&
|
||||||
|
`other fields`
|
||||||
|
|
||||||
|
#### inbound
|
||||||
|
|
||||||
|
Tags of [Inbound](/configuration/inbound).
|
||||||
|
|
||||||
|
#### ip_version
|
||||||
|
|
||||||
|
4 or 6.
|
||||||
|
|
||||||
|
Not limited if empty.
|
||||||
|
|
||||||
|
#### network
|
||||||
|
|
||||||
|
Match network protocol.
|
||||||
|
|
||||||
|
Available values:
|
||||||
|
|
||||||
|
* `tcp`
|
||||||
|
* `udp`
|
||||||
|
* `icmpv4`
|
||||||
|
* `icmpv6`
|
||||||
|
|
||||||
|
#### domain
|
||||||
|
|
||||||
|
Match full domain.
|
||||||
|
|
||||||
|
#### domain_suffix
|
||||||
|
|
||||||
|
Match domain suffix.
|
||||||
|
|
||||||
|
#### domain_keyword
|
||||||
|
|
||||||
|
Match domain using keyword.
|
||||||
|
|
||||||
|
#### domain_regex
|
||||||
|
|
||||||
|
Match domain using regular expression.
|
||||||
|
|
||||||
|
#### geosite
|
||||||
|
|
||||||
|
Match geosite.
|
||||||
|
|
||||||
|
#### source_geoip
|
||||||
|
|
||||||
|
Match source geoip.
|
||||||
|
|
||||||
|
#### geoip
|
||||||
|
|
||||||
|
Match geoip.
|
||||||
|
|
||||||
|
#### source_ip_cidr
|
||||||
|
|
||||||
|
Match source ip cidr.
|
||||||
|
|
||||||
|
#### ip_cidr
|
||||||
|
|
||||||
|
Match ip cidr.
|
||||||
|
|
||||||
|
#### source_port
|
||||||
|
|
||||||
|
Match source port.
|
||||||
|
|
||||||
|
#### source_port_range
|
||||||
|
|
||||||
|
Match source port range.
|
||||||
|
|
||||||
|
#### port
|
||||||
|
|
||||||
|
Match port.
|
||||||
|
|
||||||
|
#### port_range
|
||||||
|
|
||||||
|
Match port range.
|
||||||
|
|
||||||
|
#### invert
|
||||||
|
|
||||||
|
Invert match result.
|
||||||
|
|
||||||
|
#### action
|
||||||
|
|
||||||
|
==Required==
|
||||||
|
|
||||||
|
| Action | Description |
|
||||||
|
|--------|--------------------------------------------------------------------|
|
||||||
|
| return | Stop IP routing and assemble the connection to the transport layer |
|
||||||
|
| block | Block the connection |
|
||||||
|
| direct | Directly forward the connection |
|
||||||
|
|
||||||
|
#### outbound
|
||||||
|
|
||||||
|
==Required if action is direct==
|
||||||
|
|
||||||
|
Tag of the target outbound.
|
||||||
|
|
||||||
|
Only outbound which supports IP connection can be used, see [Outbounds that support IP connection](/configuration/outbound/#outbounds-that-support-ip-connection).
|
||||||
|
|
||||||
|
### Logical Fields
|
||||||
|
|
||||||
|
#### type
|
||||||
|
|
||||||
|
`logical`
|
||||||
|
|
||||||
|
#### mode
|
||||||
|
|
||||||
|
==Required==
|
||||||
|
|
||||||
|
`and` or `or`
|
||||||
|
|
||||||
|
#### rules
|
||||||
|
|
||||||
|
==Required==
|
||||||
|
|
||||||
|
Included default rules.
|
||||||
204
docs/configuration/route/ip-rule.zh.md
Normal file
204
docs/configuration/route/ip-rule.zh.md
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
### 结构
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"route": {
|
||||||
|
"ip_rules": [
|
||||||
|
{
|
||||||
|
"inbound": [
|
||||||
|
"mixed-in"
|
||||||
|
],
|
||||||
|
"ip_version": 6,
|
||||||
|
"network": [
|
||||||
|
"tcp"
|
||||||
|
],
|
||||||
|
"domain": [
|
||||||
|
"test.com"
|
||||||
|
],
|
||||||
|
"domain_suffix": [
|
||||||
|
".cn"
|
||||||
|
],
|
||||||
|
"domain_keyword": [
|
||||||
|
"test"
|
||||||
|
],
|
||||||
|
"domain_regex": [
|
||||||
|
"^stun\\..+"
|
||||||
|
],
|
||||||
|
"geosite": [
|
||||||
|
"cn"
|
||||||
|
],
|
||||||
|
"source_geoip": [
|
||||||
|
"private"
|
||||||
|
],
|
||||||
|
"geoip": [
|
||||||
|
"cn"
|
||||||
|
],
|
||||||
|
"source_ip_cidr": [
|
||||||
|
"10.0.0.0/24",
|
||||||
|
"192.168.0.1"
|
||||||
|
],
|
||||||
|
"ip_cidr": [
|
||||||
|
"10.0.0.0/24",
|
||||||
|
"192.168.0.1"
|
||||||
|
],
|
||||||
|
"source_port": [
|
||||||
|
12345
|
||||||
|
],
|
||||||
|
"source_port_range": [
|
||||||
|
"1000:2000",
|
||||||
|
":3000",
|
||||||
|
"4000:"
|
||||||
|
],
|
||||||
|
"port": [
|
||||||
|
80,
|
||||||
|
443
|
||||||
|
],
|
||||||
|
"port_range": [
|
||||||
|
"1000:2000",
|
||||||
|
":3000",
|
||||||
|
"4000:"
|
||||||
|
],
|
||||||
|
"invert": false,
|
||||||
|
"action": "direct",
|
||||||
|
"outbound": "wireguard"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "logical",
|
||||||
|
"mode": "and",
|
||||||
|
"rules": [],
|
||||||
|
"invert": false,
|
||||||
|
"action": "direct",
|
||||||
|
"outbound": "wireguard"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! note ""
|
||||||
|
|
||||||
|
当内容只有一项时,可以忽略 JSON 数组 [] 标签。
|
||||||
|
|
||||||
|
### Default Fields
|
||||||
|
|
||||||
|
!!! note ""
|
||||||
|
|
||||||
|
默认规则使用以下匹配逻辑:
|
||||||
|
(`domain` || `domain_suffix` || `domain_keyword` || `domain_regex` || `geosite` || `geoip` || `ip_cidr`) &&
|
||||||
|
(`port` || `port_range`) &&
|
||||||
|
(`source_geoip` || `source_ip_cidr`) &&
|
||||||
|
(`source_port` || `source_port_range`) &&
|
||||||
|
`other fields`
|
||||||
|
|
||||||
|
#### inbound
|
||||||
|
|
||||||
|
[入站](/zh/configuration/inbound) 标签。
|
||||||
|
|
||||||
|
#### ip_version
|
||||||
|
|
||||||
|
4 或 6。
|
||||||
|
|
||||||
|
默认不限制。
|
||||||
|
|
||||||
|
#### network
|
||||||
|
|
||||||
|
匹配网络协议。
|
||||||
|
|
||||||
|
可用值:
|
||||||
|
|
||||||
|
* `tcp`
|
||||||
|
* `udp`
|
||||||
|
* `icmpv4`
|
||||||
|
* `icmpv6`
|
||||||
|
|
||||||
|
#### domain
|
||||||
|
|
||||||
|
匹配完整域名。
|
||||||
|
|
||||||
|
#### domain_suffix
|
||||||
|
|
||||||
|
匹配域名后缀。
|
||||||
|
|
||||||
|
#### domain_keyword
|
||||||
|
|
||||||
|
匹配域名关键字。
|
||||||
|
|
||||||
|
#### domain_regex
|
||||||
|
|
||||||
|
匹配域名正则表达式。
|
||||||
|
|
||||||
|
#### geosite
|
||||||
|
|
||||||
|
匹配 GeoSite。
|
||||||
|
|
||||||
|
#### source_geoip
|
||||||
|
|
||||||
|
匹配源 GeoIP。
|
||||||
|
|
||||||
|
#### geoip
|
||||||
|
|
||||||
|
匹配 GeoIP。
|
||||||
|
|
||||||
|
#### source_ip_cidr
|
||||||
|
|
||||||
|
匹配源 IP CIDR。
|
||||||
|
|
||||||
|
#### ip_cidr
|
||||||
|
|
||||||
|
匹配 IP CIDR。
|
||||||
|
|
||||||
|
#### source_port
|
||||||
|
|
||||||
|
匹配源端口。
|
||||||
|
|
||||||
|
#### source_port_range
|
||||||
|
|
||||||
|
匹配源端口范围。
|
||||||
|
|
||||||
|
#### port
|
||||||
|
|
||||||
|
匹配端口。
|
||||||
|
|
||||||
|
#### port_range
|
||||||
|
|
||||||
|
匹配端口范围。
|
||||||
|
|
||||||
|
#### invert
|
||||||
|
|
||||||
|
反选匹配结果。
|
||||||
|
|
||||||
|
#### action
|
||||||
|
|
||||||
|
==必填==
|
||||||
|
|
||||||
|
| Action | 描述 |
|
||||||
|
|--------|---------------------|
|
||||||
|
| return | 停止 IP 路由并将该连接组装到传输层 |
|
||||||
|
| block | 屏蔽该连接 |
|
||||||
|
| direct | 直接转发该连接 |
|
||||||
|
|
||||||
|
|
||||||
|
#### outbound
|
||||||
|
|
||||||
|
==action 为 direct 则必填==
|
||||||
|
|
||||||
|
目标出站的标签。
|
||||||
|
|
||||||
|
### 逻辑字段
|
||||||
|
|
||||||
|
#### type
|
||||||
|
|
||||||
|
`logical`
|
||||||
|
|
||||||
|
#### mode
|
||||||
|
|
||||||
|
==必填==
|
||||||
|
|
||||||
|
`and` 或 `or`
|
||||||
|
|
||||||
|
#### rules
|
||||||
|
|
||||||
|
==必填==
|
||||||
|
|
||||||
|
包括的默认规则。
|
||||||
@@ -9,7 +9,9 @@
|
|||||||
"mixed-in"
|
"mixed-in"
|
||||||
],
|
],
|
||||||
"ip_version": 6,
|
"ip_version": 6,
|
||||||
"network": "tcp",
|
"network": [
|
||||||
|
"tcp"
|
||||||
|
],
|
||||||
"auth_user": [
|
"auth_user": [
|
||||||
"usera",
|
"usera",
|
||||||
"userb"
|
"userb"
|
||||||
@@ -244,18 +246,12 @@ Tag of the target outbound.
|
|||||||
|
|
||||||
#### mode
|
#### mode
|
||||||
|
|
||||||
|
==Required==
|
||||||
|
|
||||||
`and` or `or`
|
`and` or `or`
|
||||||
|
|
||||||
#### rules
|
#### rules
|
||||||
|
|
||||||
Included default rules.
|
|
||||||
|
|
||||||
#### invert
|
|
||||||
|
|
||||||
Invert match result.
|
|
||||||
|
|
||||||
#### outbound
|
|
||||||
|
|
||||||
==Required==
|
==Required==
|
||||||
|
|
||||||
Tag of the target outbound.
|
Included default rules.
|
||||||
|
|||||||
@@ -9,7 +9,9 @@
|
|||||||
"mixed-in"
|
"mixed-in"
|
||||||
],
|
],
|
||||||
"ip_version": 6,
|
"ip_version": 6,
|
||||||
"network": "tcp",
|
"network": [
|
||||||
|
"tcp"
|
||||||
|
],
|
||||||
"auth_user": [
|
"auth_user": [
|
||||||
"usera",
|
"usera",
|
||||||
"userb"
|
"userb"
|
||||||
@@ -242,18 +244,12 @@
|
|||||||
|
|
||||||
#### mode
|
#### mode
|
||||||
|
|
||||||
|
==必填==
|
||||||
|
|
||||||
`and` 或 `or`
|
`and` 或 `or`
|
||||||
|
|
||||||
#### rules
|
#### rules
|
||||||
|
|
||||||
包括的默认规则。
|
|
||||||
|
|
||||||
#### invert
|
|
||||||
|
|
||||||
反选匹配结果。
|
|
||||||
|
|
||||||
#### outbound
|
|
||||||
|
|
||||||
==必填==
|
==必填==
|
||||||
|
|
||||||
目标出站的标签。
|
包括的默认规则。
|
||||||
@@ -10,7 +10,8 @@
|
|||||||
"protocol": "smux",
|
"protocol": "smux",
|
||||||
"max_connections": 4,
|
"max_connections": 4,
|
||||||
"min_streams": 4,
|
"min_streams": 4,
|
||||||
"max_streams": 0
|
"max_streams": 0,
|
||||||
|
"padding": false
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -28,6 +29,7 @@ Multiplex protocol.
|
|||||||
|----------|------------------------------------|
|
|----------|------------------------------------|
|
||||||
| smux | https://github.com/xtaci/smux |
|
| smux | https://github.com/xtaci/smux |
|
||||||
| yamux | https://github.com/hashicorp/yamux |
|
| yamux | https://github.com/hashicorp/yamux |
|
||||||
|
| h2mux | https://golang.org/x/net/http2 |
|
||||||
|
|
||||||
SMux is used by default.
|
SMux is used by default.
|
||||||
|
|
||||||
@@ -48,3 +50,12 @@ Conflict with `max_streams`.
|
|||||||
Maximum multiplexed streams in a connection before opening a new connection.
|
Maximum multiplexed streams in a connection before opening a new connection.
|
||||||
|
|
||||||
Conflict with `max_connections` and `min_streams`.
|
Conflict with `max_connections` and `min_streams`.
|
||||||
|
|
||||||
|
#### padding
|
||||||
|
|
||||||
|
!!! info
|
||||||
|
|
||||||
|
Requires sing-box server version 1.3-beta9 or later.
|
||||||
|
|
||||||
|
Enable padding.
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@
|
|||||||
|-------|------------------------------------|
|
|-------|------------------------------------|
|
||||||
| smux | https://github.com/xtaci/smux |
|
| smux | https://github.com/xtaci/smux |
|
||||||
| yamux | https://github.com/hashicorp/yamux |
|
| yamux | https://github.com/hashicorp/yamux |
|
||||||
|
| h2mux | https://golang.org/x/net/http2 |
|
||||||
|
|
||||||
默认使用 SMux。
|
默认使用 SMux。
|
||||||
|
|
||||||
@@ -47,4 +48,13 @@
|
|||||||
|
|
||||||
在打开新连接之前,连接中的最大多路复用流数量。
|
在打开新连接之前,连接中的最大多路复用流数量。
|
||||||
|
|
||||||
与 `max_connections` 和 `min_streams` 冲突。
|
与 `max_connections` 和 `min_streams` 冲突。
|
||||||
|
|
||||||
|
#### padding
|
||||||
|
|
||||||
|
!!! info
|
||||||
|
|
||||||
|
需要 sing-box 服务器版本 1.3-beta9 或更高。
|
||||||
|
|
||||||
|
启用填充。
|
||||||
|
|
||||||
|
|||||||
@@ -8,3 +8,4 @@ Configuration examples for sing-box.
|
|||||||
* [Shadowsocks](./shadowsocks)
|
* [Shadowsocks](./shadowsocks)
|
||||||
* [ShadowTLS](./shadowtls)
|
* [ShadowTLS](./shadowtls)
|
||||||
* [Clash API](./clash-api)
|
* [Clash API](./clash-api)
|
||||||
|
* [WireGuard Direct](./wireguard-direct)
|
||||||
|
|||||||
@@ -8,3 +8,4 @@ sing-box 的配置示例。
|
|||||||
* [Shadowsocks](./shadowsocks)
|
* [Shadowsocks](./shadowsocks)
|
||||||
* [ShadowTLS](./shadowtls)
|
* [ShadowTLS](./shadowtls)
|
||||||
* [Clash API](./clash-api)
|
* [Clash API](./clash-api)
|
||||||
|
* [WireGuard Direct](./wireguard-direct)
|
||||||
|
|||||||
90
docs/examples/wireguard-direct.md
Normal file
90
docs/examples/wireguard-direct.md
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
# WireGuard Direct
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"dns": {
|
||||||
|
"servers": [
|
||||||
|
{
|
||||||
|
"tag": "google",
|
||||||
|
"address": "tls://8.8.8.8"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tag": "local",
|
||||||
|
"address": "223.5.5.5",
|
||||||
|
"detour": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"geoip": "cn",
|
||||||
|
"server": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"reverse_mapping": true
|
||||||
|
},
|
||||||
|
"inbounds": [
|
||||||
|
{
|
||||||
|
"type": "tun",
|
||||||
|
"tag": "tun",
|
||||||
|
"inet4_address": "172.19.0.1/30",
|
||||||
|
"auto_route": true,
|
||||||
|
"sniff": true,
|
||||||
|
"stack": "system"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outbounds": [
|
||||||
|
{
|
||||||
|
"type": "wireguard",
|
||||||
|
"tag": "wg",
|
||||||
|
"server": "127.0.0.1",
|
||||||
|
"server_port": 2345,
|
||||||
|
"local_address": [
|
||||||
|
"172.19.0.1/128"
|
||||||
|
],
|
||||||
|
"private_key": "KLTnpPY03pig/WC3zR8U7VWmpANHPFh2/4pwICGJ5Fk=",
|
||||||
|
"peer_public_key": "uvNabcamf6Rs0vzmcw99jsjTJbxo6eWGOykSY66zsUk="
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "dns",
|
||||||
|
"tag": "dns"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "direct",
|
||||||
|
"tag": "direct"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "block",
|
||||||
|
"tag": "block"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"route": {
|
||||||
|
"ip_rules": [
|
||||||
|
{
|
||||||
|
"port": 53,
|
||||||
|
"action": "return"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"geoip": "cn",
|
||||||
|
"geosite": "cn",
|
||||||
|
"action": "return"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"action": "direct",
|
||||||
|
"outbound": "wg"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"rules": [
|
||||||
|
{
|
||||||
|
"protocol": "dns",
|
||||||
|
"outbound": "dns"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"geoip": "cn",
|
||||||
|
"geosite": "cn",
|
||||||
|
"outbound": "direct"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"auto_detect_interface": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
20
docs/faq/fakeip.md
Normal file
20
docs/faq/fakeip.md
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
# FakeIP
|
||||||
|
|
||||||
|
FakeIP refers to a type of behavior in a program that simultaneously hijacks both DNS and connection requests. It
|
||||||
|
responds to DNS requests with virtual results and restores mapping when accepting connections.
|
||||||
|
|
||||||
|
#### Advantage
|
||||||
|
|
||||||
|
* Retrieve the requested domain in places like IP routing (L3) where traffic detection is not possible to assist with routing.
|
||||||
|
* Decrease an RTT on the first TCP request to a domain (the most common reason).
|
||||||
|
|
||||||
|
#### Limitation
|
||||||
|
|
||||||
|
* Its mechanism breaks applications that depend on returning correct remote addresses.
|
||||||
|
* Only A and AAAA (IP) requests are supported, which may break applications that rely on other requests.
|
||||||
|
|
||||||
|
#### Recommendation
|
||||||
|
|
||||||
|
* Do not use if you do not need L3 routing.
|
||||||
|
* If using tun, make sure FakeIP ranges is included in the tun's routes.
|
||||||
|
* Enable `experimental.clash_api.store_fakeip` to persist FakeIP records, or use `dns.rules.rewrite_ttl` to avoid losing records after program restart in DNS cached environments.
|
||||||
19
docs/faq/fakeip.zh.md
Normal file
19
docs/faq/fakeip.zh.md
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# FakeIP
|
||||||
|
|
||||||
|
FakeIP 是指同时劫持 DNS 和连接请求的程序中的一种行为。它通过虚拟结果响应 DNS 请求,在接受连接时恢复映射。
|
||||||
|
|
||||||
|
#### 优点
|
||||||
|
|
||||||
|
* 在像 L3 路由这样无法进行流量探测的地方检索所请求的域名,以协助路由。
|
||||||
|
* 减少对一个域的第一个 TCP 请求的 RTT(这是最常见的原因)。
|
||||||
|
|
||||||
|
#### 限制
|
||||||
|
|
||||||
|
* 它的机制会破坏依赖于返回正确远程地址的应用程序。
|
||||||
|
* 仅支持 A 和 AAAA(IP)请求,这可能会破坏依赖于其他请求的应用程序。
|
||||||
|
|
||||||
|
#### 建议
|
||||||
|
|
||||||
|
* 如果不需要 L3 路由,请勿使用。
|
||||||
|
* 如果使用 tun,请确保 tun 路由中包含 FakeIP 地址范围。
|
||||||
|
* 启用 `experimental.clash_api.store_fakeip` 以持久化 FakeIP 记录,或者使用 `dns.rules.rewrite_ttl` 避免程序重启后在 DNS 被缓存的环境中丢失记录。
|
||||||
@@ -11,12 +11,6 @@ it doesn't fit, because it compromises performance or design clarity, or because
|
|||||||
If it bothers you that sing-box is missing feature X, please forgive us and investigate the features that sing-box does
|
If it bothers you that sing-box is missing feature X, please forgive us and investigate the features that sing-box does
|
||||||
have. You might find that they compensate in interesting ways for the lack of X.
|
have. You might find that they compensate in interesting ways for the lack of X.
|
||||||
|
|
||||||
#### Fake IP
|
|
||||||
|
|
||||||
Fake IP (also called Fake DNS) is an invasive and imperfect DNS solution that breaks expected behavior, causes DNS leaks
|
|
||||||
and makes many software unusable. It is recommended by some software that lacks DNS processing and caching, but sing-box
|
|
||||||
does not need this.
|
|
||||||
|
|
||||||
#### Naive outbound
|
#### Naive outbound
|
||||||
|
|
||||||
NaïveProxy's main function is chromium's network stack, and it makes no sense to implement only its transport protocol.
|
NaïveProxy's main function is chromium's network stack, and it makes no sense to implement only its transport protocol.
|
||||||
|
|||||||
@@ -9,11 +9,6 @@
|
|||||||
|
|
||||||
如果 sing-box 缺少功能 X 让您感到困扰,请原谅我们并调查 sing-box 确实有的功能。 您可能会发现它们以有趣的方式弥补了 X 的缺失。
|
如果 sing-box 缺少功能 X 让您感到困扰,请原谅我们并调查 sing-box 确实有的功能。 您可能会发现它们以有趣的方式弥补了 X 的缺失。
|
||||||
|
|
||||||
#### Fake IP
|
|
||||||
|
|
||||||
Fake IP(也称 Fake DNS)是一种侵入性和不完善的 DNS 解决方案,它打破了预期的行为,导致 DNS 泄漏并使许多软件无法使用。
|
|
||||||
一些缺乏 DNS 处理和缓存的软件推荐使用它,但 sing-box 不需要。
|
|
||||||
|
|
||||||
#### Naive 出站
|
#### Naive 出站
|
||||||
|
|
||||||
NaïveProxy 的主要功能是 chromium 的网络栈,仅实现它的传输协议是舍本逐末的。
|
NaïveProxy 的主要功能是 chromium 的网络栈,仅实现它的传输协议是舍本逐末的。
|
||||||
|
|||||||
17
docs/installation/clients/sfa.md
Normal file
17
docs/installation/clients/sfa.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# SFA
|
||||||
|
|
||||||
|
Experimental Android client for sing-box.
|
||||||
|
|
||||||
|
#### Requirements
|
||||||
|
|
||||||
|
* Android 5.0+
|
||||||
|
|
||||||
|
#### Download
|
||||||
|
|
||||||
|
* [AppCenter](https://install.appcenter.ms/users/nekohasekai/apps/sfa/distribution_groups/publictest)
|
||||||
|
|
||||||
|
#### Note
|
||||||
|
|
||||||
|
* User Agent in remote profile request is `SFA/$version ($version_code; sing-box $sing_box_version)`
|
||||||
|
* The working directory is located at `/sdcard/Android/data/io.nekohasekai.sfa/files` (External files directory)
|
||||||
|
* Crash logs is located in `$working_directory/stderr.log`
|
||||||
17
docs/installation/clients/sfa.zh.md
Normal file
17
docs/installation/clients/sfa.zh.md
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
# SFA
|
||||||
|
|
||||||
|
实验性的 Android sing-box 客户端。
|
||||||
|
|
||||||
|
#### 要求
|
||||||
|
|
||||||
|
* Android 5.0+
|
||||||
|
|
||||||
|
#### 下载
|
||||||
|
|
||||||
|
* [AppCenter](https://install.appcenter.ms/users/nekohasekai/apps/sfa/distribution_groups/publictest)
|
||||||
|
|
||||||
|
#### 注意事项
|
||||||
|
|
||||||
|
* 远程配置文件请求中的 User Agent 为 `SFA/$version ($version_code; sing-box $sing_box_version)`
|
||||||
|
* 工作目录位于 `/sdcard/Android/data/io.nekohasekai.sfa/files` (外部文件目录)
|
||||||
|
* 崩溃日志位于 `$working_directory/stderr.log`
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# SFI
|
# SFI
|
||||||
|
|
||||||
Experimental official iOS client for sing-box.
|
Experimental iOS client for sing-box.
|
||||||
|
|
||||||
#### Requirements
|
#### Requirements
|
||||||
|
|
||||||
@@ -11,9 +11,10 @@ Experimental official iOS client for sing-box.
|
|||||||
|
|
||||||
* [TestFlight](https://testflight.apple.com/join/c6ylui2j)
|
* [TestFlight](https://testflight.apple.com/join/c6ylui2j)
|
||||||
|
|
||||||
#### Limit
|
#### Note
|
||||||
|
|
||||||
* `system` tun stack not working
|
* User Agent in remote profile request is `SFA/$version ($version_code; sing-box $sing_box_version)`
|
||||||
|
* Crash logs is located in `Settings` -> `View Service Log`
|
||||||
|
|
||||||
#### Privacy policy
|
#### Privacy policy
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# SFI
|
# SFI
|
||||||
|
|
||||||
实验性的官方 iOS sing-box 客户端。
|
实验性的 iOS sing-box 客户端。
|
||||||
|
|
||||||
#### 要求
|
#### 要求
|
||||||
|
|
||||||
@@ -11,9 +11,10 @@
|
|||||||
|
|
||||||
* [TestFlight](https://testflight.apple.com/join/c6ylui2j)
|
* [TestFlight](https://testflight.apple.com/join/c6ylui2j)
|
||||||
|
|
||||||
#### 限制
|
#### 注意事项
|
||||||
|
|
||||||
* `system` tun stack 不工作
|
* 远程配置文件请求中的 User Agent 为 `SFI/$version ($version_code; sing-box $sing_box_version)`
|
||||||
|
* 崩溃日志位于 `设置` -> `查看服务日志`
|
||||||
|
|
||||||
#### 隐私政策
|
#### 隐私政策
|
||||||
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package experimental
|
package experimental
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
@@ -8,7 +9,7 @@ import (
|
|||||||
"github.com/sagernet/sing-box/option"
|
"github.com/sagernet/sing-box/option"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ClashServerConstructor = func(router adapter.Router, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error)
|
type ClashServerConstructor = func(ctx context.Context, router adapter.Router, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error)
|
||||||
|
|
||||||
var clashServerConstructor ClashServerConstructor
|
var clashServerConstructor ClashServerConstructor
|
||||||
|
|
||||||
@@ -16,9 +17,9 @@ func RegisterClashServerConstructor(constructor ClashServerConstructor) {
|
|||||||
clashServerConstructor = constructor
|
clashServerConstructor = constructor
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewClashServer(router adapter.Router, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error) {
|
func NewClashServer(ctx context.Context, router adapter.Router, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error) {
|
||||||
if clashServerConstructor == nil {
|
if clashServerConstructor == nil {
|
||||||
return nil, os.ErrInvalid
|
return nil, os.ErrInvalid
|
||||||
}
|
}
|
||||||
return clashServerConstructor(router, logFactory, options)
|
return clashServerConstructor(ctx, router, logFactory, options)
|
||||||
}
|
}
|
||||||
|
|||||||
78
experimental/clashapi/api_meta.go
Normal file
78
experimental/clashapi/api_meta.go
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
package clashapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/common/json"
|
||||||
|
"github.com/sagernet/sing-box/experimental/clashapi/trafficontrol"
|
||||||
|
"github.com/sagernet/websocket"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/go-chi/render"
|
||||||
|
)
|
||||||
|
|
||||||
|
// API created by Clash.Meta
|
||||||
|
|
||||||
|
func (s *Server) setupMetaAPI(r chi.Router) {
|
||||||
|
r.Get("/memory", memory(s.trafficManager))
|
||||||
|
r.Mount("/group", groupRouter(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
type Memory struct {
|
||||||
|
Inuse uint64 `json:"inuse"`
|
||||||
|
OSLimit uint64 `json:"oslimit"` // maybe we need it in the future
|
||||||
|
}
|
||||||
|
|
||||||
|
func memory(trafficManager *trafficontrol.Manager) func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var wsConn *websocket.Conn
|
||||||
|
if websocket.IsWebSocketUpgrade(r) {
|
||||||
|
var err error
|
||||||
|
wsConn, err = upgrader.Upgrade(w, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if wsConn == nil {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
render.Status(r, http.StatusOK)
|
||||||
|
}
|
||||||
|
|
||||||
|
tick := time.NewTicker(time.Second)
|
||||||
|
defer tick.Stop()
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
var err error
|
||||||
|
first := true
|
||||||
|
for range tick.C {
|
||||||
|
buf.Reset()
|
||||||
|
|
||||||
|
inuse := trafficManager.Snapshot().Memory
|
||||||
|
|
||||||
|
// make chat.js begin with zero
|
||||||
|
// this is shit var,but we need output 0 for first time
|
||||||
|
if first {
|
||||||
|
first = false
|
||||||
|
inuse = 0
|
||||||
|
}
|
||||||
|
if err := json.NewEncoder(buf).Encode(Memory{
|
||||||
|
Inuse: inuse,
|
||||||
|
OSLimit: 0,
|
||||||
|
}); err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if wsConn == nil {
|
||||||
|
_, err = w.Write(buf.Bytes())
|
||||||
|
w.(http.Flusher).Flush()
|
||||||
|
} else {
|
||||||
|
err = wsConn.WriteMessage(websocket.TextMessage, buf.Bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
136
experimental/clashapi/api_meta_group.go
Normal file
136
experimental/clashapi/api_meta_group.go
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
package clashapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/adapter"
|
||||||
|
"github.com/sagernet/sing-box/common/badjson"
|
||||||
|
"github.com/sagernet/sing-box/common/urltest"
|
||||||
|
"github.com/sagernet/sing-box/outbound"
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
"github.com/sagernet/sing/common/batch"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/go-chi/render"
|
||||||
|
)
|
||||||
|
|
||||||
|
func groupRouter(server *Server) http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
r.Get("/", getGroups(server))
|
||||||
|
r.Route("/{name}", func(r chi.Router) {
|
||||||
|
r.Use(parseProxyName, findProxyByName(server.router))
|
||||||
|
r.Get("/", getGroup(server))
|
||||||
|
r.Get("/delay", getGroupDelay(server))
|
||||||
|
})
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func getGroups(server *Server) func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
groups := common.Map(common.Filter(server.router.Outbounds(), func(it adapter.Outbound) bool {
|
||||||
|
_, isGroup := it.(adapter.OutboundGroup)
|
||||||
|
return isGroup
|
||||||
|
}), func(it adapter.Outbound) *badjson.JSONObject {
|
||||||
|
return proxyInfo(server, it)
|
||||||
|
})
|
||||||
|
render.JSON(w, r, render.M{
|
||||||
|
"proxies": groups,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getGroup(server *Server) func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
|
||||||
|
if _, ok := proxy.(adapter.OutboundGroup); ok {
|
||||||
|
render.JSON(w, r, proxyInfo(server, proxy))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
render.Status(r, http.StatusNotFound)
|
||||||
|
render.JSON(w, r, ErrNotFound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getGroupDelay(server *Server) func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
|
||||||
|
group, ok := proxy.(adapter.OutboundGroup)
|
||||||
|
if !ok {
|
||||||
|
render.Status(r, http.StatusNotFound)
|
||||||
|
render.JSON(w, r, ErrNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
query := r.URL.Query()
|
||||||
|
url := query.Get("url")
|
||||||
|
if strings.HasPrefix(url, "http://") {
|
||||||
|
url = ""
|
||||||
|
}
|
||||||
|
timeout, err := strconv.ParseInt(query.Get("timeout"), 10, 32)
|
||||||
|
if err != nil {
|
||||||
|
render.Status(r, http.StatusBadRequest)
|
||||||
|
render.JSON(w, r, ErrBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), time.Millisecond*time.Duration(timeout))
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var result map[string]uint16
|
||||||
|
if urlTestGroup, isURLTestGroup := group.(adapter.URLTestGroup); isURLTestGroup {
|
||||||
|
result, err = urlTestGroup.URLTest(ctx, url)
|
||||||
|
} else {
|
||||||
|
outbounds := common.FilterNotNil(common.Map(group.All(), func(it string) adapter.Outbound {
|
||||||
|
itOutbound, _ := server.router.Outbound(it)
|
||||||
|
return itOutbound
|
||||||
|
}))
|
||||||
|
b, _ := batch.New(ctx, batch.WithConcurrencyNum[any](10))
|
||||||
|
checked := make(map[string]bool)
|
||||||
|
result = make(map[string]uint16)
|
||||||
|
var resultAccess sync.Mutex
|
||||||
|
for _, detour := range outbounds {
|
||||||
|
tag := detour.Tag()
|
||||||
|
realTag := outbound.RealTag(detour)
|
||||||
|
if checked[realTag] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
checked[realTag] = true
|
||||||
|
p, loaded := server.router.Outbound(realTag)
|
||||||
|
if !loaded {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
b.Go(realTag, func() (any, error) {
|
||||||
|
t, err := urltest.URLTest(ctx, url, p)
|
||||||
|
if err != nil {
|
||||||
|
server.logger.Debug("outbound ", tag, " unavailable: ", err)
|
||||||
|
server.urlTestHistory.DeleteURLTestHistory(realTag)
|
||||||
|
} else {
|
||||||
|
server.logger.Debug("outbound ", tag, " available: ", t, "ms")
|
||||||
|
server.urlTestHistory.StoreURLTestHistory(realTag, &urltest.History{
|
||||||
|
Time: time.Now(),
|
||||||
|
Delay: t,
|
||||||
|
})
|
||||||
|
resultAccess.Lock()
|
||||||
|
result[tag] = t
|
||||||
|
resultAccess.Unlock()
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
b.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
render.Status(r, http.StatusGatewayTimeout)
|
||||||
|
render.JSON(w, r, newError(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
render.JSON(w, r, result)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,21 +3,28 @@ package clashapi
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/adapter"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
"github.com/go-chi/render"
|
"github.com/go-chi/render"
|
||||||
)
|
)
|
||||||
|
|
||||||
func cacheRouter() http.Handler {
|
func cacheRouter(router adapter.Router) http.Handler {
|
||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
r.Post("/fakeip/flush", flushFakeip)
|
r.Post("/fakeip/flush", flushFakeip(router))
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
func flushFakeip(w http.ResponseWriter, r *http.Request) {
|
func flushFakeip(router adapter.Router) func(w http.ResponseWriter, r *http.Request) {
|
||||||
/*if err := cachefile.Cache().FlushFakeip(); err != nil {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
render.Status(r, http.StatusInternalServerError)
|
if cacheFile := router.ClashServer().CacheFile(); cacheFile != nil {
|
||||||
render.JSON(w, r, newError(err.Error()))
|
err := cacheFile.FakeIPReset()
|
||||||
return
|
if err != nil {
|
||||||
}*/
|
render.Status(r, http.StatusInternalServerError)
|
||||||
render.NoContent(w, r)
|
render.JSON(w, r, newError(err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
render.NoContent(w, r)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
77
experimental/clashapi/cachefile/fakeip.go
Normal file
77
experimental/clashapi/cachefile/fakeip.go
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
package cachefile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/adapter"
|
||||||
|
|
||||||
|
"go.etcd.io/bbolt"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
bucketFakeIP = []byte("fakeip")
|
||||||
|
keyMetadata = []byte("metadata")
|
||||||
|
)
|
||||||
|
|
||||||
|
func (c *CacheFile) FakeIPMetadata() *adapter.FakeIPMetadata {
|
||||||
|
var metadata adapter.FakeIPMetadata
|
||||||
|
err := c.DB.View(func(tx *bbolt.Tx) error {
|
||||||
|
bucket := tx.Bucket(bucketFakeIP)
|
||||||
|
if bucket == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
metadataBinary := bucket.Get(keyMetadata)
|
||||||
|
if len(metadataBinary) == 0 {
|
||||||
|
return os.ErrInvalid
|
||||||
|
}
|
||||||
|
return metadata.UnmarshalBinary(metadataBinary)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *CacheFile) FakeIPSaveMetadata(metadata *adapter.FakeIPMetadata) error {
|
||||||
|
return c.DB.Batch(func(tx *bbolt.Tx) error {
|
||||||
|
bucket, err := tx.CreateBucketIfNotExists(bucketFakeIP)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
metadataBinary, err := metadata.MarshalBinary()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return bucket.Put(keyMetadata, metadataBinary)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *CacheFile) FakeIPStore(address netip.Addr, domain string) error {
|
||||||
|
return c.DB.Batch(func(tx *bbolt.Tx) error {
|
||||||
|
bucket, err := tx.CreateBucketIfNotExists(bucketFakeIP)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return bucket.Put(address.AsSlice(), []byte(domain))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *CacheFile) FakeIPLoad(address netip.Addr) (string, bool) {
|
||||||
|
var domain string
|
||||||
|
_ = c.DB.View(func(tx *bbolt.Tx) error {
|
||||||
|
bucket := tx.Bucket(bucketFakeIP)
|
||||||
|
if bucket == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
domain = string(bucket.Get(address.AsSlice()))
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
return domain, domain != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *CacheFile) FakeIPReset() error {
|
||||||
|
return c.DB.Batch(func(tx *bbolt.Tx) error {
|
||||||
|
return tx.DeleteBucket(bucketFakeIP)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
@@ -214,6 +215,9 @@ func getProxyDelay(server *Server) func(w http.ResponseWriter, r *http.Request)
|
|||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
query := r.URL.Query()
|
query := r.URL.Query()
|
||||||
url := query.Get("url")
|
url := query.Get("url")
|
||||||
|
if strings.HasPrefix(url, "http://") {
|
||||||
|
url = ""
|
||||||
|
}
|
||||||
timeout, err := strconv.ParseInt(query.Get("timeout"), 10, 16)
|
timeout, err := strconv.ParseInt(query.Get("timeout"), 10, 16)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
render.Status(r, http.StatusBadRequest)
|
render.Status(r, http.StatusBadRequest)
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import (
|
|||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
F "github.com/sagernet/sing/common/format"
|
F "github.com/sagernet/sing/common/format"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
"github.com/sagernet/sing/service/filemanager"
|
||||||
"github.com/sagernet/websocket"
|
"github.com/sagernet/websocket"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
@@ -37,6 +38,7 @@ func init() {
|
|||||||
var _ adapter.ClashServer = (*Server)(nil)
|
var _ adapter.ClashServer = (*Server)(nil)
|
||||||
|
|
||||||
type Server struct {
|
type Server struct {
|
||||||
|
ctx context.Context
|
||||||
router adapter.Router
|
router adapter.Router
|
||||||
logger log.Logger
|
logger log.Logger
|
||||||
httpServer *http.Server
|
httpServer *http.Server
|
||||||
@@ -44,29 +46,38 @@ type Server struct {
|
|||||||
urlTestHistory *urltest.HistoryStorage
|
urlTestHistory *urltest.HistoryStorage
|
||||||
mode string
|
mode string
|
||||||
storeSelected bool
|
storeSelected bool
|
||||||
|
storeFakeIP bool
|
||||||
cacheFilePath string
|
cacheFilePath string
|
||||||
cacheFile adapter.ClashCacheFile
|
cacheFile adapter.ClashCacheFile
|
||||||
|
|
||||||
|
externalUI string
|
||||||
|
externalUIDownloadURL string
|
||||||
|
externalUIDownloadDetour string
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewServer(router adapter.Router, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error) {
|
func NewServer(ctx context.Context, router adapter.Router, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error) {
|
||||||
trafficManager := trafficontrol.NewManager()
|
trafficManager := trafficontrol.NewManager()
|
||||||
chiRouter := chi.NewRouter()
|
chiRouter := chi.NewRouter()
|
||||||
server := &Server{
|
server := &Server{
|
||||||
|
ctx: ctx,
|
||||||
router: router,
|
router: router,
|
||||||
logger: logFactory.NewLogger("clash-api"),
|
logger: logFactory.NewLogger("clash-api"),
|
||||||
httpServer: &http.Server{
|
httpServer: &http.Server{
|
||||||
Addr: options.ExternalController,
|
Addr: options.ExternalController,
|
||||||
Handler: chiRouter,
|
Handler: chiRouter,
|
||||||
},
|
},
|
||||||
trafficManager: trafficManager,
|
trafficManager: trafficManager,
|
||||||
urlTestHistory: urltest.NewHistoryStorage(),
|
urlTestHistory: urltest.NewHistoryStorage(),
|
||||||
mode: strings.ToLower(options.DefaultMode),
|
mode: strings.ToLower(options.DefaultMode),
|
||||||
|
storeSelected: options.StoreSelected,
|
||||||
|
storeFakeIP: options.StoreFakeIP,
|
||||||
|
externalUIDownloadURL: options.ExternalUIDownloadURL,
|
||||||
|
externalUIDownloadDetour: options.ExternalUIDownloadDetour,
|
||||||
}
|
}
|
||||||
if server.mode == "" {
|
if server.mode == "" {
|
||||||
server.mode = "rule"
|
server.mode = "rule"
|
||||||
}
|
}
|
||||||
if options.StoreSelected {
|
if options.StoreSelected || options.StoreFakeIP {
|
||||||
server.storeSelected = true
|
|
||||||
cachePath := os.ExpandEnv(options.CacheFile)
|
cachePath := os.ExpandEnv(options.CacheFile)
|
||||||
if cachePath == "" {
|
if cachePath == "" {
|
||||||
cachePath = "cache.db"
|
cachePath = "cache.db"
|
||||||
@@ -74,7 +85,7 @@ func NewServer(router adapter.Router, logFactory log.ObservableFactory, options
|
|||||||
if foundPath, loaded := C.FindPath(cachePath); loaded {
|
if foundPath, loaded := C.FindPath(cachePath); loaded {
|
||||||
cachePath = foundPath
|
cachePath = foundPath
|
||||||
} else {
|
} else {
|
||||||
cachePath = C.BasePath(cachePath)
|
cachePath = filemanager.BasePath(ctx, cachePath)
|
||||||
}
|
}
|
||||||
server.cacheFilePath = cachePath
|
server.cacheFilePath = cachePath
|
||||||
}
|
}
|
||||||
@@ -99,12 +110,15 @@ func NewServer(router adapter.Router, logFactory log.ObservableFactory, options
|
|||||||
r.Mount("/providers/rules", ruleProviderRouter())
|
r.Mount("/providers/rules", ruleProviderRouter())
|
||||||
r.Mount("/script", scriptRouter())
|
r.Mount("/script", scriptRouter())
|
||||||
r.Mount("/profile", profileRouter())
|
r.Mount("/profile", profileRouter())
|
||||||
r.Mount("/cache", cacheRouter())
|
r.Mount("/cache", cacheRouter(router))
|
||||||
r.Mount("/dns", dnsRouter(router))
|
r.Mount("/dns", dnsRouter(router))
|
||||||
|
|
||||||
|
server.setupMetaAPI(r)
|
||||||
})
|
})
|
||||||
if options.ExternalUI != "" {
|
if options.ExternalUI != "" {
|
||||||
|
server.externalUI = filemanager.BasePath(ctx, os.ExpandEnv(options.ExternalUI))
|
||||||
chiRouter.Group(func(r chi.Router) {
|
chiRouter.Group(func(r chi.Router) {
|
||||||
fs := http.StripPrefix("/ui", http.FileServer(http.Dir(C.BasePath(os.ExpandEnv(options.ExternalUI)))))
|
fs := http.StripPrefix("/ui", http.FileServer(http.Dir(server.externalUI)))
|
||||||
r.Get("/ui", http.RedirectHandler("/ui/", http.StatusTemporaryRedirect).ServeHTTP)
|
r.Get("/ui", http.RedirectHandler("/ui/", http.StatusTemporaryRedirect).ServeHTTP)
|
||||||
r.Get("/ui/*", func(w http.ResponseWriter, r *http.Request) {
|
r.Get("/ui/*", func(w http.ResponseWriter, r *http.Request) {
|
||||||
fs.ServeHTTP(w, r)
|
fs.ServeHTTP(w, r)
|
||||||
@@ -126,6 +140,7 @@ func (s *Server) PreStart() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) Start() error {
|
func (s *Server) Start() error {
|
||||||
|
s.checkAndDownloadExternalUI()
|
||||||
listener, err := net.Listen("tcp", s.httpServer.Addr)
|
listener, err := net.Listen("tcp", s.httpServer.Addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return E.Cause(err, "external controller listen error")
|
return E.Cause(err, "external controller listen error")
|
||||||
@@ -156,6 +171,10 @@ func (s *Server) StoreSelected() bool {
|
|||||||
return s.storeSelected
|
return s.storeSelected
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Server) StoreFakeIP() bool {
|
||||||
|
return s.storeFakeIP
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) CacheFile() adapter.ClashCacheFile {
|
func (s *Server) CacheFile() adapter.ClashCacheFile {
|
||||||
return s.cacheFile
|
return s.cacheFile
|
||||||
}
|
}
|
||||||
@@ -392,5 +411,5 @@ func getLogs(logFactory log.ObservableFactory) func(w http.ResponseWriter, r *ht
|
|||||||
}
|
}
|
||||||
|
|
||||||
func version(w http.ResponseWriter, r *http.Request) {
|
func version(w http.ResponseWriter, r *http.Request) {
|
||||||
render.JSON(w, r, render.M{"version": "sing-box " + C.Version, "premium": true})
|
render.JSON(w, r, render.M{"version": "sing-box " + C.Version, "premium": true, "meta": true})
|
||||||
}
|
}
|
||||||
|
|||||||
164
experimental/clashapi/server_resources.go
Normal file
164
experimental/clashapi/server_resources.go
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
package clashapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/adapter"
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
"github.com/sagernet/sing/service/filemanager"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Server) checkAndDownloadExternalUI() {
|
||||||
|
if s.externalUI == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(s.externalUI)
|
||||||
|
if err != nil {
|
||||||
|
os.MkdirAll(s.externalUI, 0o755)
|
||||||
|
}
|
||||||
|
if len(entries) == 0 {
|
||||||
|
err = s.downloadExternalUI()
|
||||||
|
if err != nil {
|
||||||
|
s.logger.Error("download external ui error: ", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) downloadExternalUI() error {
|
||||||
|
var downloadURL string
|
||||||
|
if s.externalUIDownloadURL != "" {
|
||||||
|
downloadURL = s.externalUIDownloadURL
|
||||||
|
} else {
|
||||||
|
downloadURL = "https://github.com/MetaCubeX/Yacd-meta/archive/gh-pages.zip"
|
||||||
|
}
|
||||||
|
s.logger.Info("downloading external ui")
|
||||||
|
var detour adapter.Outbound
|
||||||
|
if s.externalUIDownloadDetour != "" {
|
||||||
|
outbound, loaded := s.router.Outbound(s.externalUIDownloadDetour)
|
||||||
|
if !loaded {
|
||||||
|
return E.New("detour outbound not found: ", s.externalUIDownloadDetour)
|
||||||
|
}
|
||||||
|
detour = outbound
|
||||||
|
} else {
|
||||||
|
detour = s.router.DefaultOutbound(N.NetworkTCP)
|
||||||
|
}
|
||||||
|
httpClient := &http.Client{
|
||||||
|
Transport: &http.Transport{
|
||||||
|
ForceAttemptHTTP2: true,
|
||||||
|
TLSHandshakeTimeout: 5 * time.Second,
|
||||||
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
|
return detour.DialContext(ctx, network, M.ParseSocksaddr(addr))
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
defer httpClient.CloseIdleConnections()
|
||||||
|
response, err := httpClient.Get(downloadURL)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return E.New("download external ui failed: ", response.Status)
|
||||||
|
}
|
||||||
|
err = s.downloadZIP(filepath.Base(downloadURL), response.Body, s.externalUI)
|
||||||
|
if err != nil {
|
||||||
|
removeAllInDirectory(s.externalUI)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) downloadZIP(name string, body io.Reader, output string) error {
|
||||||
|
tempFile, err := filemanager.CreateTemp(s.ctx, name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer os.Remove(tempFile.Name())
|
||||||
|
_, err = io.Copy(tempFile, body)
|
||||||
|
tempFile.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
reader, err := zip.OpenReader(tempFile.Name())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer reader.Close()
|
||||||
|
trimDir := zipIsInSingleDirectory(reader.File)
|
||||||
|
for _, file := range reader.File {
|
||||||
|
if file.FileInfo().IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pathElements := strings.Split(file.Name, "/")
|
||||||
|
if trimDir {
|
||||||
|
pathElements = pathElements[1:]
|
||||||
|
}
|
||||||
|
saveDirectory := output
|
||||||
|
if len(pathElements) > 1 {
|
||||||
|
saveDirectory = filepath.Join(saveDirectory, filepath.Join(pathElements[:len(pathElements)-1]...))
|
||||||
|
}
|
||||||
|
err = os.MkdirAll(saveDirectory, 0o755)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
savePath := filepath.Join(saveDirectory, pathElements[len(pathElements)-1])
|
||||||
|
err = downloadZIPEntry(s.ctx, file, savePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadZIPEntry(ctx context.Context, zipFile *zip.File, savePath string) error {
|
||||||
|
saveFile, err := filemanager.Create(ctx, savePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer saveFile.Close()
|
||||||
|
reader, err := zipFile.Open()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer reader.Close()
|
||||||
|
return common.Error(io.Copy(saveFile, reader))
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeAllInDirectory(directory string) {
|
||||||
|
dirEntries, err := os.ReadDir(directory)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, dirEntry := range dirEntries {
|
||||||
|
os.RemoveAll(filepath.Join(directory, dirEntry.Name()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func zipIsInSingleDirectory(files []*zip.File) bool {
|
||||||
|
var singleDirectory string
|
||||||
|
for _, file := range files {
|
||||||
|
if file.FileInfo().IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pathElements := strings.Split(file.Name, "/")
|
||||||
|
if len(pathElements) == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if singleDirectory == "" {
|
||||||
|
singleDirectory = pathElements[0]
|
||||||
|
} else if singleDirectory != pathElements[0] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -1,35 +1,33 @@
|
|||||||
package trafficontrol
|
package trafficontrol
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/experimental/clashapi/compatible"
|
"github.com/sagernet/sing-box/experimental/clashapi/compatible"
|
||||||
|
"github.com/sagernet/sing/common/atomic"
|
||||||
"go.uber.org/atomic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Manager struct {
|
type Manager struct {
|
||||||
connections compatible.Map[string, tracker]
|
uploadTemp atomic.Int64
|
||||||
uploadTemp *atomic.Int64
|
downloadTemp atomic.Int64
|
||||||
downloadTemp *atomic.Int64
|
uploadBlip atomic.Int64
|
||||||
uploadBlip *atomic.Int64
|
downloadBlip atomic.Int64
|
||||||
downloadBlip *atomic.Int64
|
uploadTotal atomic.Int64
|
||||||
uploadTotal *atomic.Int64
|
downloadTotal atomic.Int64
|
||||||
downloadTotal *atomic.Int64
|
|
||||||
ticker *time.Ticker
|
connections compatible.Map[string, tracker]
|
||||||
done chan struct{}
|
ticker *time.Ticker
|
||||||
|
done chan struct{}
|
||||||
|
// process *process.Process
|
||||||
|
memory uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewManager() *Manager {
|
func NewManager() *Manager {
|
||||||
manager := &Manager{
|
manager := &Manager{
|
||||||
uploadTemp: atomic.NewInt64(0),
|
ticker: time.NewTicker(time.Second),
|
||||||
downloadTemp: atomic.NewInt64(0),
|
done: make(chan struct{}),
|
||||||
uploadBlip: atomic.NewInt64(0),
|
// process: &process.Process{Pid: int32(os.Getpid())},
|
||||||
downloadBlip: atomic.NewInt64(0),
|
|
||||||
uploadTotal: atomic.NewInt64(0),
|
|
||||||
downloadTotal: atomic.NewInt64(0),
|
|
||||||
ticker: time.NewTicker(time.Second),
|
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
}
|
||||||
go manager.handle()
|
go manager.handle()
|
||||||
return manager
|
return manager
|
||||||
@@ -64,10 +62,18 @@ func (m *Manager) Snapshot() *Snapshot {
|
|||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
|
|
||||||
|
//if memoryInfo, err := m.process.MemoryInfo(); err == nil {
|
||||||
|
// m.memory = memoryInfo.RSS
|
||||||
|
//} else {
|
||||||
|
var memStats runtime.MemStats
|
||||||
|
runtime.ReadMemStats(&memStats)
|
||||||
|
m.memory = memStats.StackInuse + memStats.HeapInuse + memStats.HeapIdle - memStats.HeapReleased
|
||||||
|
|
||||||
return &Snapshot{
|
return &Snapshot{
|
||||||
UploadTotal: m.uploadTotal.Load(),
|
UploadTotal: m.uploadTotal.Load(),
|
||||||
DownloadTotal: m.downloadTotal.Load(),
|
DownloadTotal: m.downloadTotal.Load(),
|
||||||
Connections: connections,
|
Connections: connections,
|
||||||
|
Memory: m.memory,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,4 +112,5 @@ type Snapshot struct {
|
|||||||
DownloadTotal int64 `json:"downloadTotal"`
|
DownloadTotal int64 `json:"downloadTotal"`
|
||||||
UploadTotal int64 `json:"uploadTotal"`
|
UploadTotal int64 `json:"uploadTotal"`
|
||||||
Connections []tracker `json:"connections"`
|
Connections []tracker `json:"connections"`
|
||||||
|
Memory uint64 `json:"memory"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package trafficontrol
|
package trafficontrol
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"time"
|
"time"
|
||||||
@@ -8,10 +9,10 @@ import (
|
|||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
"github.com/sagernet/sing-box/experimental/trackerconn"
|
"github.com/sagernet/sing-box/experimental/trackerconn"
|
||||||
"github.com/sagernet/sing/common"
|
"github.com/sagernet/sing/common"
|
||||||
|
"github.com/sagernet/sing/common/atomic"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
|
||||||
"github.com/gofrs/uuid"
|
"github.com/gofrs/uuid/v5"
|
||||||
"go.uber.org/atomic"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Metadata struct {
|
type Metadata struct {
|
||||||
@@ -43,6 +44,19 @@ type trackerInfo struct {
|
|||||||
RulePayload string `json:"rulePayload"`
|
RulePayload string `json:"rulePayload"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (t trackerInfo) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"id": t.UUID.String(),
|
||||||
|
"metadata": t.Metadata,
|
||||||
|
"upload": t.UploadTotal.Load(),
|
||||||
|
"download": t.DownloadTotal.Load(),
|
||||||
|
"start": t.Start,
|
||||||
|
"chains": t.Chain,
|
||||||
|
"rule": t.Rule,
|
||||||
|
"rulePayload": t.RulePayload,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
type tcpTracker struct {
|
type tcpTracker struct {
|
||||||
N.ExtendedConn `json:"-"`
|
N.ExtendedConn `json:"-"`
|
||||||
*trackerInfo
|
*trackerInfo
|
||||||
@@ -97,8 +111,8 @@ func NewTCPTracker(conn net.Conn, manager *Manager, metadata Metadata, router ad
|
|||||||
next = group.Now()
|
next = group.Now()
|
||||||
}
|
}
|
||||||
|
|
||||||
upload := atomic.NewInt64(0)
|
upload := new(atomic.Int64)
|
||||||
download := atomic.NewInt64(0)
|
download := new(atomic.Int64)
|
||||||
|
|
||||||
t := &tcpTracker{
|
t := &tcpTracker{
|
||||||
ExtendedConn: trackerconn.NewHook(conn, func(n int64) {
|
ExtendedConn: trackerconn.NewHook(conn, func(n int64) {
|
||||||
@@ -184,8 +198,8 @@ func NewUDPTracker(conn N.PacketConn, manager *Manager, metadata Metadata, route
|
|||||||
next = group.Now()
|
next = group.Now()
|
||||||
}
|
}
|
||||||
|
|
||||||
upload := atomic.NewInt64(0)
|
upload := new(atomic.Int64)
|
||||||
download := atomic.NewInt64(0)
|
download := new(atomic.Int64)
|
||||||
|
|
||||||
ut := &udpTracker{
|
ut := &udpTracker{
|
||||||
PacketConn: trackerconn.NewHookPacket(conn, func(n int64) {
|
PacketConn: trackerconn.NewHookPacket(conn, func(n int64) {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user