Compare commits

...

47 Commits

Author SHA1 Message Date
RPRX
ab5d7cf3d2 v25.3.31
Announcement of NFTs by Project X: https://github.com/XTLS/Xray-core/discussions/3633
Project X NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/1

XHTTP: Beyond REALITY: https://github.com/XTLS/Xray-core/discussions/4113
REALITY NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/2
2025-03-31 12:33:38 +00:00
xqzr
2abeda9c42 Sockopt: Allow listen v6only work for Windows & Darwin (#4571)
Completes https://github.com/XTLS/Xray-core/pull/1677

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2025-03-31 12:22:16 +00:00
92613hjh
63eb0539b3 Sockopt: Fix Darwin (macOS, iOS...) UDP interface bind (#4530)
Fixes https://github.com/XTLS/Xray-core/issues/4007
2025-03-31 11:19:06 +00:00
RPRX
8284a0ef8f Dialer: Do not use ListenSystemPacket() when dialing UDP
https://github.com/XTLS/Xray-core/pull/4530#issuecomment-2765744961
2025-03-31 10:09:33 +00:00
Ilya Gulya
17207fc5e4 WireGuard: Improve config error handling; Prevent panic in case of errors during server initialization (#4566)
https://github.com/XTLS/Xray-core/pull/4566#issuecomment-2764779273
2025-03-30 22:55:21 +00:00
xqzr
52a2c63682 Sockopt: Fix Windows Multicast interface bind (#4568)
https://github.com/XTLS/Xray-core/pull/4568#issuecomment-2763492336
2025-03-30 20:51:36 +00:00
patterniha
1685c61e44 DNS: Use cache for NXDOMAIN (rcode 3 error) (#4560)
https://github.com/XTLS/Xray-core/pull/4558#issuecomment-2759007356
2025-03-29 14:29:48 +00:00
Pk-web6936
681e943848 Chore: Optimize .gitignore (#4564) 2025-03-29 13:46:26 +00:00
dependabot[bot]
8530bdb0de Bump golang.org/x/net from 0.37.0 to 0.38.0 (#4561)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.37.0 to 0.38.0.
- [Commits](https://github.com/golang/net/compare/v0.37.0...v0.38.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-29 13:42:20 +00:00
风扇滑翔翼
29e37e8a82 HTTP inbound: Directly forward plain HTTP 1xx response header (#4547)
Fixes https://github.com/XTLS/Xray-core/issues/4545
2025-03-26 12:30:48 +00:00
dependabot[bot]
e129b1e90d Bump google.golang.org/protobuf from 1.36.5 to 1.36.6 (#4549)
Bumps google.golang.org/protobuf from 1.36.5 to 1.36.6.

---
updated-dependencies:
- dependency-name: google.golang.org/protobuf
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-26 12:20:17 +00:00
patterniha
5922caff89 DNS: Add expectedIPs as an alias of expectIPs (#4551)
https://github.com/XTLS/Xray-core/discussions/1903#discussioncomment-5543921
2025-03-26 12:18:58 +00:00
Meo597
4afe2d0cff DNS: Support returning upstream TTL to clients (#4526)
Closes https://github.com/XTLS/Xray-core/issues/4527
2025-03-24 13:33:56 +00:00
patterniha
2d3210e4b8 Env: Add XRAY_LOCATION_CERT variable (#4536)
https://github.com/XTLS/Xray-core/issues/4531#issuecomment-2746155941

Fixes https://github.com/XTLS/Xray-core/issues/4531

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2025-03-24 13:02:35 +00:00
dependabot[bot]
673a9ae063 Bump github.com/quic-go/quic-go from 0.50.0 to 0.50.1 (#4539)
Bumps [github.com/quic-go/quic-go](https://github.com/quic-go/quic-go) from 0.50.0 to 0.50.1.
- [Release notes](https://github.com/quic-go/quic-go/releases)
- [Changelog](https://github.com/quic-go/quic-go/blob/master/Changelog.md)
- [Commits](https://github.com/quic-go/quic-go/compare/v0.50.0...v0.50.1)

---
updated-dependencies:
- dependency-name: github.com/quic-go/quic-go
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-24 09:49:58 +00:00
RPRX
607c2a6d31 DNS DoH: Use EDNS0 with 100-300 padding by default (body padding)
https://github.com/XTLS/Xray-core/pull/4516#issuecomment-2744093003
2025-03-21 20:13:09 +00:00
风扇滑翔翼
b585b26f29 Sockopt: Fix Windows UDP interface bind; Allow customSockopt work for UDP (#4504) 2025-03-21 10:48:46 +00:00
patterniha
1067171e6a DNS: Add timeoutMs for DnsServerObject (#4523) 2025-03-21 10:24:58 +00:00
风扇滑翔翼
86a225cda1 DNS: Retry with EDNS0 when response is truncated (#4516) 2025-03-21 08:58:51 +00:00
风扇滑翔翼
6f8e253dec DNS: Add tag for DnsServerObject (#4515)
Closes https://github.com/XTLS/Xray-core/issues/4505
2025-03-21 08:58:24 +00:00
patterniha
6a211a0bb9 DNS: Add allowUnexpectedIPs for DnsServerObject (#4497)
Closes https://github.com/XTLS/Xray-core/issues/4424
2025-03-20 12:09:02 +00:00
风扇滑翔翼
335845a9b2 DNS: Ensure order for DNS server match (#4510)
Fixes https://github.com/XTLS/Xray-core/issues/4508
2025-03-20 11:21:21 +00:00
风扇滑翔翼
b70d0abebe API: Fix data race in online ipList (#4513)
Fixes https://github.com/XTLS/Xray-core/issues/4512
2025-03-20 11:12:36 +00:00
dependabot[bot]
3d21128159 Bump github.com/miekg/dns from 1.1.63 to 1.1.64 (#4506)
Bumps [github.com/miekg/dns](https://github.com/miekg/dns) from 1.1.63 to 1.1.64.
- [Changelog](https://github.com/miekg/dns/blob/master/Makefile.release)
- [Commits](https://github.com/miekg/dns/compare/v1.1.63...v1.1.64)

---
updated-dependencies:
- dependency-name: github.com/miekg/dns
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-20 11:06:51 +00:00
Nikita Korotaev
eca99771ca README.md: Add Remnawave to Web Panels (#4498) 2025-03-20 10:50:43 +00:00
RPRX
2cba2c4d59 v25.3.6
Announcement of NFTs by Project X: https://github.com/XTLS/Xray-core/discussions/3633
Project X NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/1

XHTTP: Beyond REALITY: https://github.com/XTLS/Xray-core/discussions/4113
REALITY NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/2
2025-03-06 13:50:15 +00:00
Happ-dev
306fa51475 README.md: Add Happ to iOS clients (#4465) 2025-03-06 12:27:25 +00:00
dependabot[bot]
6d6f1c6967 Bump golang.org/x/net from 0.36.0 to 0.37.0 (#4469)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.36.0 to 0.37.0.
- [Commits](https://github.com/golang/net/compare/v0.36.0...v0.37.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-06 10:59:49 +00:00
dependabot[bot]
152959824f Bump google.golang.org/grpc from 1.70.0 to 1.71.0 (#4463)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.70.0 to 1.71.0.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.70.0...v1.71.0)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-05 09:23:38 +00:00
dependabot[bot]
a977b6357e Bump golang.org/x/net from 0.35.0 to 0.36.0 (#4462)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.35.0 to 0.36.0.
- [Commits](https://github.com/golang/net/compare/v0.35.0...v0.36.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-03-05 09:23:31 +00:00
RPRX
16eee1b89c Mux server: Clone the session.Content attached on ctx as well
https://github.com/XTLS/Xray-core/pull/3908#issuecomment-2696911994

Fixes https://github.com/XTLS/Xray-core/pull/3904 for good
2025-03-04 11:01:03 +00:00
RPRX
dde0a4f272 REALITY config: Add password as an alias of publicKey
https://github.com/XTLS/Xray-core/issues/4458#issuecomment-2696181682
2025-03-04 05:29:03 +00:00
RPRX
e15dff94b5 v25.3.3
Announcement of NFTs by Project X: https://github.com/XTLS/Xray-core/discussions/3633
Project X NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/1

XHTTP: Beyond REALITY: https://github.com/XTLS/Xray-core/discussions/4113
REALITY NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/2
2025-03-03 15:30:22 +00:00
RPRX
e466b0497c DNS DoH: Use Chrome's fingerprint & keepAlivePeriod, Add header padding by default
https://github.com/XTLS/Xray-core/discussions/4430#discussioncomment-12374292
2025-03-03 14:45:12 +00:00
j3l11234
b9cb93d3c2 Sockopt: Add addressPortStrategy (query SRV or TXT) (#4416)
Co-authored-by: 风扇滑翔翼 <Fangliding.fshxy@outlook.com>
2025-03-02 13:07:55 +00:00
RPRX
8d46f7e14c TLS fingerprints: Refine "random" & "randomized", Add "randomizednoalpn"
https://github.com/XTLS/Xray-core/issues/4436#issuecomment-2687801214
2025-03-02 13:02:47 +00:00
A1lo
4b616f5cd0 XHTTP server: Switch to Go 1.24 native h2c support (#4451) 2025-03-02 13:02:40 +00:00
dependabot[bot]
06b4a7ce4d Bump lukechampine.com/blake3 from 1.3.0 to 1.4.0 (#4439)
Bumps [lukechampine.com/blake3](https://github.com/lukechampine/blake3) from 1.3.0 to 1.4.0.
- [Commits](https://github.com/lukechampine/blake3/compare/v1.3.0...v1.4.0)

---
updated-dependencies:
- dependency-name: lukechampine.com/blake3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-25 13:26:54 +00:00
dependabot[bot]
4c12e1686b Bump golang.org/x/crypto from 0.33.0 to 0.35.0 (#4438)
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.33.0 to 0.35.0.
- [Commits](https://github.com/golang/crypto/compare/v0.33.0...v0.35.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-25 13:26:32 +00:00
dependabot[bot]
225d151cd3 Bump github.com/google/go-cmp from 0.6.0 to 0.7.0 (#4433)
Bumps [github.com/google/go-cmp](https://github.com/google/go-cmp) from 0.6.0 to 0.7.0.
- [Release notes](https://github.com/google/go-cmp/releases)
- [Commits](https://github.com/google/go-cmp/compare/v0.6.0...v0.7.0)

---
updated-dependencies:
- dependency-name: github.com/google/go-cmp
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-25 13:26:00 +00:00
风扇滑翔翼
d451078e72 Chore: Fix tests (#4440) 2025-02-25 13:11:37 +00:00
RPRX
ce2384cccc Use Go 1.24 2025-02-25 11:35:25 +00:00
RPRX
be43f66b63 v25.2.21
Announcement of NFTs by Project X: https://github.com/XTLS/Xray-core/discussions/3633
Project X NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/1

XHTTP: Beyond REALITY: https://github.com/XTLS/Xray-core/discussions/4113
REALITY NFT: https://opensea.io/assets/ethereum/0x5ee362866001613093361eb8569d59c4141b76d1/2
2025-02-21 07:58:31 +00:00
dependabot[bot]
71a6d89c23 Bump github.com/quic-go/quic-go from 0.49.0 to 0.50.0 (#4420)
Bumps [github.com/quic-go/quic-go](https://github.com/quic-go/quic-go) from 0.49.0 to 0.50.0.
- [Release notes](https://github.com/quic-go/quic-go/releases)
- [Changelog](https://github.com/quic-go/quic-go/blob/master/Changelog.md)
- [Commits](https://github.com/quic-go/quic-go/compare/v0.49.0...v0.50.0)

---
updated-dependencies:
- dependency-name: github.com/quic-go/quic-go
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-21 06:34:33 +00:00
lastrise
89792aee9d Outbound: Add outbound sendThrough origin behavior (#4349)
* added support of sending through origin for outbounds

* added strings package import

* usage of net.SplitHostPort instead of manual splitting

---------

Co-authored-by: poly <poly@>
2025-02-20 15:15:59 -05:00
RPRX
b786a50aee XHTTP server: Fix stream-up "single POST problem", Use united httpServerConn instead of recover()
https://github.com/XTLS/Xray-core/issues/4373#issuecomment-2671795675

https://github.com/XTLS/Xray-core/issues/4406#issuecomment-2668041926
2025-02-20 16:28:06 +00:00
风扇滑翔翼
b38a53e629 UDS: Use UnixListenerWrapper & UnixConnWrapper (#4413)
Fixes https://github.com/XTLS/Xray-core/issues/4411

---------

Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com>
2025-02-19 11:31:29 +00:00
74 changed files with 1385 additions and 929 deletions

17
.gitignore vendored
View File

@@ -14,10 +14,18 @@
# Dependency directories (remove the comment below to include it) # Dependency directories (remove the comment below to include it)
# vendor/ # vendor/
# macOS specific files
*.DS_Store *.DS_Store
.idea
# IDE specific files
.idea/
.vscode/
# Archive files
*.zip *.zip
*.tar.gz *.tar.gz
# Binaries
xray xray
xray_softfloat xray_softfloat
mockgen mockgen
@@ -26,8 +34,13 @@ vprotogen
errorgen errorgen
!common/errors/errorgen/ !common/errors/errorgen/
*.dat *.dat
.vscode
# Build assets
/build_assets /build_assets
# Output from dlv test # Output from dlv test
**/debug.* **/debug.*
# Certificates
*.crt
*.key

View File

@@ -38,6 +38,7 @@
- [teddysun/xray](https://hub.docker.com/r/teddysun/xray) - [teddysun/xray](https://hub.docker.com/r/teddysun/xray)
- [wulabing/xray_docker](https://github.com/wulabing/xray_docker) - [wulabing/xray_docker](https://github.com/wulabing/xray_docker)
- Web Panel - **WARNING: Please DO NOT USE plain HTTP panels like 3X-UI**, as they are believed to be bribed by Iran GFW for supporting plain HTTP by default and refused to change (https://github.com/XTLS/Xray-core/pull/3884#issuecomment-2439595331), which has already put many users' data security in danger in the past few years. **If you are already using 3X-UI, please switch to the following panels, which are verified to support HTTPS and SSH port forwarding only:** - Web Panel - **WARNING: Please DO NOT USE plain HTTP panels like 3X-UI**, as they are believed to be bribed by Iran GFW for supporting plain HTTP by default and refused to change (https://github.com/XTLS/Xray-core/pull/3884#issuecomment-2439595331), which has already put many users' data security in danger in the past few years. **If you are already using 3X-UI, please switch to the following panels, which are verified to support HTTPS and SSH port forwarding only:**
- [Remnawave](https://github.com/remnawave/panel)
- [Marzban](https://github.com/Gozargah/Marzban) - [Marzban](https://github.com/Gozargah/Marzban)
- [Xray-UI](https://github.com/qist/xray-ui) - [Xray-UI](https://github.com/qist/xray-ui)
- [Hiddify](https://github.com/hiddify/Hiddify-Manager) - [Hiddify](https://github.com/hiddify/Hiddify-Manager)
@@ -85,6 +86,7 @@
- [X-flutter](https://github.com/XTLS/X-flutter) - [X-flutter](https://github.com/XTLS/X-flutter)
- [SaeedDev94/Xray](https://github.com/SaeedDev94/Xray) - [SaeedDev94/Xray](https://github.com/SaeedDev94/Xray)
- iOS & macOS arm64 - iOS & macOS arm64
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215)
- [FoXray](https://apps.apple.com/app/foxray/id6448898396) - [FoXray](https://apps.apple.com/app/foxray/id6448898396)
- [Streisand](https://apps.apple.com/app/streisand/id6450534064) - [Streisand](https://apps.apple.com/app/streisand/id6450534064)
- macOS arm64 & x64 - macOS arm64 & x64

View File

@@ -128,13 +128,16 @@ type NameServer struct {
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
Address *net.Endpoint `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` Address *net.Endpoint `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"`
ClientIp []byte `protobuf:"bytes,5,opt,name=client_ip,json=clientIp,proto3" json:"client_ip,omitempty"` ClientIp []byte `protobuf:"bytes,5,opt,name=client_ip,json=clientIp,proto3" json:"client_ip,omitempty"`
SkipFallback bool `protobuf:"varint,6,opt,name=skipFallback,proto3" json:"skipFallback,omitempty"` SkipFallback bool `protobuf:"varint,6,opt,name=skipFallback,proto3" json:"skipFallback,omitempty"`
PrioritizedDomain []*NameServer_PriorityDomain `protobuf:"bytes,2,rep,name=prioritized_domain,json=prioritizedDomain,proto3" json:"prioritized_domain,omitempty"` PrioritizedDomain []*NameServer_PriorityDomain `protobuf:"bytes,2,rep,name=prioritized_domain,json=prioritizedDomain,proto3" json:"prioritized_domain,omitempty"`
Geoip []*router.GeoIP `protobuf:"bytes,3,rep,name=geoip,proto3" json:"geoip,omitempty"` Geoip []*router.GeoIP `protobuf:"bytes,3,rep,name=geoip,proto3" json:"geoip,omitempty"`
OriginalRules []*NameServer_OriginalRule `protobuf:"bytes,4,rep,name=original_rules,json=originalRules,proto3" json:"original_rules,omitempty"` OriginalRules []*NameServer_OriginalRule `protobuf:"bytes,4,rep,name=original_rules,json=originalRules,proto3" json:"original_rules,omitempty"`
QueryStrategy QueryStrategy `protobuf:"varint,7,opt,name=query_strategy,json=queryStrategy,proto3,enum=xray.app.dns.QueryStrategy" json:"query_strategy,omitempty"` QueryStrategy QueryStrategy `protobuf:"varint,7,opt,name=query_strategy,json=queryStrategy,proto3,enum=xray.app.dns.QueryStrategy" json:"query_strategy,omitempty"`
AllowUnexpectedIPs bool `protobuf:"varint,8,opt,name=allowUnexpectedIPs,proto3" json:"allowUnexpectedIPs,omitempty"`
Tag string `protobuf:"bytes,9,opt,name=tag,proto3" json:"tag,omitempty"`
TimeoutMs uint64 `protobuf:"varint,10,opt,name=timeoutMs,proto3" json:"timeoutMs,omitempty"`
} }
func (x *NameServer) Reset() { func (x *NameServer) Reset() {
@@ -216,6 +219,27 @@ func (x *NameServer) GetQueryStrategy() QueryStrategy {
return QueryStrategy_USE_IP return QueryStrategy_USE_IP
} }
func (x *NameServer) GetAllowUnexpectedIPs() bool {
if x != nil {
return x.AllowUnexpectedIPs
}
return false
}
func (x *NameServer) GetTag() string {
if x != nil {
return x.Tag
}
return ""
}
func (x *NameServer) GetTimeoutMs() uint64 {
if x != nil {
return x.TimeoutMs
}
return 0
}
type Config struct { type Config struct {
state protoimpl.MessageState state protoimpl.MessageState
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
@@ -508,7 +532,7 @@ var file_app_dns_config_proto_rawDesc = []byte{
0x2e, 0x64, 0x6e, 0x73, 0x1a, 0x1c, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74, 0x2e, 0x64, 0x6e, 0x73, 0x1a, 0x1c, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x6e, 0x65, 0x74,
0x2f, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x2f, 0x64, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x1a, 0x17, 0x61, 0x70, 0x70, 0x2f, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2f, 0x63, 0x74, 0x6f, 0x1a, 0x17, 0x61, 0x70, 0x70, 0x2f, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x72, 0x2f, 0x63,
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xb2, 0x04, 0x0a, 0x0a, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x92, 0x05, 0x0a, 0x0a,
0x4e, 0x61, 0x6d, 0x65, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x12, 0x33, 0x0a, 0x07, 0x61, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x12, 0x33, 0x0a, 0x07, 0x61, 0x64,
0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x78, 0x72, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x78, 0x72,
0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x45, 0x6e, 0x61, 0x79, 0x2e, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x2e, 0x45, 0x6e,
@@ -534,7 +558,13 @@ var file_app_dns_config_proto_rawDesc = []byte{
0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1b, 0x2e, 0x78, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1b, 0x2e, 0x78,
0x72, 0x61, 0x79, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x64, 0x6e, 0x73, 0x2e, 0x51, 0x75, 0x65, 0x72, 0x72, 0x61, 0x79, 0x2e, 0x61, 0x70, 0x70, 0x2e, 0x64, 0x6e, 0x73, 0x2e, 0x51, 0x75, 0x65, 0x72,
0x79, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x52, 0x0d, 0x71, 0x75, 0x65, 0x72, 0x79, 0x79, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x52, 0x0d, 0x71, 0x75, 0x65, 0x72, 0x79,
0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x1a, 0x5e, 0x0a, 0x0e, 0x50, 0x72, 0x69, 0x6f, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x12, 0x2e, 0x0a, 0x12, 0x61, 0x6c, 0x6c, 0x6f,
0x77, 0x55, 0x6e, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x49, 0x50, 0x73, 0x18, 0x08,
0x20, 0x01, 0x28, 0x08, 0x52, 0x12, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x55, 0x6e, 0x65, 0x78, 0x70,
0x65, 0x63, 0x74, 0x65, 0x64, 0x49, 0x50, 0x73, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x61, 0x67, 0x18,
0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x74, 0x61, 0x67, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69,
0x6d, 0x65, 0x6f, 0x75, 0x74, 0x4d, 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x04, 0x52, 0x09, 0x74,
0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x4d, 0x73, 0x1a, 0x5e, 0x0a, 0x0e, 0x50, 0x72, 0x69, 0x6f,
0x72, 0x69, 0x74, 0x79, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x12, 0x34, 0x0a, 0x04, 0x74, 0x79, 0x72, 0x69, 0x74, 0x79, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x12, 0x34, 0x0a, 0x04, 0x74, 0x79,
0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x20, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x20, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e,
0x61, 0x70, 0x70, 0x2e, 0x64, 0x6e, 0x73, 0x2e, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x4d, 0x61, 0x61, 0x70, 0x70, 0x2e, 0x64, 0x6e, 0x73, 0x2e, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x4d, 0x61,

View File

@@ -28,6 +28,9 @@ message NameServer {
repeated xray.app.router.GeoIP geoip = 3; repeated xray.app.router.GeoIP geoip = 3;
repeated OriginalRule original_rules = 4; repeated OriginalRule original_rules = 4;
QueryStrategy query_strategy = 7; QueryStrategy query_strategy = 7;
bool allowUnexpectedIPs = 8;
string tag = 9;
uint64 timeoutMs = 10;
} }
enum DomainMatchingType { enum DomainMatchingType {

View File

@@ -4,6 +4,7 @@ package dns
import ( import (
"context" "context"
"fmt" "fmt"
"sort"
"strings" "strings"
"sync" "sync"
@@ -156,16 +157,16 @@ func (s *DNS) IsOwnLink(ctx context.Context) bool {
} }
// LookupIP implements dns.Client. // LookupIP implements dns.Client.
func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) { func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, uint32, error) {
if domain == "" { if domain == "" {
return nil, errors.New("empty domain name") return nil, 0, errors.New("empty domain name")
} }
option.IPv4Enable = option.IPv4Enable && s.ipOption.IPv4Enable option.IPv4Enable = option.IPv4Enable && s.ipOption.IPv4Enable
option.IPv6Enable = option.IPv6Enable && s.ipOption.IPv6Enable option.IPv6Enable = option.IPv6Enable && s.ipOption.IPv6Enable
if !option.IPv4Enable && !option.IPv6Enable { if !option.IPv4Enable && !option.IPv6Enable {
return nil, dns.ErrEmptyResponse return nil, 0, dns.ErrEmptyResponse
} }
// Normalize the FQDN form query // Normalize the FQDN form query
@@ -176,13 +177,14 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) {
case addrs == nil: // Domain not recorded in static host case addrs == nil: // Domain not recorded in static host
break break
case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled) case len(addrs) == 0: // Domain recorded, but no valid IP returned (e.g. IPv4 address with only IPv6 enabled)
return nil, dns.ErrEmptyResponse return nil, 0, dns.ErrEmptyResponse
case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement case len(addrs) == 1 && addrs[0].Family().IsDomain(): // Domain replacement
errors.LogInfo(s.ctx, "domain replaced: ", domain, " -> ", addrs[0].Domain()) errors.LogInfo(s.ctx, "domain replaced: ", domain, " -> ", addrs[0].Domain())
domain = addrs[0].Domain() domain = addrs[0].Domain()
default: // Successfully found ip records in static host default: // Successfully found ip records in static host
errors.LogInfo(s.ctx, "returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs) errors.LogInfo(s.ctx, "returning ", len(addrs), " IP(s) for domain ", domain, " -> ", addrs)
return toNetIP(addrs) ips, err := toNetIP(addrs)
return ips, 10, err // Hosts ttl is 10
} }
// Name servers lookup // Name servers lookup
@@ -193,9 +195,9 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) {
errors.LogDebug(s.ctx, "skip DNS resolution for domain ", domain, " at server ", client.Name()) errors.LogDebug(s.ctx, "skip DNS resolution for domain ", domain, " at server ", client.Name())
continue continue
} }
ips, err := client.QueryIP(ctx, domain, option, s.disableCache) ips, ttl, err := client.QueryIP(ctx, domain, option, s.disableCache)
if len(ips) > 0 { if len(ips) > 0 {
return ips, nil return ips, ttl, nil
} }
if err != nil { if err != nil {
errors.LogInfoInner(s.ctx, err, "failed to lookup ip for domain ", domain, " at server ", client.Name()) errors.LogInfoInner(s.ctx, err, "failed to lookup ip for domain ", domain, " at server ", client.Name())
@@ -203,11 +205,11 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, error) {
} }
// 5 for RcodeRefused in miekg/dns, hardcode to reduce binary size // 5 for RcodeRefused in miekg/dns, hardcode to reduce binary size
if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch && err != dns.ErrEmptyResponse && dns.RCodeFromError(err) != 5 { if err != context.Canceled && err != context.DeadlineExceeded && err != errExpectedIPNonMatch && err != dns.ErrEmptyResponse && dns.RCodeFromError(err) != 5 {
return nil, err return nil, 0, err
} }
} }
return nil, errors.New("returning nil for domain ", domain).Base(errors.Combine(errs...)) return nil, 0, errors.New("returning nil for domain ", domain).Base(errors.Combine(errs...))
} }
// LookupHosts implements dns.HostsLookup. // LookupHosts implements dns.HostsLookup.
@@ -250,7 +252,11 @@ func (s *DNS) sortClients(domain string) []*Client {
// Priority domain matching // Priority domain matching
hasMatch := false hasMatch := false
for _, match := range s.domainMatcher.Match(domain) { MatchSlice := s.domainMatcher.Match(domain)
sort.Slice(MatchSlice, func(i, j int) bool {
return MatchSlice[i] < MatchSlice[j]
})
for _, match := range MatchSlice {
info := s.matcherInfos[match] info := s.matcherInfos[match]
client := s.clients[info.clientIdx] client := s.clients[info.clientIdx]
domainRule := client.domains[info.domainRuleIdx] domainRule := client.domains[info.domainRuleIdx]

View File

@@ -155,7 +155,7 @@ func TestUDPServerSubnet(t *testing.T) {
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client) client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
ips, err := client.LookupIP("google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -216,7 +216,7 @@ func TestUDPServer(t *testing.T) {
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client) client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
{ {
ips, err := client.LookupIP("google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -231,7 +231,7 @@ func TestUDPServer(t *testing.T) {
} }
{ {
ips, err := client.LookupIP("facebook.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("facebook.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -246,7 +246,7 @@ func TestUDPServer(t *testing.T) {
} }
{ {
_, err := client.LookupIP("notexist.google.com", feature_dns.IPOption{ _, _, err := client.LookupIP("notexist.google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -260,7 +260,7 @@ func TestUDPServer(t *testing.T) {
} }
{ {
ips, err := client.LookupIP("ipv4only.google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("ipv4only.google.com", feature_dns.IPOption{
IPv4Enable: false, IPv4Enable: false,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -276,7 +276,7 @@ func TestUDPServer(t *testing.T) {
dnsServer.Shutdown() dnsServer.Shutdown()
{ {
ips, err := client.LookupIP("google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -357,7 +357,7 @@ func TestPrioritizedDomain(t *testing.T) {
startTime := time.Now() startTime := time.Now()
{ {
ips, err := client.LookupIP("google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -423,7 +423,7 @@ func TestUDPServerIPv6(t *testing.T) {
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client) client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
{ {
ips, err := client.LookupIP("ipv6.google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("ipv6.google.com", feature_dns.IPOption{
IPv4Enable: false, IPv4Enable: false,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -492,7 +492,7 @@ func TestStaticHostDomain(t *testing.T) {
client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client) client := v.GetFeature(feature_dns.ClientType()).(feature_dns.Client)
{ {
ips, err := client.LookupIP("example.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("example.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -603,7 +603,7 @@ func TestIPMatch(t *testing.T) {
startTime := time.Now() startTime := time.Now()
{ {
ips, err := client.LookupIP("google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -726,7 +726,7 @@ func TestLocalDomain(t *testing.T) {
startTime := time.Now() startTime := time.Now()
{ // Will match dotless: { // Will match dotless:
ips, err := client.LookupIP("hostname", feature_dns.IPOption{ ips, _, err := client.LookupIP("hostname", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -741,7 +741,7 @@ func TestLocalDomain(t *testing.T) {
} }
{ // Will match domain:local { // Will match domain:local
ips, err := client.LookupIP("hostname.local", feature_dns.IPOption{ ips, _, err := client.LookupIP("hostname.local", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -756,7 +756,7 @@ func TestLocalDomain(t *testing.T) {
} }
{ // Will match static ip { // Will match static ip
ips, err := client.LookupIP("hostnamestatic", feature_dns.IPOption{ ips, _, err := client.LookupIP("hostnamestatic", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -771,7 +771,7 @@ func TestLocalDomain(t *testing.T) {
} }
{ // Will match domain replacing { // Will match domain replacing
ips, err := client.LookupIP("hostnamealias", feature_dns.IPOption{ ips, _, err := client.LookupIP("hostnamealias", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -785,8 +785,8 @@ func TestLocalDomain(t *testing.T) {
} }
} }
{ // Will match dotless:localhost, but not expectIPs: 127.0.0.2, 127.0.0.3, then matches at dotless: { // Will match dotless:localhost, but not expectedIPs: 127.0.0.2, 127.0.0.3, then matches at dotless:
ips, err := client.LookupIP("localhost", feature_dns.IPOption{ ips, _, err := client.LookupIP("localhost", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -800,8 +800,8 @@ func TestLocalDomain(t *testing.T) {
} }
} }
{ // Will match dotless:localhost, and expectIPs: 127.0.0.2, 127.0.0.3 { // Will match dotless:localhost, and expectedIPs: 127.0.0.2, 127.0.0.3
ips, err := client.LookupIP("localhost-a", feature_dns.IPOption{ ips, _, err := client.LookupIP("localhost-a", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -815,8 +815,8 @@ func TestLocalDomain(t *testing.T) {
} }
} }
{ // Will match dotless:localhost, and expectIPs: 127.0.0.2, 127.0.0.3 { // Will match dotless:localhost, and expectedIPs: 127.0.0.2, 127.0.0.3
ips, err := client.LookupIP("localhost-b", feature_dns.IPOption{ ips, _, err := client.LookupIP("localhost-b", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -831,7 +831,7 @@ func TestLocalDomain(t *testing.T) {
} }
{ // Will match dotless: { // Will match dotless:
ips, err := client.LookupIP("Mijia Cloud", feature_dns.IPOption{ ips, _, err := client.LookupIP("Mijia Cloud", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -997,7 +997,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
startTime := time.Now() startTime := time.Now()
{ // Will match server 1,2 and server 1 returns expected ip { // Will match server 1,2 and server 1 returns expected ip
ips, err := client.LookupIP("google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -1012,7 +1012,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
} }
{ // Will match server 1,2 and server 1 returns unexpected ip, then server 2 returns expected one { // Will match server 1,2 and server 1 returns unexpected ip, then server 2 returns expected one
ips, err := client.LookupIP("ipv6.google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("ipv6.google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: false, IPv6Enable: false,
FakeEnable: false, FakeEnable: false,
@@ -1027,7 +1027,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
} }
{ // Will match server 3,1,2 and server 3 returns expected one { // Will match server 3,1,2 and server 3 returns expected one
ips, err := client.LookupIP("api.google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("api.google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
@@ -1042,7 +1042,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
} }
{ // Will match server 4,3,1,2 and server 4 returns expected one { // Will match server 4,3,1,2 and server 4 returns expected one
ips, err := client.LookupIP("v2.api.google.com", feature_dns.IPOption{ ips, _, err := client.LookupIP("v2.api.google.com", feature_dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,

View File

@@ -31,20 +31,22 @@ type record struct {
// IPRecord is a cacheable item for a resolved domain // IPRecord is a cacheable item for a resolved domain
type IPRecord struct { type IPRecord struct {
ReqID uint16 ReqID uint16
IP []net.Address IP []net.Address
Expire time.Time Expire time.Time
RCode dnsmessage.RCode RCode dnsmessage.RCode
RawHeader *dnsmessage.Header
} }
func (r *IPRecord) getIPs() ([]net.Address, error) { func (r *IPRecord) getIPs() ([]net.Address, uint32, error) {
if r == nil || r.Expire.Before(time.Now()) { if r == nil || r.Expire.Before(time.Now()) {
return nil, errRecordNotFound return nil, 0, errRecordNotFound
} }
if r.RCode != dnsmessage.RCodeSuccess { if r.RCode != dnsmessage.RCodeSuccess {
return nil, dns_feature.RCodeError(r.RCode) return nil, 0, dns_feature.RCodeError(r.RCode)
} }
return r.IP, nil ttl := uint32(time.Until(r.Expire) / time.Second)
return r.IP, ttl, nil
} }
func isNewer(baseRec *IPRecord, newRec *IPRecord) bool { func isNewer(baseRec *IPRecord, newRec *IPRecord) bool {
@@ -67,49 +69,59 @@ type dnsRequest struct {
msg *dnsmessage.Message msg *dnsmessage.Message
} }
func genEDNS0Options(clientIP net.IP) *dnsmessage.Resource { func genEDNS0Options(clientIP net.IP, padding int) *dnsmessage.Resource {
if len(clientIP) == 0 { if len(clientIP) == 0 && padding == 0 {
return nil return nil
} }
var netmask int const EDNS0SUBNET = 0x8
var family uint16 const EDNS0PADDING = 0xc
if len(clientIP) == 4 {
family = 1
netmask = 24 // 24 for IPV4, 96 for IPv6
} else {
family = 2
netmask = 96
}
b := make([]byte, 4)
binary.BigEndian.PutUint16(b[0:], family)
b[2] = byte(netmask)
b[3] = 0
switch family {
case 1:
ip := clientIP.To4().Mask(net.CIDRMask(netmask, net.IPv4len*8))
needLength := (netmask + 8 - 1) / 8 // division rounding up
b = append(b, ip[:needLength]...)
case 2:
ip := clientIP.Mask(net.CIDRMask(netmask, net.IPv6len*8))
needLength := (netmask + 8 - 1) / 8 // division rounding up
b = append(b, ip[:needLength]...)
}
const EDNS0SUBNET = 0x08
opt := new(dnsmessage.Resource) opt := new(dnsmessage.Resource)
common.Must(opt.Header.SetEDNS0(1350, 0xfe00, true)) common.Must(opt.Header.SetEDNS0(1350, 0xfe00, true))
body := dnsmessage.OPTResource{}
opt.Body = &body
opt.Body = &dnsmessage.OPTResource{ if len(clientIP) != 0 {
Options: []dnsmessage.Option{ var netmask int
{ var family uint16
if len(clientIP) == 4 {
family = 1
netmask = 24 // 24 for IPV4, 96 for IPv6
} else {
family = 2
netmask = 96
}
b := make([]byte, 4)
binary.BigEndian.PutUint16(b[0:], family)
b[2] = byte(netmask)
b[3] = 0
switch family {
case 1:
ip := clientIP.To4().Mask(net.CIDRMask(netmask, net.IPv4len*8))
needLength := (netmask + 8 - 1) / 8 // division rounding up
b = append(b, ip[:needLength]...)
case 2:
ip := clientIP.Mask(net.CIDRMask(netmask, net.IPv6len*8))
needLength := (netmask + 8 - 1) / 8 // division rounding up
b = append(b, ip[:needLength]...)
}
body.Options = append(body.Options,
dnsmessage.Option{
Code: EDNS0SUBNET, Code: EDNS0SUBNET,
Data: b, Data: b,
}, })
}, }
if padding != 0 {
body.Options = append(body.Options,
dnsmessage.Option{
Code: EDNS0PADDING,
Data: make([]byte, padding),
})
} }
return opt return opt
@@ -179,9 +191,10 @@ func parseResponse(payload []byte) (*IPRecord, error) {
now := time.Now() now := time.Now()
ipRecord := &IPRecord{ ipRecord := &IPRecord{
ReqID: h.ID, ReqID: h.ID,
RCode: h.RCode, RCode: h.RCode,
Expire: now.Add(time.Second * 600), Expire: now.Add(time.Second * 600),
RawHeader: &h,
} }
L: L:

View File

@@ -51,7 +51,7 @@ func Test_parseResponse(t *testing.T) {
}{ }{
{ {
"empty", "empty",
&IPRecord{0, []net.Address(nil), time.Time{}, dnsmessage.RCodeSuccess}, &IPRecord{0, []net.Address(nil), time.Time{}, dnsmessage.RCodeSuccess, nil},
false, false,
}, },
{ {
@@ -66,12 +66,13 @@ func Test_parseResponse(t *testing.T) {
[]net.Address{net.ParseAddress("8.8.8.8"), net.ParseAddress("8.8.4.4")}, []net.Address{net.ParseAddress("8.8.8.8"), net.ParseAddress("8.8.4.4")},
time.Time{}, time.Time{},
dnsmessage.RCodeSuccess, dnsmessage.RCodeSuccess,
nil,
}, },
false, false,
}, },
{ {
"aaaa record", "aaaa record",
&IPRecord{2, []net.Address{net.ParseAddress("2001::123:8888"), net.ParseAddress("2001::123:8844")}, time.Time{}, dnsmessage.RCodeSuccess}, &IPRecord{2, []net.Address{net.ParseAddress("2001::123:8888"), net.ParseAddress("2001::123:8844")}, time.Time{}, dnsmessage.RCodeSuccess, nil},
false, false,
}, },
} }
@@ -84,8 +85,9 @@ func Test_parseResponse(t *testing.T) {
} }
if got != nil { if got != nil {
// reset the time // reset the time and RawHeader
got.Expire = time.Time{} got.Expire = time.Time{}
got.RawHeader = nil
} }
if cmp.Diff(got, tt.want) != "" { if cmp.Diff(got, tt.want) != "" {
t.Error(cmp.Diff(got, tt.want)) t.Error(cmp.Diff(got, tt.want))
@@ -154,7 +156,7 @@ func Test_genEDNS0Options(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
if got := genEDNS0Options(tt.args.clientIP); got == nil { if got := genEDNS0Options(tt.args.clientIP, 0); got == nil {
t.Errorf("genEDNS0Options() = %v, want %v", got, tt.want) t.Errorf("genEDNS0Options() = %v, want %v", got, tt.want)
} }
}) })

View File

@@ -9,6 +9,7 @@ import (
"github.com/xtls/xray-core/app/router" "github.com/xtls/xray-core/app/router"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/common/session"
"github.com/xtls/xray-core/common/strmatcher" "github.com/xtls/xray-core/common/strmatcher"
"github.com/xtls/xray-core/core" "github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/features/dns" "github.com/xtls/xray-core/features/dns"
@@ -20,19 +21,22 @@ type Server interface {
// Name of the Client. // Name of the Client.
Name() string Name() string
// QueryIP sends IP queries to its configured server. // QueryIP sends IP queries to its configured server.
QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns.IPOption, disableCache bool) ([]net.IP, error) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns.IPOption, disableCache bool) ([]net.IP, uint32, error)
} }
// Client is the interface for DNS client. // Client is the interface for DNS client.
type Client struct { type Client struct {
server Server server Server
clientIP net.IP clientIP net.IP
skipFallback bool skipFallback bool
domains []string domains []string
expectIPs []*router.GeoIPMatcher expectedIPs []*router.GeoIPMatcher
allowUnexpectedIPs bool
tag string
timeoutMs time.Duration
} }
var errExpectedIPNonMatch = errors.New("expectIPs not match") var errExpectedIPNonMatch = errors.New("expectedIPs not match")
// NewServer creates a name server object according to the network destination url. // NewServer creates a name server object according to the network destination url.
func NewServer(ctx context.Context, dest net.Destination, dispatcher routing.Dispatcher, queryStrategy QueryStrategy) (Server, error) { func NewServer(ctx context.Context, dest net.Destination, dispatcher routing.Dispatcher, queryStrategy QueryStrategy) (Server, error) {
@@ -45,11 +49,13 @@ func NewServer(ctx context.Context, dest net.Destination, dispatcher routing.Dis
case strings.EqualFold(u.String(), "localhost"): case strings.EqualFold(u.String(), "localhost"):
return NewLocalNameServer(queryStrategy), nil return NewLocalNameServer(queryStrategy), nil
case strings.EqualFold(u.Scheme, "https"): // DNS-over-HTTPS Remote mode case strings.EqualFold(u.Scheme, "https"): // DNS-over-HTTPS Remote mode
return NewDoHNameServer(u, dispatcher, queryStrategy, false) return NewDoHNameServer(u, queryStrategy, dispatcher, false), nil
case strings.EqualFold(u.Scheme, "h2c"): // DNS-over-HTTPS h2c Remote mode case strings.EqualFold(u.Scheme, "h2c"): // DNS-over-HTTPS h2c Remote mode
return NewDoHNameServer(u, dispatcher, queryStrategy, true) return NewDoHNameServer(u, queryStrategy, dispatcher, true), nil
case strings.EqualFold(u.Scheme, "https+local"): // DNS-over-HTTPS Local mode case strings.EqualFold(u.Scheme, "https+local"): // DNS-over-HTTPS Local mode
return NewDoHLocalNameServer(u, queryStrategy), nil return NewDoHNameServer(u, queryStrategy, nil, false), nil
case strings.EqualFold(u.Scheme, "h2c+local"): // DNS-over-HTTPS h2c Local mode
return NewDoHNameServer(u, queryStrategy, nil, true), nil
case strings.EqualFold(u.Scheme, "quic+local"): // DNS-over-QUIC Local mode case strings.EqualFold(u.Scheme, "quic+local"): // DNS-over-QUIC Local mode
return NewQUICNameServer(u, queryStrategy) return NewQUICNameServer(u, queryStrategy)
case strings.EqualFold(u.Scheme, "tcp"): // DNS-over-TCP Remote mode case strings.EqualFold(u.Scheme, "tcp"): // DNS-over-TCP Remote mode
@@ -159,11 +165,19 @@ func NewClient(
} }
} }
var timeoutMs = 4000 * time.Millisecond
if ns.TimeoutMs > 0 {
timeoutMs = time.Duration(ns.TimeoutMs) * time.Millisecond
}
client.server = server client.server = server
client.clientIP = clientIP client.clientIP = clientIP
client.skipFallback = ns.SkipFallback client.skipFallback = ns.SkipFallback
client.domains = rules client.domains = rules
client.expectIPs = matchers client.expectedIPs = matchers
client.allowUnexpectedIPs = ns.AllowUnexpectedIPs
client.tag = ns.Tag
client.timeoutMs = timeoutMs
return nil return nil
}) })
return client, err return client, err
@@ -175,25 +189,33 @@ func (c *Client) Name() string {
} }
// QueryIP sends DNS query to the name server with the client's IP. // QueryIP sends DNS query to the name server with the client's IP.
func (c *Client) QueryIP(ctx context.Context, domain string, option dns.IPOption, disableCache bool) ([]net.IP, error) { func (c *Client) QueryIP(ctx context.Context, domain string, option dns.IPOption, disableCache bool) ([]net.IP, uint32, error) {
ctx, cancel := context.WithTimeout(ctx, 4*time.Second) ctx, cancel := context.WithTimeout(ctx, c.timeoutMs)
ips, err := c.server.QueryIP(ctx, domain, c.clientIP, option, disableCache) if len(c.tag) != 0 {
content := session.InboundFromContext(ctx)
errors.LogDebug(ctx, "DNS: client override tag from ", content.Tag, " to ", c.tag)
// create a new context to override the tag
// do not direct set *content.Tag, it might be used by other clients
ctx = session.ContextWithInbound(ctx, &session.Inbound{Tag: c.tag})
}
ips, ttl, err := c.server.QueryIP(ctx, domain, c.clientIP, option, disableCache)
cancel() cancel()
if err != nil { if err != nil {
return ips, err return ips, ttl, err
} }
return c.MatchExpectedIPs(domain, ips) netips, err := c.MatchExpectedIPs(domain, ips)
return netips, ttl, err
} }
// MatchExpectedIPs matches queried domain IPs with expected IPs and returns matched ones. // MatchExpectedIPs matches queried domain IPs with expected IPs and returns matched ones.
func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error) { func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error) {
if len(c.expectIPs) == 0 { if len(c.expectedIPs) == 0 {
return ips, nil return ips, nil
} }
newIps := []net.IP{} newIps := []net.IP{}
for _, ip := range ips { for _, ip := range ips {
for _, matcher := range c.expectIPs { for _, matcher := range c.expectedIPs {
if matcher.Match(ip) { if matcher.Match(ip) {
newIps = append(newIps, ip) newIps = append(newIps, ip)
break break
@@ -201,9 +223,12 @@ func (c *Client) MatchExpectedIPs(domain string, ips []net.IP) ([]net.IP, error)
} }
} }
if len(newIps) == 0 { if len(newIps) == 0 {
if c.allowUnexpectedIPs {
return ips, nil
}
return nil, errExpectedIPNonMatch return nil, errExpectedIPNonMatch
} }
errors.LogDebug(context.Background(), "domain ", domain, " expectIPs ", newIps, " matched at server ", c.Name()) errors.LogDebug(context.Background(), "domain ", domain, " expectedIPs ", newIps, " matched at server ", c.Name())
return newIps, nil return newIps, nil
} }

View File

@@ -8,10 +8,13 @@ import (
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strings"
"sync" "sync"
"time" "time"
utls "github.com/refraction-networking/utls"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/crypto"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/log" "github.com/xtls/xray-core/common/log"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
@@ -31,7 +34,6 @@ import (
// which is compatible with traditional dns over udp(RFC1035), // which is compatible with traditional dns over udp(RFC1035),
// thus most of the DOH implementation is copied from udpns.go // thus most of the DOH implementation is copied from udpns.go
type DoHNameServer struct { type DoHNameServer struct {
dispatcher routing.Dispatcher
sync.RWMutex sync.RWMutex
ips map[string]*record ips map[string]*record
pub *pubsub.Service pub *pubsub.Service
@@ -42,108 +44,18 @@ type DoHNameServer struct {
queryStrategy QueryStrategy queryStrategy QueryStrategy
} }
// NewDoHNameServer creates DOH server object for remote resolving. // NewDoHNameServer creates DOH/DOHL client object for remote/local resolving.
func NewDoHNameServer(url *url.URL, dispatcher routing.Dispatcher, queryStrategy QueryStrategy, h2c bool) (*DoHNameServer, error) { func NewDoHNameServer(url *url.URL, queryStrategy QueryStrategy, dispatcher routing.Dispatcher, h2c bool) *DoHNameServer {
url.Scheme = "https" url.Scheme = "https"
errors.LogInfo(context.Background(), "DNS: created Remote DNS-over-HTTPS client for ", url.String(), ", with h2c ", h2c) mode := "DOH"
s := baseDOHNameServer(url, "DOH", queryStrategy) if dispatcher == nil {
mode = "DOHL"
s.dispatcher = dispatcher
dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
dest, err := net.ParseDestination(network + ":" + addr)
if err != nil {
return nil, err
}
dnsCtx := toDnsContext(ctx, s.dohURL)
if h2c {
dnsCtx = session.ContextWithMitmAlpn11(dnsCtx, false) // for insurance
dnsCtx = session.ContextWithMitmServerName(dnsCtx, url.Hostname())
}
link, err := s.dispatcher.Dispatch(dnsCtx, dest)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
if err != nil {
return nil, err
}
cc := common.ChainedClosable{}
if cw, ok := link.Writer.(common.Closable); ok {
cc = append(cc, cw)
}
if cr, ok := link.Reader.(common.Closable); ok {
cc = append(cc, cr)
}
return cnc.NewConnection(
cnc.ConnectionInputMulti(link.Writer),
cnc.ConnectionOutputMulti(link.Reader),
cnc.ConnectionOnClose(cc),
), nil
} }
errors.LogInfo(context.Background(), "DNS: created ", mode, " client for ", url.String(), ", with h2c ", h2c)
s.httpClient = &http.Client{
Timeout: time.Second * 180,
Transport: &http.Transport{
MaxIdleConns: 30,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 30 * time.Second,
ForceAttemptHTTP2: true,
DialContext: dialContext,
},
}
if h2c {
s.httpClient.Transport = &http2.Transport{
IdleConnTimeout: 90 * time.Second,
DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
return dialContext(ctx, network, addr)
},
}
}
return s, nil
}
// NewDoHLocalNameServer creates DOH client object for local resolving
func NewDoHLocalNameServer(url *url.URL, queryStrategy QueryStrategy) *DoHNameServer {
url.Scheme = "https"
s := baseDOHNameServer(url, "DOHL", queryStrategy)
tr := &http.Transport{
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
dest, err := net.ParseDestination(network + ":" + addr)
if err != nil {
return nil, err
}
conn, err := internet.DialSystem(ctx, dest, nil)
log.Record(&log.AccessMessage{
From: "DNS",
To: s.dohURL,
Status: log.AccessAccepted,
Detour: "local",
})
if err != nil {
return nil, err
}
return conn, nil
},
}
s.httpClient = &http.Client{
Timeout: time.Second * 180,
Transport: tr,
}
errors.LogInfo(context.Background(), "DNS: created Local DNS-over-HTTPS client for ", url.String())
return s
}
func baseDOHNameServer(url *url.URL, prefix string, queryStrategy QueryStrategy) *DoHNameServer {
s := &DoHNameServer{ s := &DoHNameServer{
ips: make(map[string]*record), ips: make(map[string]*record),
pub: pubsub.NewService(), pub: pubsub.NewService(),
name: prefix + "//" + url.Host, name: mode + "//" + url.Host,
dohURL: url.String(), dohURL: url.String(),
queryStrategy: queryStrategy, queryStrategy: queryStrategy,
} }
@@ -151,6 +63,65 @@ func baseDOHNameServer(url *url.URL, prefix string, queryStrategy QueryStrategy)
Interval: time.Minute, Interval: time.Minute,
Execute: s.Cleanup, Execute: s.Cleanup,
} }
s.httpClient = &http.Client{
Transport: &http2.Transport{
IdleConnTimeout: net.ConnIdleTimeout,
ReadIdleTimeout: net.ChromeH2KeepAlivePeriod,
DialTLSContext: func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error) {
dest, err := net.ParseDestination(network + ":" + addr)
if err != nil {
return nil, err
}
var conn net.Conn
if dispatcher != nil {
dnsCtx := toDnsContext(ctx, s.dohURL)
if h2c {
dnsCtx = session.ContextWithMitmAlpn11(dnsCtx, false) // for insurance
dnsCtx = session.ContextWithMitmServerName(dnsCtx, url.Hostname())
}
link, err := dispatcher.Dispatch(dnsCtx, dest)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
if err != nil {
return nil, err
}
cc := common.ChainedClosable{}
if cw, ok := link.Writer.(common.Closable); ok {
cc = append(cc, cw)
}
if cr, ok := link.Reader.(common.Closable); ok {
cc = append(cc, cr)
}
conn = cnc.NewConnection(
cnc.ConnectionInputMulti(link.Writer),
cnc.ConnectionOutputMulti(link.Reader),
cnc.ConnectionOnClose(cc),
)
} else {
log.Record(&log.AccessMessage{
From: "DNS",
To: s.dohURL,
Status: log.AccessAccepted,
Detour: "local",
})
conn, err = internet.DialSystem(ctx, dest, nil)
if err != nil {
return nil, err
}
}
if !h2c {
conn = utls.UClient(conn, &utls.Config{ServerName: url.Hostname()}, utls.HelloChrome_Auto)
if err := conn.(*utls.UConn).HandshakeContext(ctx); err != nil {
return nil, err
}
}
return conn, nil
},
},
}
return s return s
} }
@@ -248,7 +219,9 @@ func (s *DoHNameServer) sendQuery(ctx context.Context, domain string, clientIP n
return return
} }
reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) // As we don't want our traffic pattern looks like DoH, we use Random-Length Padding instead of Block-Length Padding recommended in RFC 8467
// Although DoH server like 1.1.1.1 will pad the response to Block-Length 468, at least it is better than no padding for response at all
reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP, int(crypto.RandBetween(100, 300))))
var deadline time.Time var deadline time.Time
if d, ok := ctx.Deadline(); ok { if d, ok := ctx.Deadline(); ok {
@@ -310,6 +283,8 @@ func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte,
req.Header.Add("Accept", "application/dns-message") req.Header.Add("Accept", "application/dns-message")
req.Header.Add("Content-Type", "application/dns-message") req.Header.Add("Content-Type", "application/dns-message")
req.Header.Set("X-Padding", strings.Repeat("X", int(crypto.RandBetween(100, 1000))))
hc := s.httpClient hc := s.httpClient
resp, err := hc.Do(req.WithContext(ctx)) resp, err := hc.Do(req.WithContext(ctx))
@@ -326,64 +301,66 @@ func (s *DoHNameServer) dohHTTPSContext(ctx context.Context, b []byte) ([]byte,
return io.ReadAll(resp.Body) return io.ReadAll(resp.Body)
} }
func (s *DoHNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) { func (s *DoHNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, uint32, error) {
s.RLock() s.RLock()
record, found := s.ips[domain] record, found := s.ips[domain]
s.RUnlock() s.RUnlock()
if !found { if !found {
return nil, errRecordNotFound return nil, 0, errRecordNotFound
} }
var err4 error var err4 error
var err6 error var err6 error
var ips []net.Address var ips []net.Address
var ip6 []net.Address var ip6 []net.Address
var ttl uint32
if option.IPv4Enable { if option.IPv4Enable {
ips, err4 = record.A.getIPs() ips, ttl, err4 = record.A.getIPs()
} }
if option.IPv6Enable { if option.IPv6Enable {
ip6, err6 = record.AAAA.getIPs() ip6, ttl, err6 = record.AAAA.getIPs()
ips = append(ips, ip6...) ips = append(ips, ip6...)
} }
if len(ips) > 0 { if len(ips) > 0 {
return toNetIP(ips) netips, err := toNetIP(ips)
return netips, ttl, err
} }
if err4 != nil { if err4 != nil {
return nil, err4 return nil, 0, err4
} }
if err6 != nil { if err6 != nil {
return nil, err6 return nil, 0, err6
} }
if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) { if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
return nil, dns_feature.ErrEmptyResponse return nil, 0, dns_feature.ErrEmptyResponse
} }
return nil, errRecordNotFound return nil, 0, errRecordNotFound
} }
// QueryIP implements Server. // QueryIP implements Server.
func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { // nolint: dupl func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, uint32, error) { // nolint: dupl
fqdn := Fqdn(domain) fqdn := Fqdn(domain)
option = ResolveIpOptionOverride(s.queryStrategy, option) option = ResolveIpOptionOverride(s.queryStrategy, option)
if !option.IPv4Enable && !option.IPv6Enable { if !option.IPv4Enable && !option.IPv6Enable {
return nil, dns_feature.ErrEmptyResponse return nil, 0, dns_feature.ErrEmptyResponse
} }
if disableCache { if disableCache {
errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name) errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name)
} else { } else {
ips, err := s.findIPsForDomain(fqdn, option) ips, ttl, err := s.findIPsForDomain(fqdn, option)
if err == nil || err == dns_feature.ErrEmptyResponse { if err == nil || err == dns_feature.ErrEmptyResponse || dns_feature.RCodeFromError(err) == 3 {
errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips) errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips)
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err}) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err})
return ips, err return ips, ttl, err
} }
} }
@@ -417,15 +394,15 @@ func (s *DoHNameServer) QueryIP(ctx context.Context, domain string, clientIP net
start := time.Now() start := time.Now()
for { for {
ips, err := s.findIPsForDomain(fqdn, option) ips, ttl, err := s.findIPsForDomain(fqdn, option)
if err != errRecordNotFound { if err != errRecordNotFound {
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err}) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
return ips, err return ips, ttl, err
} }
select { select {
case <-ctx.Done(): case <-ctx.Done():
return nil, ctx.Err() return nil, 0, ctx.Err()
case <-done: case <-done:
} }
} }

View File

@@ -17,9 +17,9 @@ func TestDOHNameServer(t *testing.T) {
url, err := url.Parse("https+local://1.1.1.1/dns-query") url, err := url.Parse("https+local://1.1.1.1/dns-query")
common.Must(err) common.Must(err)
s := NewDoHLocalNameServer(url, QueryStrategy_USE_IP) s := NewDoHNameServer(url, QueryStrategy_USE_IP, nil, false)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)
@@ -34,9 +34,9 @@ func TestDOHNameServerWithCache(t *testing.T) {
url, err := url.Parse("https+local://1.1.1.1/dns-query") url, err := url.Parse("https+local://1.1.1.1/dns-query")
common.Must(err) common.Must(err)
s := NewDoHLocalNameServer(url, QueryStrategy_USE_IP) s := NewDoHNameServer(url, QueryStrategy_USE_IP, nil, false)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)
@@ -47,7 +47,7 @@ func TestDOHNameServerWithCache(t *testing.T) {
} }
ctx2, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx2, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips2, err := s.QueryIP(ctx2, "google.com", net.IP(nil), dns_feature.IPOption{ ips2, _, err := s.QueryIP(ctx2, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, true) }, true)
@@ -62,9 +62,9 @@ func TestDOHNameServerWithIPv4Override(t *testing.T) {
url, err := url.Parse("https+local://1.1.1.1/dns-query") url, err := url.Parse("https+local://1.1.1.1/dns-query")
common.Must(err) common.Must(err)
s := NewDoHLocalNameServer(url, QueryStrategy_USE_IP4) s := NewDoHNameServer(url, QueryStrategy_USE_IP4, nil, false)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)
@@ -85,9 +85,9 @@ func TestDOHNameServerWithIPv6Override(t *testing.T) {
url, err := url.Parse("https+local://1.1.1.1/dns-query") url, err := url.Parse("https+local://1.1.1.1/dns-query")
common.Must(err) common.Must(err)
s := NewDoHLocalNameServer(url, QueryStrategy_USE_IP6) s := NewDoHNameServer(url, QueryStrategy_USE_IP6, nil, false)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)

View File

@@ -20,9 +20,9 @@ func (FakeDNSServer) Name() string {
return "FakeDNS" return "FakeDNS"
} }
func (f *FakeDNSServer) QueryIP(ctx context.Context, domain string, _ net.IP, opt dns.IPOption, _ bool) ([]net.IP, error) { func (f *FakeDNSServer) QueryIP(ctx context.Context, domain string, _ net.IP, opt dns.IPOption, _ bool) ([]net.IP, uint32, error) {
if f.fakeDNSEngine == nil { if f.fakeDNSEngine == nil {
return nil, errors.New("Unable to locate a fake DNS Engine").AtError() return nil, 0, errors.New("Unable to locate a fake DNS Engine").AtError()
} }
var ips []net.Address var ips []net.Address
@@ -34,13 +34,13 @@ func (f *FakeDNSServer) QueryIP(ctx context.Context, domain string, _ net.IP, op
netIP, err := toNetIP(ips) netIP, err := toNetIP(ips)
if err != nil { if err != nil {
return nil, errors.New("Unable to convert IP to net ip").Base(err).AtError() return nil, 0, errors.New("Unable to convert IP to net ip").Base(err).AtError()
} }
errors.LogInfo(ctx, f.Name(), " got answer: ", domain, " -> ", ips) errors.LogInfo(ctx, f.Name(), " got answer: ", domain, " -> ", ips)
if len(netIP) > 0 { if len(netIP) > 0 {
return netIP, nil return netIP, 1, nil // fakeIP ttl is 1
} }
return nil, dns.ErrEmptyResponse return nil, 0, dns.ErrEmptyResponse
} }

View File

@@ -21,14 +21,14 @@ type LocalNameServer struct {
const errEmptyResponse = "No address associated with hostname" const errEmptyResponse = "No address associated with hostname"
// QueryIP implements Server. // QueryIP implements Server.
func (s *LocalNameServer) QueryIP(ctx context.Context, domain string, _ net.IP, option dns.IPOption, _ bool) (ips []net.IP, err error) { func (s *LocalNameServer) QueryIP(ctx context.Context, domain string, _ net.IP, option dns.IPOption, _ bool) (ips []net.IP, ttl uint32, err error) {
option = ResolveIpOptionOverride(s.queryStrategy, option) option = ResolveIpOptionOverride(s.queryStrategy, option)
if !option.IPv4Enable && !option.IPv6Enable { if !option.IPv4Enable && !option.IPv6Enable {
return nil, dns.ErrEmptyResponse return nil, 0, dns.ErrEmptyResponse
} }
start := time.Now() start := time.Now()
ips, err = s.client.LookupIP(domain, option) ips, ttl, err = s.client.LookupIP(domain, option)
if err != nil && strings.HasSuffix(err.Error(), errEmptyResponse) { if err != nil && strings.HasSuffix(err.Error(), errEmptyResponse) {
err = dns.ErrEmptyResponse err = dns.ErrEmptyResponse

View File

@@ -14,7 +14,7 @@ import (
func TestLocalNameServer(t *testing.T) { func TestLocalNameServer(t *testing.T) {
s := NewLocalNameServer(QueryStrategy_USE_IP) s := NewLocalNameServer(QueryStrategy_USE_IP)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
ips, err := s.QueryIP(ctx, "google.com", net.IP{}, dns.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP{}, dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,

View File

@@ -160,7 +160,7 @@ func (s *QUICNameServer) newReqID() uint16 {
func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
errors.LogInfo(ctx, s.name, " querying: ", domain) errors.LogInfo(ctx, s.name, " querying: ", domain)
reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP, 0))
var deadline time.Time var deadline time.Time
if d, ok := ctx.Deadline(); ok { if d, ok := ctx.Deadline(); ok {
@@ -244,64 +244,66 @@ func (s *QUICNameServer) sendQuery(ctx context.Context, domain string, clientIP
} }
} }
func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) { func (s *QUICNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, uint32, error) {
s.RLock() s.RLock()
record, found := s.ips[domain] record, found := s.ips[domain]
s.RUnlock() s.RUnlock()
if !found { if !found {
return nil, errRecordNotFound return nil, 0, errRecordNotFound
} }
var err4 error var err4 error
var err6 error var err6 error
var ips []net.Address var ips []net.Address
var ip6 []net.Address var ip6 []net.Address
var ttl uint32
if option.IPv4Enable { if option.IPv4Enable {
ips, err4 = record.A.getIPs() ips, ttl, err4 = record.A.getIPs()
} }
if option.IPv6Enable { if option.IPv6Enable {
ip6, err6 = record.AAAA.getIPs() ip6, ttl, err6 = record.AAAA.getIPs()
ips = append(ips, ip6...) ips = append(ips, ip6...)
} }
if len(ips) > 0 { if len(ips) > 0 {
return toNetIP(ips) netips, err := toNetIP(ips)
return netips, ttl, err
} }
if err4 != nil { if err4 != nil {
return nil, err4 return nil, 0, err4
} }
if err6 != nil { if err6 != nil {
return nil, err6 return nil, 0, err6
} }
if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) { if (option.IPv4Enable && record.A != nil) || (option.IPv6Enable && record.AAAA != nil) {
return nil, dns_feature.ErrEmptyResponse return nil, 0, dns_feature.ErrEmptyResponse
} }
return nil, errRecordNotFound return nil, 0, errRecordNotFound
} }
// QueryIP is called from dns.Server->queryIPTimeout // QueryIP is called from dns.Server->queryIPTimeout
func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, uint32, error) {
fqdn := Fqdn(domain) fqdn := Fqdn(domain)
option = ResolveIpOptionOverride(s.queryStrategy, option) option = ResolveIpOptionOverride(s.queryStrategy, option)
if !option.IPv4Enable && !option.IPv6Enable { if !option.IPv4Enable && !option.IPv6Enable {
return nil, dns_feature.ErrEmptyResponse return nil, 0, dns_feature.ErrEmptyResponse
} }
if disableCache { if disableCache {
errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name) errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name)
} else { } else {
ips, err := s.findIPsForDomain(fqdn, option) ips, ttl, err := s.findIPsForDomain(fqdn, option)
if err == nil || err == dns_feature.ErrEmptyResponse { if err == nil || err == dns_feature.ErrEmptyResponse || dns_feature.RCodeFromError(err) == 3 {
errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips) errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips)
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err}) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err})
return ips, err return ips, ttl, err
} }
} }
@@ -335,15 +337,15 @@ func (s *QUICNameServer) QueryIP(ctx context.Context, domain string, clientIP ne
start := time.Now() start := time.Now()
for { for {
ips, err := s.findIPsForDomain(fqdn, option) ips, ttl, err := s.findIPsForDomain(fqdn, option)
if err != errRecordNotFound { if err != errRecordNotFound {
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err}) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
return ips, err return ips, ttl, err
} }
select { select {
case <-ctx.Done(): case <-ctx.Done():
return nil, ctx.Err() return nil, 0, ctx.Err()
case <-done: case <-done:
} }
} }

View File

@@ -19,7 +19,7 @@ func TestQUICNameServer(t *testing.T) {
s, err := NewQUICNameServer(url, QueryStrategy_USE_IP) s, err := NewQUICNameServer(url, QueryStrategy_USE_IP)
common.Must(err) common.Must(err)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)
@@ -30,7 +30,7 @@ func TestQUICNameServer(t *testing.T) {
} }
ctx2, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx2, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips2, err := s.QueryIP(ctx2, "google.com", net.IP(nil), dns.IPOption{ ips2, _, err := s.QueryIP(ctx2, "google.com", net.IP(nil), dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, true) }, true)
@@ -47,7 +47,7 @@ func TestQUICNameServerWithIPv4Override(t *testing.T) {
s, err := NewQUICNameServer(url, QueryStrategy_USE_IP4) s, err := NewQUICNameServer(url, QueryStrategy_USE_IP4)
common.Must(err) common.Must(err)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)
@@ -70,7 +70,7 @@ func TestQUICNameServerWithIPv6Override(t *testing.T) {
s, err := NewQUICNameServer(url, QueryStrategy_USE_IP6) s, err := NewQUICNameServer(url, QueryStrategy_USE_IP6)
common.Must(err) common.Must(err)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2) ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)

View File

@@ -192,7 +192,7 @@ func (s *TCPNameServer) newReqID() uint16 {
func (s *TCPNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { func (s *TCPNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
errors.LogDebug(ctx, s.name, " querying DNS for: ", domain) errors.LogDebug(ctx, s.name, " querying DNS for: ", domain)
reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP, 0))
var deadline time.Time var deadline time.Time
if d, ok := ctx.Deadline(); ok { if d, ok := ctx.Deadline(); ok {
@@ -273,60 +273,62 @@ func (s *TCPNameServer) sendQuery(ctx context.Context, domain string, clientIP n
} }
} }
func (s *TCPNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) { func (s *TCPNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, uint32, error) {
s.RLock() s.RLock()
record, found := s.ips[domain] record, found := s.ips[domain]
s.RUnlock() s.RUnlock()
if !found { if !found {
return nil, errRecordNotFound return nil, 0, errRecordNotFound
} }
var err4 error var err4 error
var err6 error var err6 error
var ips []net.Address var ips []net.Address
var ip6 []net.Address var ip6 []net.Address
var ttl uint32
if option.IPv4Enable { if option.IPv4Enable {
ips, err4 = record.A.getIPs() ips, ttl, err4 = record.A.getIPs()
} }
if option.IPv6Enable { if option.IPv6Enable {
ip6, err6 = record.AAAA.getIPs() ip6, ttl, err6 = record.AAAA.getIPs()
ips = append(ips, ip6...) ips = append(ips, ip6...)
} }
if len(ips) > 0 { if len(ips) > 0 {
return toNetIP(ips) netips, err := toNetIP(ips)
return netips, ttl, err
} }
if err4 != nil { if err4 != nil {
return nil, err4 return nil, 0, err4
} }
if err6 != nil { if err6 != nil {
return nil, err6 return nil, 0, err6
} }
return nil, dns_feature.ErrEmptyResponse return nil, 0, dns_feature.ErrEmptyResponse
} }
// QueryIP implements Server. // QueryIP implements Server.
func (s *TCPNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { func (s *TCPNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, uint32, error) {
fqdn := Fqdn(domain) fqdn := Fqdn(domain)
option = ResolveIpOptionOverride(s.queryStrategy, option) option = ResolveIpOptionOverride(s.queryStrategy, option)
if !option.IPv4Enable && !option.IPv6Enable { if !option.IPv4Enable && !option.IPv6Enable {
return nil, dns_feature.ErrEmptyResponse return nil, 0, dns_feature.ErrEmptyResponse
} }
if disableCache { if disableCache {
errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name) errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name)
} else { } else {
ips, err := s.findIPsForDomain(fqdn, option) ips, ttl, err := s.findIPsForDomain(fqdn, option)
if err == nil || err == dns_feature.ErrEmptyResponse { if err == nil || err == dns_feature.ErrEmptyResponse || dns_feature.RCodeFromError(err) == 3 {
errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips) errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips)
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err}) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err})
return ips, err return ips, ttl, err
} }
} }
@@ -360,15 +362,15 @@ func (s *TCPNameServer) QueryIP(ctx context.Context, domain string, clientIP net
start := time.Now() start := time.Now()
for { for {
ips, err := s.findIPsForDomain(fqdn, option) ips, ttl, err := s.findIPsForDomain(fqdn, option)
if err != errRecordNotFound { if err != errRecordNotFound {
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err}) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
return ips, err return ips, ttl, err
} }
select { select {
case <-ctx.Done(): case <-ctx.Done():
return nil, ctx.Err() return nil, 0, ctx.Err()
case <-done: case <-done:
} }
} }

View File

@@ -19,7 +19,7 @@ func TestTCPLocalNameServer(t *testing.T) {
s, err := NewTCPLocalNameServer(url, QueryStrategy_USE_IP) s, err := NewTCPLocalNameServer(url, QueryStrategy_USE_IP)
common.Must(err) common.Must(err)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)
@@ -36,7 +36,7 @@ func TestTCPLocalNameServerWithCache(t *testing.T) {
s, err := NewTCPLocalNameServer(url, QueryStrategy_USE_IP) s, err := NewTCPLocalNameServer(url, QueryStrategy_USE_IP)
common.Must(err) common.Must(err)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)
@@ -47,7 +47,7 @@ func TestTCPLocalNameServerWithCache(t *testing.T) {
} }
ctx2, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx2, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips2, err := s.QueryIP(ctx2, "google.com", net.IP(nil), dns_feature.IPOption{ ips2, _, err := s.QueryIP(ctx2, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, true) }, true)
@@ -64,7 +64,7 @@ func TestTCPLocalNameServerWithIPv4Override(t *testing.T) {
s, err := NewTCPLocalNameServer(url, QueryStrategy_USE_IP4) s, err := NewTCPLocalNameServer(url, QueryStrategy_USE_IP4)
common.Must(err) common.Must(err)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)
@@ -88,7 +88,7 @@ func TestTCPLocalNameServerWithIPv6Override(t *testing.T) {
s, err := NewTCPLocalNameServer(url, QueryStrategy_USE_IP6) s, err := NewTCPLocalNameServer(url, QueryStrategy_USE_IP6)
common.Must(err) common.Must(err)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ips, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{ ips, _, err := s.QueryIP(ctx, "google.com", net.IP(nil), dns_feature.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
}, false) }, false)

View File

@@ -27,7 +27,7 @@ type ClassicNameServer struct {
name string name string
address *net.Destination address *net.Destination
ips map[string]*record ips map[string]*record
requests map[uint16]*dnsRequest requests map[uint16]*udpDnsRequest
pub *pubsub.Service pub *pubsub.Service
udpServer *udp.Dispatcher udpServer *udp.Dispatcher
cleanup *task.Periodic cleanup *task.Periodic
@@ -35,6 +35,11 @@ type ClassicNameServer struct {
queryStrategy QueryStrategy queryStrategy QueryStrategy
} }
type udpDnsRequest struct {
dnsRequest
ctx context.Context
}
// NewClassicNameServer creates udp server object for remote resolving. // NewClassicNameServer creates udp server object for remote resolving.
func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher, queryStrategy QueryStrategy) *ClassicNameServer { func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher, queryStrategy QueryStrategy) *ClassicNameServer {
// default to 53 if unspecific // default to 53 if unspecific
@@ -45,7 +50,7 @@ func NewClassicNameServer(address net.Destination, dispatcher routing.Dispatcher
s := &ClassicNameServer{ s := &ClassicNameServer{
address: &address, address: &address,
ips: make(map[string]*record), ips: make(map[string]*record),
requests: make(map[uint16]*dnsRequest), requests: make(map[uint16]*udpDnsRequest),
pub: pubsub.NewService(), pub: pubsub.NewService(),
name: strings.ToUpper(address.String()), name: strings.ToUpper(address.String()),
queryStrategy: queryStrategy, queryStrategy: queryStrategy,
@@ -101,7 +106,7 @@ func (s *ClassicNameServer) Cleanup() error {
} }
if len(s.requests) == 0 { if len(s.requests) == 0 {
s.requests = make(map[uint16]*dnsRequest) s.requests = make(map[uint16]*udpDnsRequest)
} }
return nil return nil
@@ -128,6 +133,27 @@ func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_prot
return return
} }
// if truncated, retry with EDNS0 option(udp payload size: 1350)
if ipRec.RawHeader.Truncated {
// if already has EDNS0 option, no need to retry
if ok && len(req.msg.Additionals) == 0 {
// copy necessary meta data from original request
// and add EDNS0 option
opt := new(dnsmessage.Resource)
common.Must(opt.Header.SetEDNS0(1350, 0xfe00, true))
opt.Body = &dnsmessage.OPTResource{}
newMsg := *req.msg
newReq := *req
newMsg.Additionals = append(newMsg.Additionals, *opt)
newMsg.ID = s.newReqID()
newReq.msg = &newMsg
s.addPendingRequest(&newReq)
b, _ := dns.PackMessage(newReq.msg)
s.udpServer.Dispatch(toDnsContext(newReq.ctx, s.address.String()), *s.address, b)
return
}
}
var rec record var rec record
switch req.reqType { switch req.reqType {
case dnsmessage.TypeA: case dnsmessage.TypeA:
@@ -179,7 +205,7 @@ func (s *ClassicNameServer) newReqID() uint16 {
return uint16(atomic.AddUint32(&s.reqID, 1)) return uint16(atomic.AddUint32(&s.reqID, 1))
} }
func (s *ClassicNameServer) addPendingRequest(req *dnsRequest) { func (s *ClassicNameServer) addPendingRequest(req *udpDnsRequest) {
s.Lock() s.Lock()
defer s.Unlock() defer s.Unlock()
@@ -191,69 +217,75 @@ func (s *ClassicNameServer) addPendingRequest(req *dnsRequest) {
func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) { func (s *ClassicNameServer) sendQuery(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption) {
errors.LogDebug(ctx, s.name, " querying DNS for: ", domain) errors.LogDebug(ctx, s.name, " querying DNS for: ", domain)
reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP)) reqs := buildReqMsgs(domain, option, s.newReqID, genEDNS0Options(clientIP, 0))
for _, req := range reqs { for _, req := range reqs {
s.addPendingRequest(req) udpReq := &udpDnsRequest{
dnsRequest: *req,
ctx: ctx,
}
s.addPendingRequest(udpReq)
b, _ := dns.PackMessage(req.msg) b, _ := dns.PackMessage(req.msg)
s.udpServer.Dispatch(toDnsContext(ctx, s.address.String()), *s.address, b) s.udpServer.Dispatch(toDnsContext(ctx, s.address.String()), *s.address, b)
} }
} }
func (s *ClassicNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, error) { func (s *ClassicNameServer) findIPsForDomain(domain string, option dns_feature.IPOption) ([]net.IP, uint32, error) {
s.RLock() s.RLock()
record, found := s.ips[domain] record, found := s.ips[domain]
s.RUnlock() s.RUnlock()
if !found { if !found {
return nil, errRecordNotFound return nil, 0, errRecordNotFound
} }
var err4 error var err4 error
var err6 error var err6 error
var ips []net.Address var ips []net.Address
var ip6 []net.Address var ip6 []net.Address
var ttl uint32
if option.IPv4Enable { if option.IPv4Enable {
ips, err4 = record.A.getIPs() ips, ttl, err4 = record.A.getIPs()
} }
if option.IPv6Enable { if option.IPv6Enable {
ip6, err6 = record.AAAA.getIPs() ip6, ttl, err6 = record.AAAA.getIPs()
ips = append(ips, ip6...) ips = append(ips, ip6...)
} }
if len(ips) > 0 { if len(ips) > 0 {
return toNetIP(ips) netips, err := toNetIP(ips)
return netips, ttl, err
} }
if err4 != nil { if err4 != nil {
return nil, err4 return nil, 0, err4
} }
if err6 != nil { if err6 != nil {
return nil, err6 return nil, 0, err6
} }
return nil, dns_feature.ErrEmptyResponse return nil, 0, dns_feature.ErrEmptyResponse
} }
// QueryIP implements Server. // QueryIP implements Server.
func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, error) { func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, clientIP net.IP, option dns_feature.IPOption, disableCache bool) ([]net.IP, uint32, error) {
fqdn := Fqdn(domain) fqdn := Fqdn(domain)
option = ResolveIpOptionOverride(s.queryStrategy, option) option = ResolveIpOptionOverride(s.queryStrategy, option)
if !option.IPv4Enable && !option.IPv6Enable { if !option.IPv4Enable && !option.IPv6Enable {
return nil, dns_feature.ErrEmptyResponse return nil, 0, dns_feature.ErrEmptyResponse
} }
if disableCache { if disableCache {
errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name) errors.LogDebug(ctx, "DNS cache is disabled. Querying IP for ", domain, " at ", s.name)
} else { } else {
ips, err := s.findIPsForDomain(fqdn, option) ips, ttl, err := s.findIPsForDomain(fqdn, option)
if err == nil || err == dns_feature.ErrEmptyResponse { if err == nil || err == dns_feature.ErrEmptyResponse || dns_feature.RCodeFromError(err) == 3 {
errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips) errors.LogDebugInner(ctx, err, s.name, " cache HIT ", domain, " -> ", ips)
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err}) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSCacheHit, Elapsed: 0, Error: err})
return ips, err return ips, ttl, err
} }
} }
@@ -287,15 +319,15 @@ func (s *ClassicNameServer) QueryIP(ctx context.Context, domain string, clientIP
start := time.Now() start := time.Now()
for { for {
ips, err := s.findIPsForDomain(fqdn, option) ips, ttl, err := s.findIPsForDomain(fqdn, option)
if err != errRecordNotFound { if err != errRecordNotFound {
log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err}) log.Record(&log.DNSLog{Server: s.name, Domain: domain, Result: ips, Status: log.DNSQueried, Elapsed: time.Since(start), Error: err})
return ips, err return ips, ttl, err
} }
select { select {
case <-ctx.Done(): case <-ctx.Done():
return nil, ctx.Err() return nil, 0, ctx.Err()
case <-done: case <-done:
} }
} }

View File

@@ -324,6 +324,7 @@ func (w *udpWorker) callback(b *buf.Buffer, source net.Destination, originalDest
if w.sniffingConfig != nil { if w.sniffingConfig != nil {
content.SniffingRequest.Enabled = w.sniffingConfig.Enabled content.SniffingRequest.Enabled = w.sniffingConfig.Enabled
content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride content.SniffingRequest.OverrideDestinationForProtocol = w.sniffingConfig.DestinationOverride
content.SniffingRequest.ExcludeForDomain = w.sniffingConfig.DomainsExcluded
content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly content.SniffingRequest.MetadataOnly = w.sniffingConfig.MetadataOnly
content.SniffingRequest.RouteOnly = w.sniffingConfig.RouteOnly content.SniffingRequest.RouteOnly = w.sniffingConfig.RouteOnly
} }

View File

@@ -273,7 +273,16 @@ func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connecti
outbounds := session.OutboundsFromContext(ctx) outbounds := session.OutboundsFromContext(ctx)
ob := outbounds[len(outbounds)-1] ob := outbounds[len(outbounds)-1]
if h.senderSettings.ViaCidr == "" { if h.senderSettings.ViaCidr == "" {
ob.Gateway = h.senderSettings.Via.AsAddress() if h.senderSettings.Via.AsAddress().Family().IsDomain() && h.senderSettings.Via.AsAddress().Domain() == "origin" {
if inbound := session.InboundFromContext(ctx); inbound != nil {
origin, _, err := net.SplitHostPort(inbound.Conn.LocalAddr().String())
if err == nil {
ob.Gateway = net.ParseAddress(origin)
}
}
} else {
ob.Gateway = h.senderSettings.Via.AsAddress()
}
} else { //Get a random address. } else { //Get a random address.
ob.Gateway = ParseRandomIPv6(h.senderSettings.Via.AsAddress(), h.senderSettings.ViaCidr) ob.Gateway = ParseRandomIPv6(h.senderSettings.Via.AsAddress(), h.senderSettings.ViaCidr)
} }

View File

@@ -177,7 +177,7 @@ func TestIPOnDemand(t *testing.T) {
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
}).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes() }).Return([]net.IP{{192, 168, 0, 1}}, uint32(600), nil).AnyTimes()
r := new(Router) r := new(Router)
common.Must(r.Init(context.TODO(), config, mockDNS, nil, nil)) common.Must(r.Init(context.TODO(), config, mockDNS, nil, nil))
@@ -222,7 +222,7 @@ func TestIPIfNonMatchDomain(t *testing.T) {
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,
}).Return([]net.IP{{192, 168, 0, 1}}, nil).AnyTimes() }).Return([]net.IP{{192, 168, 0, 1}}, uint32(600), nil).AnyTimes()
r := new(Router) r := new(Router)
common.Must(r.Init(context.TODO(), config, mockDNS, nil, nil)) common.Must(r.Init(context.TODO(), config, mockDNS, nil, nil))

View File

@@ -40,11 +40,11 @@ func (c *OnlineMap) AddIP(ip string) {
if ip == "127.0.0.1" { if ip == "127.0.0.1" {
return return
} }
c.access.Lock()
if _, ok := list[ip]; !ok { if _, ok := list[ip]; !ok {
c.access.Lock()
list[ip] = time.Now() list[ip] = time.Now()
c.access.Unlock()
} }
c.access.Unlock()
if time.Since(c.lastCleanup) > c.cleanupPeriod { if time.Since(c.lastCleanup) > c.cleanupPeriod {
list = c.RemoveExpiredIPs(list) list = c.RemoveExpiredIPs(list)
c.lastCleanup = time.Now() c.lastCleanup = time.Now()

View File

@@ -1,2 +1,15 @@
// Package crypto provides common crypto libraries for Xray. // Package crypto provides common crypto libraries for Xray.
package crypto // import "github.com/xtls/xray-core/common/crypto" package crypto // import "github.com/xtls/xray-core/common/crypto"
import (
"crypto/rand"
"math/big"
)
func RandBetween(from int64, to int64) int64 {
if from == to {
return from
}
bigInt, _ := rand.Int(rand.Reader, big.NewInt(to-from))
return from + bigInt.Int64()
}

View File

@@ -120,7 +120,7 @@ func (w *ServerWorker) handleStatusKeepAlive(meta *FrameMetadata, reader *buf.Bu
func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error { func (w *ServerWorker) handleStatusNew(ctx context.Context, meta *FrameMetadata, reader *buf.BufferedReader) error {
// deep-clone outbounds because it is going to be mutated concurrently // deep-clone outbounds because it is going to be mutated concurrently
// (Target and OriginalTarget) // (Target and OriginalTarget)
ctx = session.ContextCloneOutbounds(ctx) ctx = session.ContextCloneOutboundsAndContent(ctx)
errors.LogInfo(ctx, "received request for ", meta.Target) errors.LogInfo(ctx, "received request for ", meta.Target)
{ {
msg := &log.AccessMessage{ msg := &log.AccessMessage{

View File

@@ -1,2 +1,14 @@
// Package net is a drop-in replacement to Golang's net package, with some more functionalities. // Package net is a drop-in replacement to Golang's net package, with some more functionalities.
package net // import "github.com/xtls/xray-core/common/net" package net // import "github.com/xtls/xray-core/common/net"
import "time"
// defines the maximum time an idle TCP session can survive in the tunnel, so
// it should be consistent across HTTP versions and with other transports.
const ConnIdleTimeout = 300 * time.Second
// consistent with quic-go
const QuicgoH3KeepAlivePeriod = 10 * time.Second
// consistent with chrome
const ChromeH2KeepAlivePeriod = 45 * time.Second

View File

@@ -3,6 +3,7 @@ package filesystem
import ( import (
"io" "io"
"os" "os"
"path/filepath"
"github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/platform" "github.com/xtls/xray-core/common/platform"
@@ -28,6 +29,13 @@ func ReadAsset(file string) ([]byte, error) {
return ReadFile(platform.GetAssetLocation(file)) return ReadFile(platform.GetAssetLocation(file))
} }
func ReadCert(file string) ([]byte, error) {
if filepath.IsAbs(file) {
return ReadFile(file)
}
return ReadFile(platform.GetCertLocation(file))
}
func CopyFile(dst string, src string) error { func CopyFile(dst string, src string) error {
bytes, err := ReadFile(src) bytes, err := ReadFile(src)
if err != nil { if err != nil {

View File

@@ -21,7 +21,7 @@ func GetToolLocation(file string) string {
return filepath.Join(toolPath, file) return filepath.Join(toolPath, file)
} }
// GetAssetLocation searches for `file` in certain locations // GetAssetLocation searches for `file` in the env dir, the executable dir, and certain locations
func GetAssetLocation(file string) string { func GetAssetLocation(file string) string {
assetPath := NewEnvFlag(AssetLocation).GetValue(getExecutableDir) assetPath := NewEnvFlag(AssetLocation).GetValue(getExecutableDir)
defPath := filepath.Join(assetPath, file) defPath := filepath.Join(assetPath, file)
@@ -42,3 +42,9 @@ func GetAssetLocation(file string) string {
// asset not found, let the caller throw out the error // asset not found, let the caller throw out the error
return defPath return defPath
} }
// GetCertLocation searches for `file` in the env dir and the executable dir
func GetCertLocation(file string) string {
certPath := NewEnvFlag(CertLocation).GetValue(getExecutableDir)
return filepath.Join(certPath, file)
}

View File

@@ -13,6 +13,7 @@ const (
ConfdirLocation = "xray.location.confdir" ConfdirLocation = "xray.location.confdir"
ToolLocation = "xray.location.tool" ToolLocation = "xray.location.tool"
AssetLocation = "xray.location.asset" AssetLocation = "xray.location.asset"
CertLocation = "xray.location.cert"
UseReadV = "xray.buf.readv" UseReadV = "xray.buf.readv"
UseFreedomSplice = "xray.buf.splice" UseFreedomSplice = "xray.buf.splice"

View File

@@ -19,8 +19,14 @@ func GetToolLocation(file string) string {
return filepath.Join(toolPath, file+".exe") return filepath.Join(toolPath, file+".exe")
} }
// GetAssetLocation searches for `file` in the executable dir // GetAssetLocation searches for `file` in the env dir and the executable dir
func GetAssetLocation(file string) string { func GetAssetLocation(file string) string {
assetPath := NewEnvFlag(AssetLocation).GetValue(getExecutableDir) assetPath := NewEnvFlag(AssetLocation).GetValue(getExecutableDir)
return filepath.Join(assetPath, file) return filepath.Join(assetPath, file)
} }
// GetCertLocation searches for `file` in the env dir and the executable dir
func GetCertLocation(file string) string {
certPath := NewEnvFlag(CertLocation).GetValue(getExecutableDir)
return filepath.Join(certPath, file)
}

View File

@@ -63,7 +63,7 @@ func SniffHTTP(b []byte, c context.Context) (*SniffHeader, error) {
ShouldSniffAttr := true ShouldSniffAttr := true
// If content.Attributes have information, that means it comes from HTTP inbound PlainHTTP mode. // If content.Attributes have information, that means it comes from HTTP inbound PlainHTTP mode.
// It will set attributes, so skip it. // It will set attributes, so skip it.
if content == nil || content.AttributeLen() != 0 { if content == nil || len(content.Attributes) != 0 {
ShouldSniffAttr = false ShouldSniffAttr = false
} }
if err := beginWithHTTPMethod(b); err != nil { if err := beginWithHTTPMethod(b); err != nil {

View File

@@ -1,2 +0,0 @@
*.crt
*.key

View File

@@ -42,7 +42,7 @@ func ContextWithOutbounds(ctx context.Context, outbounds []*Outbound) context.Co
return context.WithValue(ctx, outboundSessionKey, outbounds) return context.WithValue(ctx, outboundSessionKey, outbounds)
} }
func ContextCloneOutbounds(ctx context.Context) context.Context { func ContextCloneOutboundsAndContent(ctx context.Context) context.Context {
outbounds := OutboundsFromContext(ctx) outbounds := OutboundsFromContext(ctx)
newOutbounds := make([]*Outbound, len(outbounds)) newOutbounds := make([]*Outbound, len(outbounds))
for i, ob := range outbounds { for i, ob := range outbounds {
@@ -55,7 +55,15 @@ func ContextCloneOutbounds(ctx context.Context) context.Context {
newOutbounds[i] = &v newOutbounds[i] = &v
} }
return ContextWithOutbounds(ctx, newOutbounds) content := ContentFromContext(ctx)
newContent := Content{}
if content != nil {
newContent = *content
if content.Attributes != nil {
panic("content.Attributes != nil")
}
}
return ContextWithContent(ContextWithOutbounds(ctx, newOutbounds), &newContent)
} }
func OutboundsFromContext(ctx context.Context) []*Outbound { func OutboundsFromContext(ctx context.Context) []*Outbound {

View File

@@ -4,7 +4,6 @@ package session // import "github.com/xtls/xray-core/common/session"
import ( import (
"context" "context"
"math/rand" "math/rand"
"sync"
c "github.com/xtls/xray-core/common/ctx" c "github.com/xtls/xray-core/common/ctx"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
@@ -75,8 +74,8 @@ type Outbound struct {
// SniffingRequest controls the behavior of content sniffing. // SniffingRequest controls the behavior of content sniffing.
type SniffingRequest struct { type SniffingRequest struct {
ExcludeForDomain []string ExcludeForDomain []string // read-only once set
OverrideDestinationForProtocol []string OverrideDestinationForProtocol []string // read-only once set
Enabled bool Enabled bool
MetadataOnly bool MetadataOnly bool
RouteOnly bool RouteOnly bool
@@ -92,10 +91,6 @@ type Content struct {
Attributes map[string]string Attributes map[string]string
SkipDNSResolve bool SkipDNSResolve bool
mu sync.Mutex
isLocked bool
} }
// Sockopt is the settings for socket connection. // Sockopt is the settings for socket connection.
@@ -104,22 +99,8 @@ type Sockopt struct {
Mark int32 Mark int32
} }
// Some how when using mux, there will be a same ctx between different requests
// This will cause problem as it's designed for single request, like concurrent map writes
// Add a Mutex as a temp solution
// SetAttribute attaches additional string attributes to content. // SetAttribute attaches additional string attributes to content.
func (c *Content) SetAttribute(name string, value string) { func (c *Content) SetAttribute(name string, value string) {
if c.isLocked {
errors.LogError(context.Background(), "Multiple goroutines are tring to access one routing content, tring to write ", name, ":", value)
}
c.mu.Lock()
c.isLocked = true
defer func() {
c.isLocked = false
c.mu.Unlock()
}()
if c.Attributes == nil { if c.Attributes == nil {
c.Attributes = make(map[string]string) c.Attributes = make(map[string]string)
} }
@@ -128,24 +109,8 @@ func (c *Content) SetAttribute(name string, value string) {
// Attribute retrieves additional string attributes from content. // Attribute retrieves additional string attributes from content.
func (c *Content) Attribute(name string) string { func (c *Content) Attribute(name string) string {
c.mu.Lock()
c.isLocked = true
defer func() {
c.isLocked = false
c.mu.Unlock()
}()
if c.Attributes == nil { if c.Attributes == nil {
return "" return ""
} }
return c.Attributes[name] return c.Attributes[name]
} }
func (c *Content) AttributeLen() int {
c.mu.Lock()
c.isLocked = true
defer func() {
c.isLocked = false
c.mu.Unlock()
}()
return len(c.Attributes)
}

View File

@@ -18,8 +18,8 @@ import (
var ( var (
Version_x byte = 25 Version_x byte = 25
Version_y byte = 2 Version_y byte = 3
Version_z byte = 18 Version_z byte = 31
) )
var ( var (

View File

@@ -21,7 +21,7 @@ type Client interface {
features.Feature features.Feature
// LookupIP returns IP address for the given domain. IPs may contain IPv4 and/or IPv6 addresses. // LookupIP returns IP address for the given domain. IPs may contain IPv4 and/or IPv6 addresses.
LookupIP(domain string, option IPOption) ([]net.IP, error) LookupIP(domain string, option IPOption) ([]net.IP, uint32, error)
} }
type HostsLookup interface { type HostsLookup interface {

View File

@@ -20,10 +20,10 @@ func (*Client) Start() error { return nil }
func (*Client) Close() error { return nil } func (*Client) Close() error { return nil }
// LookupIP implements Client. // LookupIP implements Client.
func (*Client) LookupIP(host string, option dns.IPOption) ([]net.IP, error) { func (*Client) LookupIP(host string, option dns.IPOption) ([]net.IP, uint32, error) {
ips, err := net.LookupIP(host) ips, err := net.LookupIP(host)
if err != nil { if err != nil {
return nil, err return nil, 0, err
} }
parsedIPs := make([]net.IP, 0, len(ips)) parsedIPs := make([]net.IP, 0, len(ips))
ipv4 := make([]net.IP, 0, len(ips)) ipv4 := make([]net.IP, 0, len(ips))
@@ -40,21 +40,22 @@ func (*Client) LookupIP(host string, option dns.IPOption) ([]net.IP, error) {
ipv6 = append(ipv6, ip) ipv6 = append(ipv6, ip)
} }
} }
// Local DNS ttl is 600
switch { switch {
case option.IPv4Enable && option.IPv6Enable: case option.IPv4Enable && option.IPv6Enable:
if len(parsedIPs) > 0 { if len(parsedIPs) > 0 {
return parsedIPs, nil return parsedIPs, 600, nil
} }
case option.IPv4Enable: case option.IPv4Enable:
if len(ipv4) > 0 { if len(ipv4) > 0 {
return ipv4, nil return ipv4, 600, nil
} }
case option.IPv6Enable: case option.IPv6Enable:
if len(ipv6) > 0 { if len(ipv6) > 0 {
return ipv6, nil return ipv6, 600, nil
} }
} }
return nil, dns.ErrEmptyResponse return nil, 0, dns.ErrEmptyResponse
} }
// New create a new dns.Client that queries localhost for DNS. // New create a new dns.Client that queries localhost for DNS.

View File

@@ -23,7 +23,7 @@ func (ctx *ResolvableContext) GetTargetIPs() []net.IP {
} }
if domain := ctx.GetTargetDomain(); len(domain) != 0 { if domain := ctx.GetTargetDomain(); len(domain) != 0 {
ips, err := ctx.dnsClient.LookupIP(domain, dns.IPOption{ ips, _, err := ctx.dnsClient.LookupIP(domain, dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: false, FakeEnable: false,

30
go.mod
View File

@@ -1,18 +1,18 @@
module github.com/xtls/xray-core module github.com/xtls/xray-core
go 1.23 go 1.24
require ( require (
github.com/OmarTariq612/goech v0.0.0-20240405204721-8e2e1dafd3a0 github.com/OmarTariq612/goech v0.0.0-20240405204721-8e2e1dafd3a0
github.com/cloudflare/circl v1.6.0 github.com/cloudflare/circl v1.6.0
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
github.com/golang/mock v1.7.0-rc.1 github.com/golang/mock v1.7.0-rc.1
github.com/google/go-cmp v0.6.0 github.com/google/go-cmp v0.7.0
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
github.com/miekg/dns v1.1.63 github.com/miekg/dns v1.1.64
github.com/pelletier/go-toml v1.9.5 github.com/pelletier/go-toml v1.9.5
github.com/pires/go-proxyproto v0.8.0 github.com/pires/go-proxyproto v0.8.0
github.com/quic-go/quic-go v0.49.0 github.com/quic-go/quic-go v0.50.1
github.com/refraction-networking/utls v1.6.7 github.com/refraction-networking/utls v1.6.7
github.com/sagernet/sing v0.5.1 github.com/sagernet/sing v0.5.1
github.com/sagernet/sing-shadowsocks v0.2.7 github.com/sagernet/sing-shadowsocks v0.2.7
@@ -22,16 +22,16 @@ require (
github.com/vishvananda/netlink v1.3.0 github.com/vishvananda/netlink v1.3.0
github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba go4.org/netipx v0.0.0-20231129151722-fdeea329fbba
golang.org/x/crypto v0.33.0 golang.org/x/crypto v0.36.0
golang.org/x/net v0.35.0 golang.org/x/net v0.38.0
golang.org/x/sync v0.11.0 golang.org/x/sync v0.12.0
golang.org/x/sys v0.30.0 golang.org/x/sys v0.31.0
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173
google.golang.org/grpc v1.70.0 google.golang.org/grpc v1.71.0
google.golang.org/protobuf v1.36.5 google.golang.org/protobuf v1.36.6
gvisor.dev/gvisor v0.0.0-20240320123526-dc6abceb7ff0 gvisor.dev/gvisor v0.0.0-20240320123526-dc6abceb7ff0
h12.io/socks v1.0.3 h12.io/socks v1.0.3
lukechampine.com/blake3 v1.3.0 lukechampine.com/blake3 v1.4.0
) )
require ( require (
@@ -50,12 +50,12 @@ require (
github.com/vishvananda/netns v0.0.4 // indirect github.com/vishvananda/netns v0.0.4 // indirect
go.uber.org/mock v0.5.0 // indirect go.uber.org/mock v0.5.0 // indirect
golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc // indirect golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc // indirect
golang.org/x/mod v0.21.0 // indirect golang.org/x/mod v0.23.0 // indirect
golang.org/x/text v0.22.0 // indirect golang.org/x/text v0.23.0 // indirect
golang.org/x/time v0.7.0 // indirect golang.org/x/time v0.7.0 // indirect
golang.org/x/tools v0.26.0 // indirect golang.org/x/tools v0.30.0 // indirect
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

78
go.sum
View File

@@ -24,8 +24,8 @@ github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU=
github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/pprof v0.0.0-20240528025155-186aa0362fba h1:ql1qNgCyOB7iAEk8JTNM+zJrgIbnyCKX/wdlyPufP5g= github.com/google/pprof v0.0.0-20240528025155-186aa0362fba h1:ql1qNgCyOB7iAEk8JTNM+zJrgIbnyCKX/wdlyPufP5g=
github.com/google/pprof v0.0.0-20240528025155-186aa0362fba/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo= github.com/google/pprof v0.0.0-20240528025155-186aa0362fba/go.mod h1:K1liHPHnj73Fdn/EKuT8nrFqBihUSKXoLYU0BuatOYo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -38,8 +38,8 @@ github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0N
github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/miekg/dns v1.1.63 h1:8M5aAw6OMZfFXTT7K5V0Eu5YiiL8l7nUAkyN6C9YwaY= github.com/miekg/dns v1.1.64 h1:wuZgD9wwCE6XMT05UU/mlSko71eRSXEAm2EbjQXLKnQ=
github.com/miekg/dns v1.1.63/go.mod h1:6NGHfjhpmr5lt3XPLuyfDJi5AXbNIPM9PY6H6sF1Nfs= github.com/miekg/dns v1.1.64/go.mod h1:Dzw9769uoKVaLuODMDZz9M6ynFU6Em65csPuoi8G0ck=
github.com/onsi/ginkgo/v2 v2.19.0 h1:9Cnnf7UHo57Hy3k6/m5k3dRfGTMXGvxhHFvkDTCTpvA= github.com/onsi/ginkgo/v2 v2.19.0 h1:9Cnnf7UHo57Hy3k6/m5k3dRfGTMXGvxhHFvkDTCTpvA=
github.com/onsi/ginkgo/v2 v2.19.0/go.mod h1:rlwLi9PilAFJ8jCg9UE1QP6VBpd6/xj3SRC0d6TU0To= github.com/onsi/ginkgo/v2 v2.19.0/go.mod h1:rlwLi9PilAFJ8jCg9UE1QP6VBpd6/xj3SRC0d6TU0To=
github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk= github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk=
@@ -54,8 +54,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI= github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg= github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
github.com/quic-go/quic-go v0.49.0 h1:w5iJHXwHxs1QxyBv1EHKuC50GX5to8mJAxvtnttJp94= github.com/quic-go/quic-go v0.50.1 h1:unsgjFIUqW8a2oopkY7YNONpV1gYND6Nt9hnt1PN94Q=
github.com/quic-go/quic-go v0.49.0/go.mod h1:s2wDnmCdooUQBmQfpUSTCYBl1/D4FcqbULMMkASvR6s= github.com/quic-go/quic-go v0.50.1/go.mod h1:Vim6OmUvlYdwBhXP9ZVrtGmCMWa3wEqhq3NgYrI8b4E=
github.com/refraction-networking/utls v1.6.7 h1:zVJ7sP1dJx/WtVuITug3qYUq034cDq9B2MR1K67ULZM= github.com/refraction-networking/utls v1.6.7 h1:zVJ7sP1dJx/WtVuITug3qYUq034cDq9B2MR1K67ULZM=
github.com/refraction-networking/utls v1.6.7/go.mod h1:BC3O4vQzye5hqpmDTWUqi4P5DDhzJfkV1tdqtawQIH0= github.com/refraction-networking/utls v1.6.7/go.mod h1:BC3O4vQzye5hqpmDTWUqi4P5DDhzJfkV1tdqtawQIH0=
github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 h1:f/FNXud6gA3MNr8meMVVGxhp+QBTqY91tM8HjEuMjGg= github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 h1:f/FNXud6gA3MNr8meMVVGxhp+QBTqY91tM8HjEuMjGg=
@@ -79,38 +79,40 @@ github.com/vishvananda/netns v0.0.4/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZla
github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d h1:+B97uD9uHLgAAulhigmys4BVwZZypzK7gPN3WtpgRJg= github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d h1:+B97uD9uHLgAAulhigmys4BVwZZypzK7gPN3WtpgRJg=
github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d/go.mod h1:dm4y/1QwzjGaK17ofi0Vs6NpKAHegZky8qk6J2JJZAE= github.com/xtls/reality v0.0.0-20240712055506-48f0b2d5ed6d/go.mod h1:dm4y/1QwzjGaK17ofi0Vs6NpKAHegZky8qk6J2JJZAE=
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
go.opentelemetry.io/otel/metric v1.32.0 h1:xV2umtmNcThh2/a/aCP+h64Xx5wsj8qqnkYZktzNa0M= go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY=
go.opentelemetry.io/otel/metric v1.32.0/go.mod h1:jH7CIbbK6SH2V2wE16W05BHCtIDzauciCRLoc/SyMv8= go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI=
go.opentelemetry.io/otel/sdk v1.32.0 h1:RNxepc9vK59A8XsgZQouW8ue8Gkb4jpWtJm9ge5lEG4= go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ=
go.opentelemetry.io/otel/sdk v1.32.0/go.mod h1:LqgegDBjKMmb2GC6/PrTnteJG39I8/vJCAP9LlJXEjU= go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE=
go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU= go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A=
go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ= go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU=
go.opentelemetry.io/otel/trace v1.32.0 h1:WIC9mYrXf8TmY/EXuULKc8hR17vE+Hjv2cssQDe03fM= go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk=
go.opentelemetry.io/otel/trace v1.32.0/go.mod h1:+i4rkvCraA+tG6AzwloGaCtkx53Fa+L+V8e9a7YvhT8= go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w=
go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k=
go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE=
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU= go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM= go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M= go4.org/netipx v0.0.0-20231129151722-fdeea329fbba h1:0b9z3AuHCjxk0x/opv64kcgZLBseWJUpBw5I82+2U4M=
go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y= go4.org/netipx v0.0.0-20231129151722-fdeea329fbba/go.mod h1:PLyyIXexvUFg3Owu6p/WfdlivPbZJsZdgWZlrGope/Y=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc h1:O9NuF4s+E/PvMIy+9IUZB9znFwUIXEWSstNjek6VpVg= golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc h1:O9NuF4s+E/PvMIy+9IUZB9znFwUIXEWSstNjek6VpVg=
golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc= golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0= golang.org/x/mod v0.23.0 h1:Zb7khfcRGKk+kqfxFaP5tZqCnDZMjC5VtUBs87Hr6QM=
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/mod v0.23.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -119,21 +121,21 @@ golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ= golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ=
golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.26.0 h1:v/60pFQmzmT9ExmjDv2gGIfi3OqfKoEP6I5+umXlbnQ= golang.org/x/tools v0.30.0 h1:BgcpHewrV5AUp2G9MebG4XPFI1E2W41zU1SaqVA9vJY=
golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0= golang.org/x/tools v0.30.0/go.mod h1:c347cR/OJfw5TI+GfX7RUPNMdDRRbjvYTS0jPyvsVtY=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -141,12 +143,12 @@ golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeu
golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 h1:/jFs0duh4rdb8uIfPMv78iAJGcPKDeqAFnaLBropIC4= golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173 h1:/jFs0duh4rdb8uIfPMv78iAJGcPKDeqAFnaLBropIC4=
golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173/go.mod h1:tkCQ4FQXmpAgYVh++1cq16/dH4QJtmvpRv19DWGAHSA= golang.zx2c4.com/wireguard v0.0.0-20231211153847-12269c276173/go.mod h1:tkCQ4FQXmpAgYVh++1cq16/dH4QJtmvpRv19DWGAHSA=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a h1:hgh8P4EuoxpsuKMXX/To36nOFD7vixReXgn8lPGnt+o= google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f h1:OxYkA3wjPsZyBylwymxSHa7ViiW1Sml4ToBrncvFehI=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU= google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50=
google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ= google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg=
google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw= google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec=
google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
@@ -160,5 +162,5 @@ gvisor.dev/gvisor v0.0.0-20240320123526-dc6abceb7ff0 h1:P+U/06iIKPQ3DLcg+zBfSCia
gvisor.dev/gvisor v0.0.0-20240320123526-dc6abceb7ff0/go.mod h1:NQHVAzMwvZ+Qe3ElSiHmq9RUm1MdNHpUZ52fiEqvn+0= gvisor.dev/gvisor v0.0.0-20240320123526-dc6abceb7ff0/go.mod h1:NQHVAzMwvZ+Qe3ElSiHmq9RUm1MdNHpUZ52fiEqvn+0=
h12.io/socks v1.0.3 h1:Ka3qaQewws4j4/eDQnOdpr4wXsC//dXtWvftlIcCQUo= h12.io/socks v1.0.3 h1:Ka3qaQewws4j4/eDQnOdpr4wXsC//dXtWvftlIcCQUo=
h12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck= h12.io/socks v1.0.3/go.mod h1:AIhxy1jOId/XCz9BO+EIgNL2rQiPTBNnOfnVnQ+3Eck=
lukechampine.com/blake3 v1.3.0 h1:sJ3XhFINmHSrYCgl958hscfIa3bw8x4DqMP3u1YvoYE= lukechampine.com/blake3 v1.4.0 h1:xDbKOZCVbnZsfzM6mHSYcGRHZ3YrLDzqz8XnV4uaD5w=
lukechampine.com/blake3 v1.3.0/go.mod h1:0OFRp7fBtAylGVCO40o87sbupkyIGgbpv1+M1k1LM6k= lukechampine.com/blake3 v1.4.0/go.mod h1:MQJNQCTnR+kwOP/JEZSxj3MaQjp80FOFSNMMHXcSeX0=

View File

@@ -12,13 +12,17 @@ import (
) )
type NameServerConfig struct { type NameServerConfig struct {
Address *Address `json:"address"` Address *Address `json:"address"`
ClientIP *Address `json:"clientIp"` ClientIP *Address `json:"clientIp"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
SkipFallback bool `json:"skipFallback"` SkipFallback bool `json:"skipFallback"`
Domains []string `json:"domains"` Domains []string `json:"domains"`
ExpectIPs StringList `json:"expectIps"` ExpectedIPs StringList `json:"expectedIPs"`
QueryStrategy string `json:"queryStrategy"` ExpectIPs StringList `json:"expectIPs"`
QueryStrategy string `json:"queryStrategy"`
AllowUnexpectedIPs bool `json:"allowUnexpectedIps"`
Tag string `json:"tag"`
TimeoutMs uint64 `json:"timeoutMs"`
} }
func (c *NameServerConfig) UnmarshalJSON(data []byte) error { func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
@@ -29,13 +33,17 @@ func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
} }
var advanced struct { var advanced struct {
Address *Address `json:"address"` Address *Address `json:"address"`
ClientIP *Address `json:"clientIp"` ClientIP *Address `json:"clientIp"`
Port uint16 `json:"port"` Port uint16 `json:"port"`
SkipFallback bool `json:"skipFallback"` SkipFallback bool `json:"skipFallback"`
Domains []string `json:"domains"` Domains []string `json:"domains"`
ExpectIPs StringList `json:"expectIps"` ExpectedIPs StringList `json:"expectedIPs"`
QueryStrategy string `json:"queryStrategy"` ExpectIPs StringList `json:"expectIPs"`
QueryStrategy string `json:"queryStrategy"`
AllowUnexpectedIPs bool `json:"allowUnexpectedIps"`
Tag string `json:"tag"`
TimeoutMs uint64 `json:"timeoutMs"`
} }
if err := json.Unmarshal(data, &advanced); err == nil { if err := json.Unmarshal(data, &advanced); err == nil {
c.Address = advanced.Address c.Address = advanced.Address
@@ -43,8 +51,12 @@ func (c *NameServerConfig) UnmarshalJSON(data []byte) error {
c.Port = advanced.Port c.Port = advanced.Port
c.SkipFallback = advanced.SkipFallback c.SkipFallback = advanced.SkipFallback
c.Domains = advanced.Domains c.Domains = advanced.Domains
c.ExpectedIPs = advanced.ExpectedIPs
c.ExpectIPs = advanced.ExpectIPs c.ExpectIPs = advanced.ExpectIPs
c.QueryStrategy = advanced.QueryStrategy c.QueryStrategy = advanced.QueryStrategy
c.AllowUnexpectedIPs = advanced.AllowUnexpectedIPs
c.Tag = advanced.Tag
c.TimeoutMs = advanced.TimeoutMs
return nil return nil
} }
@@ -92,9 +104,13 @@ func (c *NameServerConfig) Build() (*dns.NameServer, error) {
}) })
} }
geoipList, err := ToCidrList(c.ExpectIPs) var expectedIPs = c.ExpectedIPs
if len(expectedIPs) == 0 {
expectedIPs = c.ExpectIPs
}
geoipList, err := ToCidrList(expectedIPs)
if err != nil { if err != nil {
return nil, errors.New("invalid IP rule: ", c.ExpectIPs).Base(err) return nil, errors.New("invalid IP rule: ", expectedIPs).Base(err)
} }
var myClientIP []byte var myClientIP []byte
@@ -111,12 +127,15 @@ func (c *NameServerConfig) Build() (*dns.NameServer, error) {
Address: c.Address.Build(), Address: c.Address.Build(),
Port: uint32(c.Port), Port: uint32(c.Port),
}, },
ClientIp: myClientIP, ClientIp: myClientIP,
SkipFallback: c.SkipFallback, SkipFallback: c.SkipFallback,
PrioritizedDomain: domains, PrioritizedDomain: domains,
Geoip: geoipList, Geoip: geoipList,
OriginalRules: originalRules, OriginalRules: originalRules,
QueryStrategy: resolveQueryStrategy(c.QueryStrategy), QueryStrategy: resolveQueryStrategy(c.QueryStrategy),
AllowUnexpectedIPs: c.AllowUnexpectedIPs,
Tag: c.Tag,
TimeoutMs: c.TimeoutMs,
}, nil }, nil
} }

View File

@@ -334,7 +334,7 @@ func (c *SplitHTTPConfig) Build() (proto.Message, error) {
func readFileOrString(f string, s []string) ([]byte, error) { func readFileOrString(f string, s []string) ([]byte, error) {
if len(f) > 0 { if len(f) > 0 {
return filesystem.ReadFile(f) return filesystem.ReadCert(f)
} }
if len(s) > 0 { if len(s) > 0 {
return []byte(strings.Join(s, "\n")), nil return []byte(strings.Join(s, "\n")), nil
@@ -502,6 +502,7 @@ type REALITYConfig struct {
Fingerprint string `json:"fingerprint"` Fingerprint string `json:"fingerprint"`
ServerName string `json:"serverName"` ServerName string `json:"serverName"`
Password string `json:"password"`
PublicKey string `json:"publicKey"` PublicKey string `json:"publicKey"`
ShortId string `json:"shortId"` ShortId string `json:"shortId"`
SpiderX string `json:"spiderX"` SpiderX string `json:"spiderX"`
@@ -610,11 +611,14 @@ func (c *REALITYConfig) Build() (proto.Message, error) {
if len(c.ServerNames) != 0 { if len(c.ServerNames) != 0 {
return nil, errors.New(`non-empty "serverNames", please use "serverName" instead`) return nil, errors.New(`non-empty "serverNames", please use "serverName" instead`)
} }
if c.Password != "" {
c.PublicKey = c.Password
}
if c.PublicKey == "" { if c.PublicKey == "" {
return nil, errors.New(`empty "publicKey"`) return nil, errors.New(`empty "password"`)
} }
if config.PublicKey, err = base64.RawURLEncoding.DecodeString(c.PublicKey); err != nil || len(config.PublicKey) != 32 { if config.PublicKey, err = base64.RawURLEncoding.DecodeString(c.PublicKey); err != nil || len(config.PublicKey) != 32 {
return nil, errors.New(`invalid "publicKey": `, c.PublicKey) return nil, errors.New(`invalid "password": `, c.PublicKey)
} }
if len(c.ShortIds) != 0 { if len(c.ShortIds) != 0 {
return nil, errors.New(`non-empty "shortIds", please use "shortId" instead`) return nil, errors.New(`non-empty "shortIds", please use "shortId" instead`)
@@ -687,10 +691,11 @@ func (p TransportProtocol) Build() (string, error) {
} }
type CustomSockoptConfig struct { type CustomSockoptConfig struct {
Level string `json:"level"` Network string `json:"network"`
Opt string `json:"opt"` Level string `json:"level"`
Value string `json:"value"` Opt string `json:"opt"`
Type string `json:"type"` Value string `json:"value"`
Type string `json:"type"`
} }
type SocketConfig struct { type SocketConfig struct {
@@ -711,6 +716,7 @@ type SocketConfig struct {
Interface string `json:"interface"` Interface string `json:"interface"`
TcpMptcp bool `json:"tcpMptcp"` TcpMptcp bool `json:"tcpMptcp"`
CustomSockopt []*CustomSockoptConfig `json:"customSockopt"` CustomSockopt []*CustomSockoptConfig `json:"customSockopt"`
AddressPortStrategy string `json:"addressPortStrategy"`
} }
// Build implements Buildable. // Build implements Buildable.
@@ -772,14 +778,35 @@ func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
for _, copt := range c.CustomSockopt { for _, copt := range c.CustomSockopt {
customSockopt := &internet.CustomSockopt{ customSockopt := &internet.CustomSockopt{
Level: copt.Level, Network: copt.Network,
Opt: copt.Opt, Level: copt.Level,
Value: copt.Value, Opt: copt.Opt,
Type: copt.Type, Value: copt.Value,
Type: copt.Type,
} }
customSockopts = append(customSockopts, customSockopt) customSockopts = append(customSockopts, customSockopt)
} }
addressPortStrategy := internet.AddressPortStrategy_None
switch strings.ToLower(c.AddressPortStrategy) {
case "none", "":
addressPortStrategy = internet.AddressPortStrategy_None
case "srvportonly":
addressPortStrategy = internet.AddressPortStrategy_SrvPortOnly
case "srvaddressonly":
addressPortStrategy = internet.AddressPortStrategy_SrvAddressOnly
case "srvportandaddress":
addressPortStrategy = internet.AddressPortStrategy_SrvPortAndAddress
case "txtportonly":
addressPortStrategy = internet.AddressPortStrategy_TxtPortOnly
case "txtaddressonly":
addressPortStrategy = internet.AddressPortStrategy_TxtAddressOnly
case "txtportandaddress":
addressPortStrategy = internet.AddressPortStrategy_TxtPortAndAddress
default:
return nil, errors.New("unsupported address and port strategy: ", c.AddressPortStrategy)
}
return &internet.SocketConfig{ return &internet.SocketConfig{
Mark: c.Mark, Mark: c.Mark,
Tfo: tfo, Tfo: tfo,
@@ -798,6 +825,7 @@ func (c *SocketConfig) Build() (*internet.SocketConfig, error) {
Interface: c.Interface, Interface: c.Interface,
TcpMptcp: c.TcpMptcp, TcpMptcp: c.TcpMptcp,
CustomSockopt: customSockopts, CustomSockopt: customSockopts,
AddressPortStrategy: addressPortStrategy,
}, nil }, nil
} }

View File

@@ -67,7 +67,7 @@ func (c *WireGuardConfig) Build() (proto.Message, error) {
var err error var err error
config.SecretKey, err = ParseWireGuardKey(c.SecretKey) config.SecretKey, err = ParseWireGuardKey(c.SecretKey)
if err != nil { if err != nil {
return nil, err return nil, errors.New("invalid WireGuard secret key: %w", err)
} }
if c.Address == nil { if c.Address == nil {
@@ -126,6 +126,10 @@ func (c *WireGuardConfig) Build() (proto.Message, error) {
func ParseWireGuardKey(str string) (string, error) { func ParseWireGuardKey(str string) (string, error) {
var err error var err error
if str == "" {
return "", errors.New("key must not be empty")
}
if len(str)%2 == 0 { if len(str)%2 == 0 {
_, err = hex.DecodeString(str) _, err = hex.DecodeString(str)
if err == nil { if err == nil {

View File

@@ -241,14 +241,14 @@ func (c *InboundDetourConfig) Build() (*core.InboundHandlerConfig, error) {
} }
rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol) rawConfig, err := inboundConfigLoader.LoadWithID(settings, c.Protocol)
if err != nil { if err != nil {
return nil, errors.New("failed to load inbound detour config.").Base(err) return nil, errors.New("failed to load inbound detour config for protocol ", c.Protocol).Base(err)
} }
if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok { if dokodemoConfig, ok := rawConfig.(*DokodemoConfig); ok {
receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect receiverSettings.ReceiveOriginalDestination = dokodemoConfig.Redirect
} }
ts, err := rawConfig.(Buildable).Build() ts, err := rawConfig.(Buildable).Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build inbound handler for protocol ", c.Protocol).Base(err)
} }
return &core.InboundHandlerConfig{ return &core.InboundHandlerConfig{
@@ -292,7 +292,9 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
senderSettings.ViaCidr = strings.Split(*c.SendThrough, "/")[1] senderSettings.ViaCidr = strings.Split(*c.SendThrough, "/")[1]
} else { } else {
if address.Family().IsDomain() { if address.Family().IsDomain() {
return nil, errors.New("unable to send through: " + address.String()) if address.Address.Domain() != "origin" {
return nil, errors.New("unable to send through: " + address.String())
}
} }
} }
senderSettings.Via = address.Build() senderSettings.Via = address.Build()
@@ -301,7 +303,7 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
if c.StreamSetting != nil { if c.StreamSetting != nil {
ss, err := c.StreamSetting.Build() ss, err := c.StreamSetting.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build stream settings for outbound detour").Base(err)
} }
senderSettings.StreamSettings = ss senderSettings.StreamSettings = ss
} }
@@ -309,7 +311,7 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
if c.ProxySettings != nil { if c.ProxySettings != nil {
ps, err := c.ProxySettings.Build() ps, err := c.ProxySettings.Build()
if err != nil { if err != nil {
return nil, errors.New("invalid outbound detour proxy settings.").Base(err) return nil, errors.New("invalid outbound detour proxy settings").Base(err)
} }
if ps.TransportLayerProxy { if ps.TransportLayerProxy {
if senderSettings.StreamSettings != nil { if senderSettings.StreamSettings != nil {
@@ -329,7 +331,7 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
if c.MuxSettings != nil { if c.MuxSettings != nil {
ms, err := c.MuxSettings.Build() ms, err := c.MuxSettings.Build()
if err != nil { if err != nil {
return nil, errors.New("failed to build Mux config.").Base(err) return nil, errors.New("failed to build Mux config").Base(err)
} }
senderSettings.MultiplexSettings = ms senderSettings.MultiplexSettings = ms
} }
@@ -340,11 +342,11 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
} }
rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol) rawConfig, err := outboundConfigLoader.LoadWithID(settings, c.Protocol)
if err != nil { if err != nil {
return nil, errors.New("failed to parse to outbound detour config.").Base(err) return nil, errors.New("failed to load outbound detour config for protocol ", c.Protocol).Base(err)
} }
ts, err := rawConfig.(Buildable).Build() ts, err := rawConfig.(Buildable).Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
} }
return &core.OutboundHandlerConfig{ return &core.OutboundHandlerConfig{
@@ -488,7 +490,7 @@ func (c *Config) Override(o *Config, fn string) {
// Build implements Buildable. // Build implements Buildable.
func (c *Config) Build() (*core.Config, error) { func (c *Config) Build() (*core.Config, error) {
if err := PostProcessConfigureFile(c); err != nil { if err := PostProcessConfigureFile(c); err != nil {
return nil, err return nil, errors.New("failed to post-process configuration file").Base(err)
} }
config := &core.Config{ config := &core.Config{
@@ -502,21 +504,21 @@ func (c *Config) Build() (*core.Config, error) {
if c.API != nil { if c.API != nil {
apiConf, err := c.API.Build() apiConf, err := c.API.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build API configuration").Base(err)
} }
config.App = append(config.App, serial.ToTypedMessage(apiConf)) config.App = append(config.App, serial.ToTypedMessage(apiConf))
} }
if c.Metrics != nil { if c.Metrics != nil {
metricsConf, err := c.Metrics.Build() metricsConf, err := c.Metrics.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build metrics configuration").Base(err)
} }
config.App = append(config.App, serial.ToTypedMessage(metricsConf)) config.App = append(config.App, serial.ToTypedMessage(metricsConf))
} }
if c.Stats != nil { if c.Stats != nil {
statsConf, err := c.Stats.Build() statsConf, err := c.Stats.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build stats configuration").Base(err)
} }
config.App = append(config.App, serial.ToTypedMessage(statsConf)) config.App = append(config.App, serial.ToTypedMessage(statsConf))
} }
@@ -534,7 +536,7 @@ func (c *Config) Build() (*core.Config, error) {
if c.RouterConfig != nil { if c.RouterConfig != nil {
routerConfig, err := c.RouterConfig.Build() routerConfig, err := c.RouterConfig.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build routing configuration").Base(err)
} }
config.App = append(config.App, serial.ToTypedMessage(routerConfig)) config.App = append(config.App, serial.ToTypedMessage(routerConfig))
} }
@@ -542,7 +544,7 @@ func (c *Config) Build() (*core.Config, error) {
if c.DNSConfig != nil { if c.DNSConfig != nil {
dnsApp, err := c.DNSConfig.Build() dnsApp, err := c.DNSConfig.Build()
if err != nil { if err != nil {
return nil, errors.New("failed to parse DNS config").Base(err) return nil, errors.New("failed to build DNS configuration").Base(err)
} }
config.App = append(config.App, serial.ToTypedMessage(dnsApp)) config.App = append(config.App, serial.ToTypedMessage(dnsApp))
} }
@@ -550,7 +552,7 @@ func (c *Config) Build() (*core.Config, error) {
if c.Policy != nil { if c.Policy != nil {
pc, err := c.Policy.Build() pc, err := c.Policy.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build policy configuration").Base(err)
} }
config.App = append(config.App, serial.ToTypedMessage(pc)) config.App = append(config.App, serial.ToTypedMessage(pc))
} }
@@ -558,7 +560,7 @@ func (c *Config) Build() (*core.Config, error) {
if c.Reverse != nil { if c.Reverse != nil {
r, err := c.Reverse.Build() r, err := c.Reverse.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build reverse configuration").Base(err)
} }
config.App = append(config.App, serial.ToTypedMessage(r)) config.App = append(config.App, serial.ToTypedMessage(r))
} }
@@ -566,7 +568,7 @@ func (c *Config) Build() (*core.Config, error) {
if c.FakeDNS != nil { if c.FakeDNS != nil {
r, err := c.FakeDNS.Build() r, err := c.FakeDNS.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build fake DNS configuration").Base(err)
} }
config.App = append([]*serial.TypedMessage{serial.ToTypedMessage(r)}, config.App...) config.App = append([]*serial.TypedMessage{serial.ToTypedMessage(r)}, config.App...)
} }
@@ -574,7 +576,7 @@ func (c *Config) Build() (*core.Config, error) {
if c.Observatory != nil { if c.Observatory != nil {
r, err := c.Observatory.Build() r, err := c.Observatory.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build observatory configuration").Base(err)
} }
config.App = append(config.App, serial.ToTypedMessage(r)) config.App = append(config.App, serial.ToTypedMessage(r))
} }
@@ -582,7 +584,7 @@ func (c *Config) Build() (*core.Config, error) {
if c.BurstObservatory != nil { if c.BurstObservatory != nil {
r, err := c.BurstObservatory.Build() r, err := c.BurstObservatory.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build burst observatory configuration").Base(err)
} }
config.App = append(config.App, serial.ToTypedMessage(r)) config.App = append(config.App, serial.ToTypedMessage(r))
} }
@@ -600,7 +602,7 @@ func (c *Config) Build() (*core.Config, error) {
for _, rawInboundConfig := range inbounds { for _, rawInboundConfig := range inbounds {
ic, err := rawInboundConfig.Build() ic, err := rawInboundConfig.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build inbound config with tag ", rawInboundConfig.Tag).Base(err)
} }
config.Inbound = append(config.Inbound, ic) config.Inbound = append(config.Inbound, ic)
} }
@@ -614,7 +616,7 @@ func (c *Config) Build() (*core.Config, error) {
for _, rawOutboundConfig := range outbounds { for _, rawOutboundConfig := range outbounds {
oc, err := rawOutboundConfig.Build() oc, err := rawOutboundConfig.Build()
if err != nil { if err != nil {
return nil, err return nil, errors.New("failed to build outbound config with tag ", rawOutboundConfig.Tag).Base(err)
} }
config.Outbound = append(config.Outbound, oc) config.Outbound = append(config.Outbound, oc)
} }

View File

@@ -89,12 +89,11 @@ func whichProtoc(suffix, targetedVersion string) (string, error) {
path, err := exec.LookPath(protoc) path, err := exec.LookPath(protoc)
if err != nil { if err != nil {
errStr := fmt.Sprintf(` return "", fmt.Errorf(`
Command "%s" not found. Command "%s" not found.
Make sure that %s is in your system path or current path. Make sure that %s is in your system path or current path.
Download %s v%s or later from https://github.com/protocolbuffers/protobuf/releases Download %s v%s or later from https://github.com/protocolbuffers/protobuf/releases
`, protoc, protoc, protoc, targetedVersion) `, protoc, protoc, protoc, targetedVersion)
return "", fmt.Errorf(errStr)
} }
return path, nil return path, nil
} }

View File

@@ -50,17 +50,17 @@ func executeTypedMessageToJson(cmd *base.Command, args []string) {
reader, err := confloader.LoadConfig(cmd.Flag.Arg(0)) reader, err := confloader.LoadConfig(cmd.Flag.Arg(0))
if err != nil { if err != nil {
base.Fatalf(err.Error()) base.Fatalf("failed to load config: %s", err)
} }
b, err := io.ReadAll(reader) b, err := io.ReadAll(reader)
if err != nil { if err != nil {
base.Fatalf(err.Error()) base.Fatalf("failed to read config: %s", err)
} }
tm := cserial.TypedMessage{} tm := cserial.TypedMessage{}
if err = json.Unmarshal(b, &tm); err != nil { if err = json.Unmarshal(b, &tm); err != nil {
base.Fatalf(err.Error()) base.Fatalf("failed to unmarshal config: %s", err)
} }
if j, ok := creflect.MarshalToJson(&tm, injectTypeInfo); ok { if j, ok := creflect.MarshalToJson(&tm, injectTypeInfo); ok {

View File

@@ -53,12 +53,12 @@ func executeConvertConfigsToProtobuf(cmd *base.Command, args []string) {
} }
if len(unnamedArgs) < 1 { if len(unnamedArgs) < 1 {
base.Fatalf("empty config list") base.Fatalf("invalid config list length: %d", len(unnamedArgs))
} }
pbConfig, err := core.LoadConfig("auto", unnamedArgs) pbConfig, err := core.LoadConfig("auto", unnamedArgs)
if err != nil { if err != nil {
base.Fatalf(err.Error()) base.Fatalf("failed to load config: %s", err)
} }
if optDump { if optDump {

View File

@@ -236,17 +236,18 @@ func (h *Handler) handleIPQuery(id uint16, qType dnsmessage.Type, domain string,
var ips []net.IP var ips []net.IP
var err error var err error
var ttl uint32 = 600 var ttl4 uint32
var ttl6 uint32
switch qType { switch qType {
case dnsmessage.TypeA: case dnsmessage.TypeA:
ips, err = h.client.LookupIP(domain, dns.IPOption{ ips, ttl4, err = h.client.LookupIP(domain, dns.IPOption{
IPv4Enable: true, IPv4Enable: true,
IPv6Enable: false, IPv6Enable: false,
FakeEnable: true, FakeEnable: true,
}) })
case dnsmessage.TypeAAAA: case dnsmessage.TypeAAAA:
ips, err = h.client.LookupIP(domain, dns.IPOption{ ips, ttl6, err = h.client.LookupIP(domain, dns.IPOption{
IPv4Enable: false, IPv4Enable: false,
IPv6Enable: true, IPv6Enable: true,
FakeEnable: true, FakeEnable: true,
@@ -259,10 +260,6 @@ func (h *Handler) handleIPQuery(id uint16, qType dnsmessage.Type, domain string,
return return
} }
if fkr0, ok := h.fdns.(dns.FakeDNSEngineRev0); ok && len(ips) > 0 && fkr0.IsIPInIPPool(net.IPAddress(ips[0])) {
ttl = 1
}
switch qType { switch qType {
case dnsmessage.TypeA: case dnsmessage.TypeA:
for i, ip := range ips { for i, ip := range ips {
@@ -293,16 +290,17 @@ func (h *Handler) handleIPQuery(id uint16, qType dnsmessage.Type, domain string,
})) }))
common.Must(builder.StartAnswers()) common.Must(builder.StartAnswers())
rHeader := dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(domain), Class: dnsmessage.ClassINET, TTL: ttl} rHeader4 := dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(domain), Class: dnsmessage.ClassINET, TTL: ttl4}
rHeader6 := dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(domain), Class: dnsmessage.ClassINET, TTL: ttl6}
for _, ip := range ips { for _, ip := range ips {
if len(ip) == net.IPv4len { if len(ip) == net.IPv4len {
var r dnsmessage.AResource var r dnsmessage.AResource
copy(r.A[:], ip) copy(r.A[:], ip)
common.Must(builder.AResource(rHeader, r)) common.Must(builder.AResource(rHeader4, r))
} else { } else {
var r dnsmessage.AAAAResource var r dnsmessage.AAAAResource
copy(r.AAAA[:], ip) copy(r.AAAA[:], ip)
common.Must(builder.AAAAResource(rHeader, r)) common.Must(builder.AAAAResource(rHeader6, r))
} }
} }
msgBytes, err := builder.Finish() msgBytes, err := builder.Finish()

View File

@@ -4,12 +4,12 @@ import (
"context" "context"
"crypto/rand" "crypto/rand"
"io" "io"
"math/big"
"time" "time"
"github.com/pires/go-proxyproto" "github.com/pires/go-proxyproto"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/buf" "github.com/xtls/xray-core/common/buf"
"github.com/xtls/xray-core/common/crypto"
"github.com/xtls/xray-core/common/dice" "github.com/xtls/xray-core/common/dice"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
@@ -71,13 +71,13 @@ func (h *Handler) policy() policy.Session {
} }
func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address { func (h *Handler) resolveIP(ctx context.Context, domain string, localAddr net.Address) net.Address {
ips, err := h.dns.LookupIP(domain, dns.IPOption{ ips, _, err := h.dns.LookupIP(domain, dns.IPOption{
IPv4Enable: (localAddr == nil || localAddr.Family().IsIPv4()) && h.config.preferIP4(), IPv4Enable: (localAddr == nil || localAddr.Family().IsIPv4()) && h.config.preferIP4(),
IPv6Enable: (localAddr == nil || localAddr.Family().IsIPv6()) && h.config.preferIP6(), IPv6Enable: (localAddr == nil || localAddr.Family().IsIPv6()) && h.config.preferIP6(),
}) })
{ // Resolve fallback { // Resolve fallback
if (len(ips) == 0 || err != nil) && h.config.hasFallback() && localAddr == nil { if (len(ips) == 0 || err != nil) && h.config.hasFallback() && localAddr == nil {
ips, err = h.dns.LookupIP(domain, dns.IPOption{ ips, _, err = h.dns.LookupIP(domain, dns.IPOption{
IPv4Enable: h.config.fallbackIP4(), IPv4Enable: h.config.fallbackIP4(),
IPv6Enable: h.config.fallbackIP6(), IPv6Enable: h.config.fallbackIP6(),
}) })
@@ -414,7 +414,7 @@ func (w *NoisePacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
noise = n.Packet noise = n.Packet
} else { } else {
//Random noise //Random noise
noise, err = GenerateRandomBytes(randBetween(int64(n.LengthMin), noise, err = GenerateRandomBytes(crypto.RandBetween(int64(n.LengthMin),
int64(n.LengthMax))) int64(n.LengthMax)))
} }
if err != nil { if err != nil {
@@ -423,7 +423,7 @@ func (w *NoisePacketWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
w.Writer.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(noise)}) w.Writer.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(noise)})
if n.DelayMin != 0 || n.DelayMax != 0 { if n.DelayMin != 0 || n.DelayMax != 0 {
time.Sleep(time.Duration(randBetween(int64(n.DelayMin), int64(n.DelayMax))) * time.Millisecond) time.Sleep(time.Duration(crypto.RandBetween(int64(n.DelayMin), int64(n.DelayMax))) * time.Millisecond)
} }
} }
@@ -452,7 +452,7 @@ func (f *FragmentWriter) Write(b []byte) (int, error) {
buf := make([]byte, 1024) buf := make([]byte, 1024)
var hello []byte var hello []byte
for from := 0; ; { for from := 0; ; {
to := from + int(randBetween(int64(f.fragment.LengthMin), int64(f.fragment.LengthMax))) to := from + int(crypto.RandBetween(int64(f.fragment.LengthMin), int64(f.fragment.LengthMax)))
if to > len(data) { if to > len(data) {
to = len(data) to = len(data)
} }
@@ -466,7 +466,7 @@ func (f *FragmentWriter) Write(b []byte) (int, error) {
hello = append(hello, buf[:5+l]...) hello = append(hello, buf[:5+l]...)
} else { } else {
_, err := f.writer.Write(buf[:5+l]) _, err := f.writer.Write(buf[:5+l])
time.Sleep(time.Duration(randBetween(int64(f.fragment.IntervalMin), int64(f.fragment.IntervalMax))) * time.Millisecond) time.Sleep(time.Duration(crypto.RandBetween(int64(f.fragment.IntervalMin), int64(f.fragment.IntervalMax))) * time.Millisecond)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@@ -493,13 +493,13 @@ func (f *FragmentWriter) Write(b []byte) (int, error) {
return f.writer.Write(b) return f.writer.Write(b)
} }
for from := 0; ; { for from := 0; ; {
to := from + int(randBetween(int64(f.fragment.LengthMin), int64(f.fragment.LengthMax))) to := from + int(crypto.RandBetween(int64(f.fragment.LengthMin), int64(f.fragment.LengthMax)))
if to > len(b) { if to > len(b) {
to = len(b) to = len(b)
} }
n, err := f.writer.Write(b[from:to]) n, err := f.writer.Write(b[from:to])
from += n from += n
time.Sleep(time.Duration(randBetween(int64(f.fragment.IntervalMin), int64(f.fragment.IntervalMax))) * time.Millisecond) time.Sleep(time.Duration(crypto.RandBetween(int64(f.fragment.IntervalMin), int64(f.fragment.IntervalMax))) * time.Millisecond)
if err != nil { if err != nil {
return from, err return from, err
} }
@@ -509,14 +509,6 @@ func (f *FragmentWriter) Write(b []byte) (int, error) {
} }
} }
// stolen from github.com/xtls/xray-core/transport/internet/reality
func randBetween(left int64, right int64) int64 {
if left == right {
return left
}
bigInt, _ := rand.Int(rand.Reader, big.NewInt(right-left))
return left + bigInt.Int64()
}
func GenerateRandomBytes(n int64) ([]byte, error) { func GenerateRandomBytes(n int64) ([]byte, error) {
b := make([]byte, n) b := make([]byte, n)
_, err := rand.Read(b) _, err := rand.Read(b)

View File

@@ -294,7 +294,7 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri
responseDone := func() error { responseDone := func() error {
responseReader := bufio.NewReaderSize(&buf.BufferedReader{Reader: link.Reader}, buf.Size) responseReader := bufio.NewReaderSize(&buf.BufferedReader{Reader: link.Reader}, buf.Size)
response, err := http.ReadResponse(responseReader, request) response, err := readResponseAndHandle100Continue(responseReader, request, writer)
if err == nil { if err == nil {
http_proto.RemoveHopByHopHeaders(response.Header) http_proto.RemoveHopByHopHeaders(response.Header)
if response.ContentLength >= 0 { if response.ContentLength >= 0 {
@@ -338,6 +338,38 @@ func (s *Server) handlePlainHTTP(ctx context.Context, request *http.Request, wri
return result return result
} }
// Sometimes, server might send 1xx response to client
// it should not be processed by http proxy handler, just forward it to client
func readResponseAndHandle100Continue(r *bufio.Reader, req *http.Request, writer io.Writer) (*http.Response, error) {
// have a little look of response
peekBytes, err := r.Peek(56)
if err == nil || err == bufio.ErrBufferFull {
str := string(peekBytes)
ResponseLine := strings.Split(str, "\r\n")[0]
_, status, _ := strings.Cut(ResponseLine, " ")
// only handle 1xx response
if strings.HasPrefix(status, "1") {
ResponseHeader1xx := []byte{}
// read until \r\n\r\n (end of http response header)
for {
data, err := r.ReadSlice('\n')
if err != nil {
return nil, errors.New("failed to read http 1xx response").Base(err)
}
ResponseHeader1xx = append(ResponseHeader1xx, data...)
if bytes.Equal(ResponseHeader1xx[len(ResponseHeader1xx)-4:], []byte{'\r', '\n', '\r', '\n'}) {
break
}
if len(ResponseHeader1xx) > 1024 {
return nil, errors.New("too big http 1xx response")
}
}
writer.Write(ResponseHeader1xx)
}
}
return http.ReadResponse(r, req)
}
func init() { func init() {
common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) { common.Must(common.RegisterConfig((*ServerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return NewServer(ctx, config.(*ServerConfig)) return NewServer(ctx, config.(*ServerConfig))

View File

@@ -547,8 +547,8 @@ func UnwrapRawConn(conn net.Conn) (net.Conn, stats.Counter, stats.Counter) {
conn = pc.Raw() conn = pc.Raw()
// 8192 > 4096, there is no need to process pc's bufReader // 8192 > 4096, there is no need to process pc's bufReader
} }
if uc, ok := conn.(*internet.UDSWrapperConn); ok { if uc, ok := conn.(*internet.UnixConnWrapper); ok {
conn = uc.Conn conn = uc.UnixConn
} }
} }
return conn, readCounter, writerCounter return conn, readCounter, writerCounter

View File

@@ -54,7 +54,7 @@ func (n *netBind) ParseEndpoint(s string) (conn.Endpoint, error) {
addr := xnet.ParseAddress(ipStr) addr := xnet.ParseAddress(ipStr)
if addr.Family() == xnet.AddressFamilyDomain { if addr.Family() == xnet.AddressFamilyDomain {
ips, err := n.dns.LookupIP(addr.Domain(), n.dnsOption) ips, _, err := n.dns.LookupIP(addr.Domain(), n.dnsOption)
if err != nil { if err != nil {
return nil, err return nil, err
} else if len(ips) == 0 { } else if len(ips) == 0 {

View File

@@ -150,13 +150,13 @@ func (h *Handler) Process(ctx context.Context, link *transport.Link, dialer inte
// resolve dns // resolve dns
addr := destination.Address addr := destination.Address
if addr.Family().IsDomain() { if addr.Family().IsDomain() {
ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{ ips, _, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
IPv4Enable: h.hasIPv4 && h.conf.preferIP4(), IPv4Enable: h.hasIPv4 && h.conf.preferIP4(),
IPv6Enable: h.hasIPv6 && h.conf.preferIP6(), IPv6Enable: h.hasIPv6 && h.conf.preferIP6(),
}) })
{ // Resolve fallback { // Resolve fallback
if (len(ips) == 0 || err != nil) && h.conf.hasFallback() { if (len(ips) == 0 || err != nil) && h.conf.hasFallback() {
ips, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{ ips, _, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{
IPv4Enable: h.hasIPv4 && h.conf.fallbackIP4(), IPv4Enable: h.hasIPv4 && h.conf.fallbackIP4(),
IPv6Enable: h.hasIPv6 && h.conf.fallbackIP6(), IPv6Enable: h.hasIPv6 && h.conf.fallbackIP6(),
}) })
@@ -284,13 +284,13 @@ func (h *Handler) createIPCRequest() string {
addr = net.ParseAddress(dialerIp.String()) addr = net.ParseAddress(dialerIp.String())
errors.LogInfo(h.bind.ctx, "createIPCRequest use dialer dest ip: ", addr) errors.LogInfo(h.bind.ctx, "createIPCRequest use dialer dest ip: ", addr)
} else { } else {
ips, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{ ips, _, err := h.dns.LookupIP(addr.Domain(), dns.IPOption{
IPv4Enable: h.hasIPv4 && h.conf.preferIP4(), IPv4Enable: h.hasIPv4 && h.conf.preferIP4(),
IPv6Enable: h.hasIPv6 && h.conf.preferIP6(), IPv6Enable: h.hasIPv6 && h.conf.preferIP6(),
}) })
{ // Resolve fallback { // Resolve fallback
if (len(ips) == 0 || err != nil) && h.conf.hasFallback() { if (len(ips) == 0 || err != nil) && h.conf.hasFallback() {
ips, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{ ips, _, err = h.dns.LookupIP(addr.Domain(), dns.IPOption{
IPv4Enable: h.hasIPv4 && h.conf.fallbackIP4(), IPv4Enable: h.hasIPv4 && h.conf.fallbackIP4(),
IPv6Enable: h.hasIPv6 && h.conf.fallbackIP6(), IPv6Enable: h.hasIPv6 && h.conf.fallbackIP6(),
}) })

View File

@@ -10,6 +10,7 @@ import (
"fmt" "fmt"
"net/netip" "net/netip"
"os" "os"
"sync"
"syscall" "syscall"
"golang.zx2c4.com/wireguard/tun" "golang.zx2c4.com/wireguard/tun"
@@ -33,6 +34,7 @@ type netTun struct {
incomingPacket chan *buffer.View incomingPacket chan *buffer.View
mtu int mtu int
hasV4, hasV6 bool hasV4, hasV6 bool
closeOnce sync.Once
} }
type Net netTun type Net netTun
@@ -174,18 +176,15 @@ func (tun *netTun) Flush() error {
// Close implements tun.Device // Close implements tun.Device
func (tun *netTun) Close() error { func (tun *netTun) Close() error {
tun.stack.RemoveNIC(1) tun.closeOnce.Do(func() {
tun.stack.RemoveNIC(1)
if tun.events != nil {
close(tun.events) close(tun.events)
}
tun.ep.Close() tun.ep.Close()
if tun.incomingPacket != nil {
close(tun.incomingPacket) close(tun.incomingPacket)
} })
return nil return nil
} }

View File

@@ -0,0 +1,52 @@
package wireguard_test
import (
"context"
"github.com/stretchr/testify/assert"
"runtime/debug"
"testing"
"github.com/xtls/xray-core/core"
"github.com/xtls/xray-core/proxy/wireguard"
)
// TestWireGuardServerInitializationError verifies that an error during TUN initialization
// (triggered by an empty SecretKey) in the WireGuard server does not cause a panic and returns an error instead.
func TestWireGuardServerInitializationError(t *testing.T) {
// Create a minimal core instance with default features
config := &core.Config{}
instance, err := core.New(config)
if err != nil {
t.Fatalf("Failed to create core instance: %v", err)
}
// Set the Xray instance in the context
ctx := context.WithValue(context.Background(), core.XrayKey(1), instance)
// Define the server configuration with an empty SecretKey to trigger error
conf := &wireguard.DeviceConfig{
IsClient: false,
Endpoint: []string{"10.0.0.1/32"},
Mtu: 1420,
SecretKey: "", // Empty SecretKey to trigger error
Peers: []*wireguard.PeerConfig{
{
PublicKey: "some_public_key",
AllowedIps: []string{"10.0.0.2/32"},
},
},
}
// Use defer to catch any panic and fail the test explicitly
defer func() {
if r := recover(); r != nil {
t.Errorf("TUN initialization panicked: %v", r)
debug.PrintStack()
}
}()
// Attempt to initialize the WireGuard server
_, err = wireguard.NewServer(ctx, conf)
// Check that an error is returned
assert.ErrorContains(t, err, "failed to set private_key: hex string does not fit the slice")
}

View File

@@ -50,12 +50,13 @@ func (mr *DNSClientMockRecorder) Close() *gomock.Call {
} }
// LookupIP mocks base method // LookupIP mocks base method
func (m *DNSClient) LookupIP(arg0 string, arg1 dns.IPOption) ([]net.IP, error) { func (m *DNSClient) LookupIP(arg0 string, arg1 dns.IPOption) ([]net.IP, uint32, error) {
m.ctrl.T.Helper() m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "LookupIP", arg0, arg1) ret := m.ctrl.Call(m, "LookupIP", arg0, arg1)
ret0, _ := ret[0].([]net.IP) ret0, _ := ret[0].([]net.IP)
ret1, _ := ret[1].(error) ret1, _ := ret[1].(uint32)
return ret0, ret1 ret2, _ := ret[2].(error)
return ret0, ret1, ret2
} }
// LookupIP indicates an expected call of LookupIP // LookupIP indicates an expected call of LookupIP

View File

@@ -95,6 +95,67 @@ func (DomainStrategy) EnumDescriptor() ([]byte, []int) {
return file_transport_internet_config_proto_rawDescGZIP(), []int{0} return file_transport_internet_config_proto_rawDescGZIP(), []int{0}
} }
type AddressPortStrategy int32
const (
AddressPortStrategy_None AddressPortStrategy = 0
AddressPortStrategy_SrvPortOnly AddressPortStrategy = 1
AddressPortStrategy_SrvAddressOnly AddressPortStrategy = 2
AddressPortStrategy_SrvPortAndAddress AddressPortStrategy = 3
AddressPortStrategy_TxtPortOnly AddressPortStrategy = 4
AddressPortStrategy_TxtAddressOnly AddressPortStrategy = 5
AddressPortStrategy_TxtPortAndAddress AddressPortStrategy = 6
)
// Enum value maps for AddressPortStrategy.
var (
AddressPortStrategy_name = map[int32]string{
0: "None",
1: "SrvPortOnly",
2: "SrvAddressOnly",
3: "SrvPortAndAddress",
4: "TxtPortOnly",
5: "TxtAddressOnly",
6: "TxtPortAndAddress",
}
AddressPortStrategy_value = map[string]int32{
"None": 0,
"SrvPortOnly": 1,
"SrvAddressOnly": 2,
"SrvPortAndAddress": 3,
"TxtPortOnly": 4,
"TxtAddressOnly": 5,
"TxtPortAndAddress": 6,
}
)
func (x AddressPortStrategy) Enum() *AddressPortStrategy {
p := new(AddressPortStrategy)
*p = x
return p
}
func (x AddressPortStrategy) String() string {
return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
}
func (AddressPortStrategy) Descriptor() protoreflect.EnumDescriptor {
return file_transport_internet_config_proto_enumTypes[1].Descriptor()
}
func (AddressPortStrategy) Type() protoreflect.EnumType {
return &file_transport_internet_config_proto_enumTypes[1]
}
func (x AddressPortStrategy) Number() protoreflect.EnumNumber {
return protoreflect.EnumNumber(x)
}
// Deprecated: Use AddressPortStrategy.Descriptor instead.
func (AddressPortStrategy) EnumDescriptor() ([]byte, []int) {
return file_transport_internet_config_proto_rawDescGZIP(), []int{1}
}
type SocketConfig_TProxyMode int32 type SocketConfig_TProxyMode int32
const ( const (
@@ -131,11 +192,11 @@ func (x SocketConfig_TProxyMode) String() string {
} }
func (SocketConfig_TProxyMode) Descriptor() protoreflect.EnumDescriptor { func (SocketConfig_TProxyMode) Descriptor() protoreflect.EnumDescriptor {
return file_transport_internet_config_proto_enumTypes[1].Descriptor() return file_transport_internet_config_proto_enumTypes[2].Descriptor()
} }
func (SocketConfig_TProxyMode) Type() protoreflect.EnumType { func (SocketConfig_TProxyMode) Type() protoreflect.EnumType {
return &file_transport_internet_config_proto_enumTypes[1] return &file_transport_internet_config_proto_enumTypes[2]
} }
func (x SocketConfig_TProxyMode) Number() protoreflect.EnumNumber { func (x SocketConfig_TProxyMode) Number() protoreflect.EnumNumber {
@@ -356,10 +417,11 @@ type CustomSockopt struct {
sizeCache protoimpl.SizeCache sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields unknownFields protoimpl.UnknownFields
Level string `protobuf:"bytes,1,opt,name=level,proto3" json:"level,omitempty"` Network string `protobuf:"bytes,1,opt,name=network,proto3" json:"network,omitempty"`
Opt string `protobuf:"bytes,2,opt,name=opt,proto3" json:"opt,omitempty"` Level string `protobuf:"bytes,2,opt,name=level,proto3" json:"level,omitempty"`
Value string `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` Opt string `protobuf:"bytes,3,opt,name=opt,proto3" json:"opt,omitempty"`
Type string `protobuf:"bytes,4,opt,name=type,proto3" json:"type,omitempty"` Value string `protobuf:"bytes,4,opt,name=value,proto3" json:"value,omitempty"`
Type string `protobuf:"bytes,5,opt,name=type,proto3" json:"type,omitempty"`
} }
func (x *CustomSockopt) Reset() { func (x *CustomSockopt) Reset() {
@@ -392,6 +454,13 @@ func (*CustomSockopt) Descriptor() ([]byte, []int) {
return file_transport_internet_config_proto_rawDescGZIP(), []int{3} return file_transport_internet_config_proto_rawDescGZIP(), []int{3}
} }
func (x *CustomSockopt) GetNetwork() string {
if x != nil {
return x.Network
}
return ""
}
func (x *CustomSockopt) GetLevel() string { func (x *CustomSockopt) GetLevel() string {
if x != nil { if x != nil {
return x.Level return x.Level
@@ -434,23 +503,24 @@ type SocketConfig struct {
Tproxy SocketConfig_TProxyMode `protobuf:"varint,3,opt,name=tproxy,proto3,enum=xray.transport.internet.SocketConfig_TProxyMode" json:"tproxy,omitempty"` Tproxy SocketConfig_TProxyMode `protobuf:"varint,3,opt,name=tproxy,proto3,enum=xray.transport.internet.SocketConfig_TProxyMode" json:"tproxy,omitempty"`
// ReceiveOriginalDestAddress is for enabling IP_RECVORIGDSTADDR socket // ReceiveOriginalDestAddress is for enabling IP_RECVORIGDSTADDR socket
// option. This option is for UDP only. // option. This option is for UDP only.
ReceiveOriginalDestAddress bool `protobuf:"varint,4,opt,name=receive_original_dest_address,json=receiveOriginalDestAddress,proto3" json:"receive_original_dest_address,omitempty"` ReceiveOriginalDestAddress bool `protobuf:"varint,4,opt,name=receive_original_dest_address,json=receiveOriginalDestAddress,proto3" json:"receive_original_dest_address,omitempty"`
BindAddress []byte `protobuf:"bytes,5,opt,name=bind_address,json=bindAddress,proto3" json:"bind_address,omitempty"` BindAddress []byte `protobuf:"bytes,5,opt,name=bind_address,json=bindAddress,proto3" json:"bind_address,omitempty"`
BindPort uint32 `protobuf:"varint,6,opt,name=bind_port,json=bindPort,proto3" json:"bind_port,omitempty"` BindPort uint32 `protobuf:"varint,6,opt,name=bind_port,json=bindPort,proto3" json:"bind_port,omitempty"`
AcceptProxyProtocol bool `protobuf:"varint,7,opt,name=accept_proxy_protocol,json=acceptProxyProtocol,proto3" json:"accept_proxy_protocol,omitempty"` AcceptProxyProtocol bool `protobuf:"varint,7,opt,name=accept_proxy_protocol,json=acceptProxyProtocol,proto3" json:"accept_proxy_protocol,omitempty"`
DomainStrategy DomainStrategy `protobuf:"varint,8,opt,name=domain_strategy,json=domainStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"domain_strategy,omitempty"` DomainStrategy DomainStrategy `protobuf:"varint,8,opt,name=domain_strategy,json=domainStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"domain_strategy,omitempty"`
DialerProxy string `protobuf:"bytes,9,opt,name=dialer_proxy,json=dialerProxy,proto3" json:"dialer_proxy,omitempty"` DialerProxy string `protobuf:"bytes,9,opt,name=dialer_proxy,json=dialerProxy,proto3" json:"dialer_proxy,omitempty"`
TcpKeepAliveInterval int32 `protobuf:"varint,10,opt,name=tcp_keep_alive_interval,json=tcpKeepAliveInterval,proto3" json:"tcp_keep_alive_interval,omitempty"` TcpKeepAliveInterval int32 `protobuf:"varint,10,opt,name=tcp_keep_alive_interval,json=tcpKeepAliveInterval,proto3" json:"tcp_keep_alive_interval,omitempty"`
TcpKeepAliveIdle int32 `protobuf:"varint,11,opt,name=tcp_keep_alive_idle,json=tcpKeepAliveIdle,proto3" json:"tcp_keep_alive_idle,omitempty"` TcpKeepAliveIdle int32 `protobuf:"varint,11,opt,name=tcp_keep_alive_idle,json=tcpKeepAliveIdle,proto3" json:"tcp_keep_alive_idle,omitempty"`
TcpCongestion string `protobuf:"bytes,12,opt,name=tcp_congestion,json=tcpCongestion,proto3" json:"tcp_congestion,omitempty"` TcpCongestion string `protobuf:"bytes,12,opt,name=tcp_congestion,json=tcpCongestion,proto3" json:"tcp_congestion,omitempty"`
Interface string `protobuf:"bytes,13,opt,name=interface,proto3" json:"interface,omitempty"` Interface string `protobuf:"bytes,13,opt,name=interface,proto3" json:"interface,omitempty"`
V6Only bool `protobuf:"varint,14,opt,name=v6only,proto3" json:"v6only,omitempty"` V6Only bool `protobuf:"varint,14,opt,name=v6only,proto3" json:"v6only,omitempty"`
TcpWindowClamp int32 `protobuf:"varint,15,opt,name=tcp_window_clamp,json=tcpWindowClamp,proto3" json:"tcp_window_clamp,omitempty"` TcpWindowClamp int32 `protobuf:"varint,15,opt,name=tcp_window_clamp,json=tcpWindowClamp,proto3" json:"tcp_window_clamp,omitempty"`
TcpUserTimeout int32 `protobuf:"varint,16,opt,name=tcp_user_timeout,json=tcpUserTimeout,proto3" json:"tcp_user_timeout,omitempty"` TcpUserTimeout int32 `protobuf:"varint,16,opt,name=tcp_user_timeout,json=tcpUserTimeout,proto3" json:"tcp_user_timeout,omitempty"`
TcpMaxSeg int32 `protobuf:"varint,17,opt,name=tcp_max_seg,json=tcpMaxSeg,proto3" json:"tcp_max_seg,omitempty"` TcpMaxSeg int32 `protobuf:"varint,17,opt,name=tcp_max_seg,json=tcpMaxSeg,proto3" json:"tcp_max_seg,omitempty"`
Penetrate bool `protobuf:"varint,18,opt,name=penetrate,proto3" json:"penetrate,omitempty"` Penetrate bool `protobuf:"varint,18,opt,name=penetrate,proto3" json:"penetrate,omitempty"`
TcpMptcp bool `protobuf:"varint,19,opt,name=tcp_mptcp,json=tcpMptcp,proto3" json:"tcp_mptcp,omitempty"` TcpMptcp bool `protobuf:"varint,19,opt,name=tcp_mptcp,json=tcpMptcp,proto3" json:"tcp_mptcp,omitempty"`
CustomSockopt []*CustomSockopt `protobuf:"bytes,20,rep,name=customSockopt,proto3" json:"customSockopt,omitempty"` CustomSockopt []*CustomSockopt `protobuf:"bytes,20,rep,name=customSockopt,proto3" json:"customSockopt,omitempty"`
AddressPortStrategy AddressPortStrategy `protobuf:"varint,21,opt,name=address_port_strategy,json=addressPortStrategy,proto3,enum=xray.transport.internet.AddressPortStrategy" json:"address_port_strategy,omitempty"`
} }
func (x *SocketConfig) Reset() { func (x *SocketConfig) Reset() {
@@ -623,6 +693,13 @@ func (x *SocketConfig) GetCustomSockopt() []*CustomSockopt {
return nil return nil
} }
func (x *SocketConfig) GetAddressPortStrategy() AddressPortStrategy {
if x != nil {
return x.AddressPortStrategy
}
return AddressPortStrategy_None
}
var File_transport_internet_config_proto protoreflect.FileDescriptor var File_transport_internet_config_proto protoreflect.FileDescriptor
var file_transport_internet_config_proto_rawDesc = []byte{ var file_transport_internet_config_proto_rawDesc = []byte{
@@ -671,89 +748,107 @@ var file_transport_internet_config_proto_rawDesc = []byte{
0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x74, 0x61, 0x67, 0x12, 0x30, 0x0a, 0x13, 0x67, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x74, 0x61, 0x67, 0x12, 0x30, 0x0a, 0x13,
0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x4c, 0x61, 0x79, 0x65, 0x72, 0x50, 0x72, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x4c, 0x61, 0x79, 0x65, 0x72, 0x50, 0x72,
0x6f, 0x78, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x13, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6f, 0x78, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x13, 0x74, 0x72, 0x61, 0x6e, 0x73,
0x70, 0x6f, 0x72, 0x74, 0x4c, 0x61, 0x79, 0x65, 0x72, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x22, 0x61, 0x70, 0x6f, 0x72, 0x74, 0x4c, 0x61, 0x79, 0x65, 0x72, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x22, 0x7b,
0x0a, 0x0d, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x53, 0x6f, 0x63, 0x6b, 0x6f, 0x70, 0x74, 0x12, 0x0a, 0x0d, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x53, 0x6f, 0x63, 0x6b, 0x6f, 0x70, 0x74, 0x12,
0x14, 0x0a, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x18, 0x0a, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x6c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x10, 0x0a, 0x03, 0x6f, 0x70, 0x74, 0x18, 0x02, 0x20, 0x01, 0x52, 0x07, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x65, 0x76,
0x28, 0x09, 0x52, 0x03, 0x6f, 0x70, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x65, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x12,
0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x12, 0x0a, 0x10, 0x0a, 0x03, 0x6f, 0x70, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6f, 0x70,
0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09,
0x65, 0x22, 0x9b, 0x07, 0x0a, 0x0c, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18,
0x69, 0x67, 0x12, 0x12, 0x0a, 0x04, 0x6d, 0x61, 0x72, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x22, 0xfd, 0x07, 0x0a, 0x0c,
0x52, 0x04, 0x6d, 0x61, 0x72, 0x6b, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x66, 0x6f, 0x18, 0x02, 0x20, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x12, 0x0a, 0x04,
0x01, 0x28, 0x05, 0x52, 0x03, 0x74, 0x66, 0x6f, 0x12, 0x48, 0x0a, 0x06, 0x74, 0x70, 0x72, 0x6f, 0x6d, 0x61, 0x72, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x6d, 0x61, 0x72, 0x6b,
0x78, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x30, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x12, 0x10, 0x0a, 0x03, 0x74, 0x66, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x74,
0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x66, 0x6f, 0x12, 0x48, 0x0a, 0x06, 0x74, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x18, 0x03, 0x20, 0x01,
0x65, 0x74, 0x2e, 0x53, 0x6f, 0x63, 0x6b, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x28, 0x0e, 0x32, 0x30, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70,
0x54, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x4d, 0x6f, 0x64, 0x65, 0x52, 0x06, 0x74, 0x70, 0x72, 0x6f, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x53, 0x6f, 0x63,
0x78, 0x79, 0x12, 0x41, 0x0a, 0x1d, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x5f, 0x6f, 0x72, 0x6b, 0x65, 0x74, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x54, 0x50, 0x72, 0x6f, 0x78, 0x79,
0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x5f, 0x64, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x4d, 0x6f, 0x64, 0x65, 0x52, 0x06, 0x74, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x12, 0x41, 0x0a, 0x1d,
0x65, 0x73, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x1a, 0x72, 0x65, 0x63, 0x65, 0x69, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x5f, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c,
0x76, 0x65, 0x4f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x44, 0x65, 0x73, 0x74, 0x41, 0x64, 0x5f, 0x64, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x04, 0x20,
0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x21, 0x0a, 0x0c, 0x62, 0x69, 0x6e, 0x64, 0x5f, 0x61, 0x64, 0x01, 0x28, 0x08, 0x52, 0x1a, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x4f, 0x72, 0x69, 0x67,
0x64, 0x72, 0x65, 0x73, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x62, 0x69, 0x6e, 0x69, 0x6e, 0x61, 0x6c, 0x44, 0x65, 0x73, 0x74, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12,
0x64, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x69, 0x6e, 0x64, 0x21, 0x0a, 0x0c, 0x62, 0x69, 0x6e, 0x64, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x18,
0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x62, 0x69, 0x6e, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x62, 0x69, 0x6e, 0x64, 0x41, 0x64, 0x64, 0x72, 0x65,
0x64, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x32, 0x0a, 0x15, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x5f, 0x73, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x69, 0x6e, 0x64, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18,
0x70, 0x72, 0x6f, 0x78, 0x79, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x07, 0x06, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x08, 0x62, 0x69, 0x6e, 0x64, 0x50, 0x6f, 0x72, 0x74, 0x12,
0x20, 0x01, 0x28, 0x08, 0x52, 0x13, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x50, 0x72, 0x6f, 0x78, 0x32, 0x0a, 0x15, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x5f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x5f,
0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x12, 0x50, 0x0a, 0x0f, 0x64, 0x6f, 0x6d, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x18, 0x07, 0x20, 0x01, 0x28, 0x08, 0x52, 0x13,
0x61, 0x69, 0x6e, 0x5f, 0x73, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x18, 0x08, 0x20, 0x01, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x50, 0x72, 0x6f, 0x74, 0x6f,
0x28, 0x0e, 0x32, 0x27, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x63, 0x6f, 0x6c, 0x12, 0x50, 0x0a, 0x0f, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x5f, 0x73, 0x74,
0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x44, 0x6f, 0x6d, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x27, 0x2e, 0x78,
0x61, 0x69, 0x6e, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x52, 0x0e, 0x64, 0x6f, 0x6d, 0x72, 0x61, 0x79, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e,
0x61, 0x69, 0x6e, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x53, 0x74, 0x72,
0x69, 0x61, 0x6c, 0x65, 0x72, 0x5f, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x18, 0x09, 0x20, 0x01, 0x28, 0x61, 0x74, 0x65, 0x67, 0x79, 0x52, 0x0e, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x53, 0x74, 0x72,
0x09, 0x52, 0x0b, 0x64, 0x69, 0x61, 0x6c, 0x65, 0x72, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x12, 0x35, 0x61, 0x74, 0x65, 0x67, 0x79, 0x12, 0x21, 0x0a, 0x0c, 0x64, 0x69, 0x61, 0x6c, 0x65, 0x72, 0x5f,
0x0a, 0x17, 0x74, 0x63, 0x70, 0x5f, 0x6b, 0x65, 0x65, 0x70, 0x5f, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x70, 0x72, 0x6f, 0x78, 0x79, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x69, 0x61,
0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x05, 0x52, 0x6c, 0x65, 0x72, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x12, 0x35, 0x0a, 0x17, 0x74, 0x63, 0x70, 0x5f,
0x14, 0x74, 0x63, 0x70, 0x4b, 0x65, 0x65, 0x70, 0x41, 0x6c, 0x69, 0x76, 0x65, 0x49, 0x6e, 0x74, 0x6b, 0x65, 0x65, 0x70, 0x5f, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x5f, 0x69, 0x6e, 0x74, 0x65, 0x72,
0x65, 0x72, 0x76, 0x61, 0x6c, 0x12, 0x2d, 0x0a, 0x13, 0x74, 0x63, 0x70, 0x5f, 0x6b, 0x65, 0x65, 0x76, 0x61, 0x6c, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x05, 0x52, 0x14, 0x74, 0x63, 0x70, 0x4b, 0x65,
0x70, 0x5f, 0x61, 0x6c, 0x69, 0x76, 0x65, 0x5f, 0x69, 0x64, 0x6c, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x65, 0x70, 0x41, 0x6c, 0x69, 0x76, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61, 0x6c, 0x12,
0x28, 0x05, 0x52, 0x10, 0x74, 0x63, 0x70, 0x4b, 0x65, 0x65, 0x70, 0x41, 0x6c, 0x69, 0x76, 0x65, 0x2d, 0x0a, 0x13, 0x74, 0x63, 0x70, 0x5f, 0x6b, 0x65, 0x65, 0x70, 0x5f, 0x61, 0x6c, 0x69, 0x76,
0x49, 0x64, 0x6c, 0x65, 0x12, 0x25, 0x0a, 0x0e, 0x74, 0x63, 0x70, 0x5f, 0x63, 0x6f, 0x6e, 0x67, 0x65, 0x5f, 0x69, 0x64, 0x6c, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x05, 0x52, 0x10, 0x74, 0x63,
0x65, 0x73, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x74, 0x63, 0x70, 0x4b, 0x65, 0x65, 0x70, 0x41, 0x6c, 0x69, 0x76, 0x65, 0x49, 0x64, 0x6c, 0x65, 0x12, 0x25,
0x70, 0x43, 0x6f, 0x6e, 0x67, 0x65, 0x73, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1c, 0x0a, 0x09, 0x69, 0x0a, 0x0e, 0x74, 0x63, 0x70, 0x5f, 0x63, 0x6f, 0x6e, 0x67, 0x65, 0x73, 0x74, 0x69, 0x6f, 0x6e,
0x6e, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x74, 0x63, 0x70, 0x43, 0x6f, 0x6e, 0x67, 0x65,
0x69, 0x6e, 0x74, 0x65, 0x72, 0x66, 0x61, 0x63, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x76, 0x36, 0x6f, 0x73, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1c, 0x0a, 0x09, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x66, 0x61,
0x6e, 0x6c, 0x79, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x08, 0x52, 0x06, 0x76, 0x36, 0x6f, 0x6e, 0x6c, 0x63, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x66,
0x79, 0x12, 0x28, 0x0a, 0x10, 0x74, 0x63, 0x70, 0x5f, 0x77, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x5f, 0x61, 0x63, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x76, 0x36, 0x6f, 0x6e, 0x6c, 0x79, 0x18, 0x0e, 0x20,
0x63, 0x6c, 0x61, 0x6d, 0x70, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0e, 0x74, 0x63, 0x70, 0x01, 0x28, 0x08, 0x52, 0x06, 0x76, 0x36, 0x6f, 0x6e, 0x6c, 0x79, 0x12, 0x28, 0x0a, 0x10, 0x74,
0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x43, 0x6c, 0x61, 0x6d, 0x70, 0x12, 0x28, 0x0a, 0x10, 0x74, 0x63, 0x70, 0x5f, 0x77, 0x69, 0x6e, 0x64, 0x6f, 0x77, 0x5f, 0x63, 0x6c, 0x61, 0x6d, 0x70, 0x18,
0x63, 0x70, 0x5f, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0e, 0x74, 0x63, 0x70, 0x57, 0x69, 0x6e, 0x64, 0x6f, 0x77,
0x10, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0e, 0x74, 0x63, 0x70, 0x55, 0x73, 0x65, 0x72, 0x54, 0x69, 0x43, 0x6c, 0x61, 0x6d, 0x70, 0x12, 0x28, 0x0a, 0x10, 0x74, 0x63, 0x70, 0x5f, 0x75, 0x73, 0x65,
0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12, 0x1e, 0x0a, 0x0b, 0x74, 0x63, 0x70, 0x5f, 0x6d, 0x61, 0x78, 0x72, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x10, 0x20, 0x01, 0x28, 0x05, 0x52,
0x5f, 0x73, 0x65, 0x67, 0x18, 0x11, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x74, 0x63, 0x70, 0x4d, 0x0e, 0x74, 0x63, 0x70, 0x55, 0x73, 0x65, 0x72, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x12,
0x61, 0x78, 0x53, 0x65, 0x67, 0x12, 0x1c, 0x0a, 0x09, 0x70, 0x65, 0x6e, 0x65, 0x74, 0x72, 0x61, 0x1e, 0x0a, 0x0b, 0x74, 0x63, 0x70, 0x5f, 0x6d, 0x61, 0x78, 0x5f, 0x73, 0x65, 0x67, 0x18, 0x11,
0x74, 0x65, 0x18, 0x12, 0x20, 0x01, 0x28, 0x08, 0x52, 0x09, 0x70, 0x65, 0x6e, 0x65, 0x74, 0x72, 0x20, 0x01, 0x28, 0x05, 0x52, 0x09, 0x74, 0x63, 0x70, 0x4d, 0x61, 0x78, 0x53, 0x65, 0x67, 0x12,
0x61, 0x74, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x74, 0x63, 0x70, 0x5f, 0x6d, 0x70, 0x74, 0x63, 0x70, 0x1c, 0x0a, 0x09, 0x70, 0x65, 0x6e, 0x65, 0x74, 0x72, 0x61, 0x74, 0x65, 0x18, 0x12, 0x20, 0x01,
0x18, 0x13, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x74, 0x63, 0x70, 0x4d, 0x70, 0x74, 0x63, 0x70, 0x28, 0x08, 0x52, 0x09, 0x70, 0x65, 0x6e, 0x65, 0x74, 0x72, 0x61, 0x74, 0x65, 0x12, 0x1b, 0x0a,
0x12, 0x4c, 0x0a, 0x0d, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x53, 0x6f, 0x63, 0x6b, 0x6f, 0x70, 0x09, 0x74, 0x63, 0x70, 0x5f, 0x6d, 0x70, 0x74, 0x63, 0x70, 0x18, 0x13, 0x20, 0x01, 0x28, 0x08,
0x74, 0x18, 0x14, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x26, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x74, 0x52, 0x08, 0x74, 0x63, 0x70, 0x4d, 0x70, 0x74, 0x63, 0x70, 0x12, 0x4c, 0x0a, 0x0d, 0x63, 0x75,
0x73, 0x74, 0x6f, 0x6d, 0x53, 0x6f, 0x63, 0x6b, 0x6f, 0x70, 0x74, 0x18, 0x14, 0x20, 0x03, 0x28,
0x0b, 0x32, 0x26, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f,
0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x2e, 0x43, 0x75, 0x73, 0x74,
0x6f, 0x6d, 0x53, 0x6f, 0x63, 0x6b, 0x6f, 0x70, 0x74, 0x52, 0x0d, 0x63, 0x75, 0x73, 0x74, 0x6f,
0x6d, 0x53, 0x6f, 0x63, 0x6b, 0x6f, 0x70, 0x74, 0x12, 0x60, 0x0a, 0x15, 0x61, 0x64, 0x64, 0x72,
0x65, 0x73, 0x73, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x5f, 0x73, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67,
0x79, 0x18, 0x15, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x74,
0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65,
0x74, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x53, 0x6f, 0x63, 0x6b, 0x6f, 0x70, 0x74, 0x52, 0x74, 0x2e, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x50, 0x6f, 0x72, 0x74, 0x53, 0x74, 0x72,
0x0d, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x53, 0x6f, 0x63, 0x6b, 0x6f, 0x70, 0x74, 0x22, 0x2f, 0x61, 0x74, 0x65, 0x67, 0x79, 0x52, 0x13, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x50, 0x6f,
0x0a, 0x0a, 0x54, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x07, 0x0a, 0x03, 0x72, 0x74, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x22, 0x2f, 0x0a, 0x0a, 0x54, 0x50,
0x4f, 0x66, 0x66, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x54, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x10, 0x72, 0x6f, 0x78, 0x79, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x07, 0x0a, 0x03, 0x4f, 0x66, 0x66, 0x10,
0x01, 0x12, 0x0c, 0x0a, 0x08, 0x52, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x10, 0x02, 0x2a, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x54, 0x50, 0x72, 0x6f, 0x78, 0x79, 0x10, 0x01, 0x12, 0x0c, 0x0a,
0xa9, 0x01, 0x0a, 0x0e, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x08, 0x52, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x10, 0x02, 0x2a, 0xa9, 0x01, 0x0a, 0x0e,
0x67, 0x79, 0x12, 0x09, 0x0a, 0x05, 0x41, 0x53, 0x5f, 0x49, 0x53, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x44, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x12, 0x09,
0x06, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x53, 0x45, 0x0a, 0x05, 0x41, 0x53, 0x5f, 0x49, 0x53, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x55, 0x53, 0x45,
0x5f, 0x49, 0x50, 0x34, 0x10, 0x02, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x5f, 0x49, 0x50, 0x10, 0x01, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x34,
0x36, 0x10, 0x03, 0x12, 0x0c, 0x0a, 0x08, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x34, 0x36, 0x10, 0x10, 0x02, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x36, 0x10, 0x03, 0x12,
0x04, 0x12, 0x0c, 0x0a, 0x08, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x36, 0x34, 0x10, 0x05, 0x12, 0x0c, 0x0a, 0x08, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x34, 0x36, 0x10, 0x04, 0x12, 0x0c, 0x0a,
0x0c, 0x0a, 0x08, 0x46, 0x4f, 0x52, 0x43, 0x45, 0x5f, 0x49, 0x50, 0x10, 0x06, 0x12, 0x0d, 0x0a, 0x08, 0x55, 0x53, 0x45, 0x5f, 0x49, 0x50, 0x36, 0x34, 0x10, 0x05, 0x12, 0x0c, 0x0a, 0x08, 0x46,
0x09, 0x46, 0x4f, 0x52, 0x43, 0x45, 0x5f, 0x49, 0x50, 0x34, 0x10, 0x07, 0x12, 0x0d, 0x0a, 0x09, 0x4f, 0x52, 0x43, 0x45, 0x5f, 0x49, 0x50, 0x10, 0x06, 0x12, 0x0d, 0x0a, 0x09, 0x46, 0x4f, 0x52,
0x46, 0x4f, 0x52, 0x43, 0x45, 0x5f, 0x49, 0x50, 0x36, 0x10, 0x08, 0x12, 0x0e, 0x0a, 0x0a, 0x46, 0x43, 0x45, 0x5f, 0x49, 0x50, 0x34, 0x10, 0x07, 0x12, 0x0d, 0x0a, 0x09, 0x46, 0x4f, 0x52, 0x43,
0x4f, 0x52, 0x43, 0x45, 0x5f, 0x49, 0x50, 0x34, 0x36, 0x10, 0x09, 0x12, 0x0e, 0x0a, 0x0a, 0x46, 0x45, 0x5f, 0x49, 0x50, 0x36, 0x10, 0x08, 0x12, 0x0e, 0x0a, 0x0a, 0x46, 0x4f, 0x52, 0x43, 0x45,
0x4f, 0x52, 0x43, 0x45, 0x5f, 0x49, 0x50, 0x36, 0x34, 0x10, 0x0a, 0x42, 0x67, 0x0a, 0x1b, 0x63, 0x5f, 0x49, 0x50, 0x34, 0x36, 0x10, 0x09, 0x12, 0x0e, 0x0a, 0x0a, 0x46, 0x4f, 0x52, 0x43, 0x45,
0x6f, 0x6d, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x5f, 0x49, 0x50, 0x36, 0x34, 0x10, 0x0a, 0x2a, 0x97, 0x01, 0x0a, 0x13, 0x41, 0x64, 0x64, 0x72,
0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x50, 0x01, 0x5a, 0x2c, 0x67, 0x69, 0x65, 0x73, 0x73, 0x50, 0x6f, 0x72, 0x74, 0x53, 0x74, 0x72, 0x61, 0x74, 0x65, 0x67, 0x79, 0x12,
0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78, 0x74, 0x6c, 0x73, 0x2f, 0x78, 0x72, 0x08, 0x0a, 0x04, 0x4e, 0x6f, 0x6e, 0x65, 0x10, 0x00, 0x12, 0x0f, 0x0a, 0x0b, 0x53, 0x72, 0x76,
0x61, 0x79, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x50, 0x6f, 0x72, 0x74, 0x4f, 0x6e, 0x6c, 0x79, 0x10, 0x01, 0x12, 0x12, 0x0a, 0x0e, 0x53, 0x72,
0x74, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0xaa, 0x02, 0x17, 0x58, 0x72, 0x61, 0x76, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x4f, 0x6e, 0x6c, 0x79, 0x10, 0x02, 0x12, 0x15,
0x79, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x0a, 0x11, 0x53, 0x72, 0x76, 0x50, 0x6f, 0x72, 0x74, 0x41, 0x6e, 0x64, 0x41, 0x64, 0x64, 0x72,
0x72, 0x6e, 0x65, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, 0x65, 0x73, 0x73, 0x10, 0x03, 0x12, 0x0f, 0x0a, 0x0b, 0x54, 0x78, 0x74, 0x50, 0x6f, 0x72, 0x74,
0x4f, 0x6e, 0x6c, 0x79, 0x10, 0x04, 0x12, 0x12, 0x0a, 0x0e, 0x54, 0x78, 0x74, 0x41, 0x64, 0x64,
0x72, 0x65, 0x73, 0x73, 0x4f, 0x6e, 0x6c, 0x79, 0x10, 0x05, 0x12, 0x15, 0x0a, 0x11, 0x54, 0x78,
0x74, 0x50, 0x6f, 0x72, 0x74, 0x41, 0x6e, 0x64, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x10,
0x06, 0x42, 0x67, 0x0a, 0x1b, 0x63, 0x6f, 0x6d, 0x2e, 0x78, 0x72, 0x61, 0x79, 0x2e, 0x74, 0x72,
0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74,
0x50, 0x01, 0x5a, 0x2c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x78,
0x74, 0x6c, 0x73, 0x2f, 0x78, 0x72, 0x61, 0x79, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x74, 0x72,
0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74,
0xaa, 0x02, 0x17, 0x58, 0x72, 0x61, 0x79, 0x2e, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72,
0x74, 0x2e, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
} }
var ( var (
@@ -768,33 +863,35 @@ func file_transport_internet_config_proto_rawDescGZIP() []byte {
return file_transport_internet_config_proto_rawDescData return file_transport_internet_config_proto_rawDescData
} }
var file_transport_internet_config_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_transport_internet_config_proto_enumTypes = make([]protoimpl.EnumInfo, 3)
var file_transport_internet_config_proto_msgTypes = make([]protoimpl.MessageInfo, 5) var file_transport_internet_config_proto_msgTypes = make([]protoimpl.MessageInfo, 5)
var file_transport_internet_config_proto_goTypes = []any{ var file_transport_internet_config_proto_goTypes = []any{
(DomainStrategy)(0), // 0: xray.transport.internet.DomainStrategy (DomainStrategy)(0), // 0: xray.transport.internet.DomainStrategy
(SocketConfig_TProxyMode)(0), // 1: xray.transport.internet.SocketConfig.TProxyMode (AddressPortStrategy)(0), // 1: xray.transport.internet.AddressPortStrategy
(*TransportConfig)(nil), // 2: xray.transport.internet.TransportConfig (SocketConfig_TProxyMode)(0), // 2: xray.transport.internet.SocketConfig.TProxyMode
(*StreamConfig)(nil), // 3: xray.transport.internet.StreamConfig (*TransportConfig)(nil), // 3: xray.transport.internet.TransportConfig
(*ProxyConfig)(nil), // 4: xray.transport.internet.ProxyConfig (*StreamConfig)(nil), // 4: xray.transport.internet.StreamConfig
(*CustomSockopt)(nil), // 5: xray.transport.internet.CustomSockopt (*ProxyConfig)(nil), // 5: xray.transport.internet.ProxyConfig
(*SocketConfig)(nil), // 6: xray.transport.internet.SocketConfig (*CustomSockopt)(nil), // 6: xray.transport.internet.CustomSockopt
(*serial.TypedMessage)(nil), // 7: xray.common.serial.TypedMessage (*SocketConfig)(nil), // 7: xray.transport.internet.SocketConfig
(*net.IPOrDomain)(nil), // 8: xray.common.net.IPOrDomain (*serial.TypedMessage)(nil), // 8: xray.common.serial.TypedMessage
(*net.IPOrDomain)(nil), // 9: xray.common.net.IPOrDomain
} }
var file_transport_internet_config_proto_depIdxs = []int32{ var file_transport_internet_config_proto_depIdxs = []int32{
7, // 0: xray.transport.internet.TransportConfig.settings:type_name -> xray.common.serial.TypedMessage 8, // 0: xray.transport.internet.TransportConfig.settings:type_name -> xray.common.serial.TypedMessage
8, // 1: xray.transport.internet.StreamConfig.address:type_name -> xray.common.net.IPOrDomain 9, // 1: xray.transport.internet.StreamConfig.address:type_name -> xray.common.net.IPOrDomain
2, // 2: xray.transport.internet.StreamConfig.transport_settings:type_name -> xray.transport.internet.TransportConfig 3, // 2: xray.transport.internet.StreamConfig.transport_settings:type_name -> xray.transport.internet.TransportConfig
7, // 3: xray.transport.internet.StreamConfig.security_settings:type_name -> xray.common.serial.TypedMessage 8, // 3: xray.transport.internet.StreamConfig.security_settings:type_name -> xray.common.serial.TypedMessage
6, // 4: xray.transport.internet.StreamConfig.socket_settings:type_name -> xray.transport.internet.SocketConfig 7, // 4: xray.transport.internet.StreamConfig.socket_settings:type_name -> xray.transport.internet.SocketConfig
1, // 5: xray.transport.internet.SocketConfig.tproxy:type_name -> xray.transport.internet.SocketConfig.TProxyMode 2, // 5: xray.transport.internet.SocketConfig.tproxy:type_name -> xray.transport.internet.SocketConfig.TProxyMode
0, // 6: xray.transport.internet.SocketConfig.domain_strategy:type_name -> xray.transport.internet.DomainStrategy 0, // 6: xray.transport.internet.SocketConfig.domain_strategy:type_name -> xray.transport.internet.DomainStrategy
5, // 7: xray.transport.internet.SocketConfig.customSockopt:type_name -> xray.transport.internet.CustomSockopt 6, // 7: xray.transport.internet.SocketConfig.customSockopt:type_name -> xray.transport.internet.CustomSockopt
8, // [8:8] is the sub-list for method output_type 1, // 8: xray.transport.internet.SocketConfig.address_port_strategy:type_name -> xray.transport.internet.AddressPortStrategy
8, // [8:8] is the sub-list for method input_type 9, // [9:9] is the sub-list for method output_type
8, // [8:8] is the sub-list for extension type_name 9, // [9:9] is the sub-list for method input_type
8, // [8:8] is the sub-list for extension extendee 9, // [9:9] is the sub-list for extension type_name
0, // [0:8] is the sub-list for field type_name 9, // [9:9] is the sub-list for extension extendee
0, // [0:9] is the sub-list for field type_name
} }
func init() { file_transport_internet_config_proto_init() } func init() { file_transport_internet_config_proto_init() }
@@ -807,7 +904,7 @@ func file_transport_internet_config_proto_init() {
File: protoimpl.DescBuilder{ File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(), GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_transport_internet_config_proto_rawDesc, RawDescriptor: file_transport_internet_config_proto_rawDesc,
NumEnums: 2, NumEnums: 3,
NumMessages: 5, NumMessages: 5,
NumExtensions: 0, NumExtensions: 0,
NumServices: 0, NumServices: 0,

View File

@@ -23,6 +23,16 @@ enum DomainStrategy {
FORCE_IP64 = 10; FORCE_IP64 = 10;
} }
enum AddressPortStrategy {
None = 0;
SrvPortOnly = 1;
SrvAddressOnly = 2;
SrvPortAndAddress = 3;
TxtPortOnly = 4;
TxtAddressOnly = 5;
TxtPortAndAddress = 6;
}
message TransportConfig { message TransportConfig {
// Transport protocol name. // Transport protocol name.
string protocol_name = 3; string protocol_name = 3;
@@ -55,10 +65,11 @@ message ProxyConfig {
} }
message CustomSockopt { message CustomSockopt {
string level = 1; string network = 1;
string opt = 2; string level = 2;
string value = 3; string opt = 3;
string type = 4; string value = 4;
string type = 5;
} }
// SocketConfig is options to be applied on network sockets. // SocketConfig is options to be applied on network sockets.
@@ -116,4 +127,6 @@ message SocketConfig {
bool tcp_mptcp = 19; bool tcp_mptcp = 19;
repeated CustomSockopt customSockopt = 20; repeated CustomSockopt customSockopt = 20;
AddressPortStrategy address_port_strategy = 21;
} }

View File

@@ -2,6 +2,9 @@ package internet
import ( import (
"context" "context"
"fmt"
gonet "net"
"strings"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/dice" "github.com/xtls/xray-core/common/dice"
@@ -87,13 +90,13 @@ func lookupIP(domain string, strategy DomainStrategy, localAddr net.Address) ([]
return nil, nil return nil, nil
} }
ips, err := dnsClient.LookupIP(domain, dns.IPOption{ ips, _, err := dnsClient.LookupIP(domain, dns.IPOption{
IPv4Enable: (localAddr == nil || localAddr.Family().IsIPv4()) && strategy.preferIP4(), IPv4Enable: (localAddr == nil || localAddr.Family().IsIPv4()) && strategy.preferIP4(),
IPv6Enable: (localAddr == nil || localAddr.Family().IsIPv6()) && strategy.preferIP6(), IPv6Enable: (localAddr == nil || localAddr.Family().IsIPv6()) && strategy.preferIP6(),
}) })
{ // Resolve fallback { // Resolve fallback
if (len(ips) == 0 || err != nil) && strategy.hasFallback() && localAddr == nil { if (len(ips) == 0 || err != nil) && strategy.hasFallback() && localAddr == nil {
ips, err = dnsClient.LookupIP(domain, dns.IPOption{ ips, _, err = dnsClient.LookupIP(domain, dns.IPOption{
IPv4Enable: strategy.fallbackIP4(), IPv4Enable: strategy.fallbackIP4(),
IPv6Enable: strategy.fallbackIP6(), IPv6Enable: strategy.fallbackIP6(),
}) })
@@ -140,6 +143,93 @@ func redirect(ctx context.Context, dst net.Destination, obt string) net.Conn {
return nil return nil
} }
func checkAddressPortStrategy(ctx context.Context, dest net.Destination, sockopt *SocketConfig) (*net.Destination, error) {
if sockopt.AddressPortStrategy == AddressPortStrategy_None {
return nil, nil
}
newDest := dest
var OverridePort, OverrideAddress bool
var OverrideBy string
switch sockopt.AddressPortStrategy {
case AddressPortStrategy_SrvPortOnly:
OverridePort = true
OverrideAddress = false
OverrideBy = "srv"
case AddressPortStrategy_SrvAddressOnly:
OverridePort = false
OverrideAddress = true
OverrideBy = "srv"
case AddressPortStrategy_SrvPortAndAddress:
OverridePort = true
OverrideAddress = true
OverrideBy = "srv"
case AddressPortStrategy_TxtPortOnly:
OverridePort = true
OverrideAddress = false
OverrideBy = "txt"
case AddressPortStrategy_TxtAddressOnly:
OverridePort = false
OverrideAddress = true
OverrideBy = "txt"
case AddressPortStrategy_TxtPortAndAddress:
OverridePort = true
OverrideAddress = true
OverrideBy = "txt"
default:
return nil, errors.New("unknown AddressPortStrategy")
}
if !dest.Address.Family().IsDomain() {
return nil, nil
}
if OverrideBy == "srv" {
errors.LogDebug(ctx, "query SRV record for "+dest.Address.String())
parts := strings.SplitN(dest.Address.String(), ".", 3)
if len(parts) != 3 {
return nil, errors.New("invalid address format", dest.Address.String())
}
_, srvRecords, err := gonet.DefaultResolver.LookupSRV(context.Background(), parts[0][1:], parts[1][1:], parts[2])
if err != nil {
return nil, errors.New("failed to lookup SRV record").Base(err)
}
errors.LogDebug(ctx, "SRV record: "+fmt.Sprintf("addr=%s, port=%d, priority=%d, weight=%d", srvRecords[0].Target, srvRecords[0].Port, srvRecords[0].Priority, srvRecords[0].Weight))
if OverridePort {
newDest.Port = net.Port(srvRecords[0].Port)
}
if OverrideAddress {
newDest.Address = net.ParseAddress(srvRecords[0].Target)
}
return &newDest, nil
}
if OverrideBy == "txt" {
errors.LogDebug(ctx, "query TXT record for "+dest.Address.String())
txtRecords, err := gonet.DefaultResolver.LookupTXT(ctx, dest.Address.String())
if err != nil {
errors.LogError(ctx, "failed to lookup SRV record: "+err.Error())
return nil, errors.New("failed to lookup SRV record").Base(err)
}
for _, txtRecord := range txtRecords {
errors.LogDebug(ctx, "TXT record: "+txtRecord)
addr_s, port_s, _ := net.SplitHostPort(string(txtRecord))
addr := net.ParseAddress(addr_s)
port, err := net.PortFromString(port_s)
if err != nil {
continue
}
if OverridePort {
newDest.Port = port
}
if OverrideAddress {
newDest.Address = addr
}
return &newDest, nil
}
}
return nil, nil
}
// DialSystem calls system dialer to create a network connection. // DialSystem calls system dialer to create a network connection.
func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig) (net.Conn, error) { func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig) (net.Conn, error) {
var src net.Address var src net.Address
@@ -152,6 +242,11 @@ func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig
return effectiveSystemDialer.Dial(ctx, src, dest, sockopt) return effectiveSystemDialer.Dial(ctx, src, dest, sockopt)
} }
if newDest, err := checkAddressPortStrategy(ctx, dest, sockopt); err == nil && newDest != nil {
errors.LogInfo(ctx, "replace destination with "+newDest.String())
dest = *newDest
}
if canLookupIP(ctx, dest, sockopt) { if canLookupIP(ctx, dest, sockopt) {
ips, err := lookupIP(dest.Address.String(), sockopt.DomainStrategy, src) ips, err := lookupIP(dest.Address.String(), sockopt.DomainStrategy, src)
if err == nil && len(ips) > 0 { if err == nil && len(ips) > 0 {

View File

@@ -8,7 +8,6 @@ import (
"crypto/ecdh" "crypto/ecdh"
"crypto/ed25519" "crypto/ed25519"
"crypto/hmac" "crypto/hmac"
"crypto/rand"
"crypto/sha256" "crypto/sha256"
"crypto/sha512" "crypto/sha512"
gotls "crypto/tls" gotls "crypto/tls"
@@ -16,7 +15,6 @@ import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io" "io"
"math/big"
"net/http" "net/http"
"reflect" "reflect"
"regexp" "regexp"
@@ -27,6 +25,7 @@ import (
utls "github.com/refraction-networking/utls" utls "github.com/refraction-networking/utls"
"github.com/xtls/reality" "github.com/xtls/reality"
"github.com/xtls/xray-core/common/crypto"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
"github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/common/net"
"github.com/xtls/xray-core/core" "github.com/xtls/xray-core/core"
@@ -213,13 +212,13 @@ func UClient(c net.Conn, config *Config, ctx context.Context, dest net.Destinati
} }
times := 1 times := 1
if !first { if !first {
times = int(randBetween(config.SpiderY[4], config.SpiderY[5])) times = int(crypto.RandBetween(config.SpiderY[4], config.SpiderY[5]))
} }
for j := 0; j < times; j++ { for j := 0; j < times; j++ {
if !first && j == 0 { if !first && j == 0 {
req.Header.Set("Referer", firstURL) req.Header.Set("Referer", firstURL)
} }
req.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", int(randBetween(config.SpiderY[0], config.SpiderY[1])))}) req.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", int(crypto.RandBetween(config.SpiderY[0], config.SpiderY[1])))})
if resp, err = client.Do(req); err != nil { if resp, err = client.Do(req); err != nil {
break break
} }
@@ -243,18 +242,18 @@ func UClient(c net.Conn, config *Config, ctx context.Context, dest net.Destinati
} }
maps.Unlock() maps.Unlock()
if !first { if !first {
time.Sleep(time.Duration(randBetween(config.SpiderY[6], config.SpiderY[7])) * time.Millisecond) // interval time.Sleep(time.Duration(crypto.RandBetween(config.SpiderY[6], config.SpiderY[7])) * time.Millisecond) // interval
} }
} }
} }
get(true) get(true)
concurrency := int(randBetween(config.SpiderY[2], config.SpiderY[3])) concurrency := int(crypto.RandBetween(config.SpiderY[2], config.SpiderY[3]))
for i := 0; i < concurrency; i++ { for i := 0; i < concurrency; i++ {
go get(false) go get(false)
} }
// Do not close the connection // Do not close the connection
}() }()
time.Sleep(time.Duration(randBetween(config.SpiderY[8], config.SpiderY[9])) * time.Millisecond) // return time.Sleep(time.Duration(crypto.RandBetween(config.SpiderY[8], config.SpiderY[9])) * time.Millisecond) // return
return nil, errors.New("REALITY: processed invalid connection").AtWarning() return nil, errors.New("REALITY: processed invalid connection").AtWarning()
} }
return uConn, nil return uConn, nil
@@ -271,7 +270,7 @@ var maps struct {
} }
func getPathLocked(paths map[string]struct{}) string { func getPathLocked(paths map[string]struct{}) string {
stopAt := int(randBetween(0, int64(len(paths)-1))) stopAt := int(crypto.RandBetween(0, int64(len(paths)-1)))
i := 0 i := 0
for s := range paths { for s := range paths {
if i == stopAt { if i == stopAt {
@@ -281,11 +280,3 @@ func getPathLocked(paths map[string]struct{}) string {
} }
return "/" return "/"
} }
func randBetween(left int64, right int64) int64 {
if left == right {
return left
}
bigInt, _ := rand.Int(rand.Reader, big.NewInt(right-left))
return left + bigInt.Int64()
}

View File

@@ -1,7 +1,7 @@
package internet package internet
import ( import (
network "net" gonet "net"
"os" "os"
"syscall" "syscall"
"unsafe" "unsafe"
@@ -108,13 +108,58 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
return err return err
} }
} }
if config.Interface != "" {
InterfaceIndex := getInterfaceIndexByName(config.Interface) if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 {
if InterfaceIndex != 0 { if config.TcpKeepAliveIdle > 0 {
if err := unix.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_BOUND_IF, InterfaceIndex); err != nil { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_KEEPALIVE, int(config.TcpKeepAliveInterval)); err != nil {
return errors.New("failed to set Interface").Base(err) return errors.New("failed to set TCP_KEEPINTVL", err)
} }
} }
if config.TcpKeepAliveInterval > 0 {
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, sysTCP_KEEPINTVL, int(config.TcpKeepAliveIdle)); err != nil {
return errors.New("failed to set TCP_KEEPIDLE", err)
}
}
if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1); err != nil {
return errors.New("failed to set SO_KEEPALIVE", err)
}
} else if config.TcpKeepAliveInterval < 0 || config.TcpKeepAliveIdle < 0 {
if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 0); err != nil {
return errors.New("failed to unset SO_KEEPALIVE", err)
}
}
}
if config.Interface != "" {
iface, err := gonet.InterfaceByName(config.Interface)
if err != nil {
return errors.New("failed to get interface ", config.Interface).Base(err)
}
if network == "tcp6" || network == "udp6" {
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, iface.Index); err != nil {
return errors.New("failed to set IPV6_BOUND_IF").Base(err)
}
} else {
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, iface.Index); err != nil {
return errors.New("failed to set IP_BOUND_IF").Base(err)
}
}
}
return nil
}
func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) error {
if isTCPSocket(network) {
tfo := config.ParseTFOValue()
if tfo > 0 {
tfo = TCP_FASTOPEN_SERVER
}
if tfo >= 0 {
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_FASTOPEN, tfo); err != nil {
return err
}
} }
if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 { if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 {
@@ -138,47 +183,26 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
} }
} }
return nil if config.Interface != "" {
} iface, err := gonet.InterfaceByName(config.Interface)
func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) error { if err != nil {
if isTCPSocket(network) { return errors.New("failed to get interface ", config.Interface).Base(err)
tfo := config.ParseTFOValue()
if tfo > 0 {
tfo = TCP_FASTOPEN_SERVER
} }
if tfo >= 0 { if network == "tcp6" || network == "udp6" {
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_FASTOPEN, tfo); err != nil { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, iface.Index); err != nil {
return err return errors.New("failed to set IPV6_BOUND_IF").Base(err)
} }
} } else {
if config.Interface != "" { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, iface.Index); err != nil {
InterfaceIndex := getInterfaceIndexByName(config.Interface) return errors.New("failed to set IP_BOUND_IF").Base(err)
if InterfaceIndex != 0 {
if err := unix.SetsockoptInt(int(fd), syscall.IPPROTO_IP, syscall.IP_BOUND_IF, InterfaceIndex); err != nil {
return errors.New("failed to set Interface").Base(err)
}
} }
} }
}
if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 { if config.V6Only {
if config.TcpKeepAliveIdle > 0 { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_V6ONLY, 1); err != nil {
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_KEEPALIVE, int(config.TcpKeepAliveInterval)); err != nil { return errors.New("failed to set IPV6_V6ONLY").Base(err)
return errors.New("failed to set TCP_KEEPINTVL", err)
}
}
if config.TcpKeepAliveInterval > 0 {
if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, sysTCP_KEEPINTVL, int(config.TcpKeepAliveIdle)); err != nil {
return errors.New("failed to set TCP_KEEPIDLE", err)
}
}
if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 1); err != nil {
return errors.New("failed to set SO_KEEPALIVE", err)
}
} else if config.TcpKeepAliveInterval < 0 || config.TcpKeepAliveIdle < 0 {
if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_KEEPALIVE, 0); err != nil {
return errors.New("failed to unset SO_KEEPALIVE", err)
}
} }
} }
@@ -224,24 +248,3 @@ func setReusePort(fd uintptr) error {
} }
return nil return nil
} }
func getInterfaceIndexByName(name string) int {
ifaces, err := network.Interfaces()
if err == nil {
for _, iface := range ifaces {
if (iface.Flags&network.FlagUp == network.FlagUp) && (iface.Flags&network.FlagLoopback != network.FlagLoopback) {
addrs, _ := iface.Addrs()
for _, addr := range addrs {
if ipnet, ok := addr.(*network.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
if iface.Name == name {
return iface.Index
}
}
}
}
}
}
}
return 0
}

View File

@@ -3,6 +3,7 @@ package internet
import ( import (
"net" "net"
"strconv" "strconv"
"strings"
"syscall" "syscall"
"github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/errors"
@@ -35,6 +36,8 @@ func bindAddr(fd uintptr, ip []byte, port uint32) error {
return syscall.Bind(int(fd), sockaddr) return syscall.Bind(int(fd), sockaddr)
} }
// applyOutboundSocketOptions applies socket options for outbound connection.
// note that unlike other part of Xray, this function needs network with speified network stack(tcp4/tcp6/udp4/udp6)
func applyOutboundSocketOptions(network string, address string, fd uintptr, config *SocketConfig) error { func applyOutboundSocketOptions(network string, address string, fd uintptr, config *SocketConfig) error {
if config.Mark != 0 { if config.Mark != 0 {
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, int(config.Mark)); err != nil { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, int(config.Mark)); err != nil {
@@ -103,30 +106,38 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
} }
} }
if len(config.CustomSockopt) > 0 { }
for _, custom := range config.CustomSockopt {
var level = 0x6 // default TCP if len(config.CustomSockopt) > 0 {
var opt int for _, custom := range config.CustomSockopt {
if len(custom.Opt) == 0 { // Skip unwanted network type
return errors.New("No opt!") // network might be tcp4 or tcp6
} else { // use HasPrefix so that "tcp" can match tcp4/6 with "tcp" if user want to control all tcp (udp is also the same)
opt, _ = strconv.Atoi(custom.Opt) // if it is empty, strings.HasPrefix will always return true to make it apply for all networks
if !strings.HasPrefix(network, custom.Network) {
continue
}
var level = 0x6 // default TCP
var opt int
if len(custom.Opt) == 0 {
return errors.New("No opt!")
} else {
opt, _ = strconv.Atoi(custom.Opt)
}
if custom.Level != "" {
level, _ = strconv.Atoi(custom.Level)
}
if custom.Type == "int" {
value, _ := strconv.Atoi(custom.Value)
if err := syscall.SetsockoptInt(int(fd), level, opt, value); err != nil {
return errors.New("failed to set CustomSockoptInt", opt, value, err)
} }
if custom.Level != "" { } else if custom.Type == "str" {
level, _ = strconv.Atoi(custom.Level) if err := syscall.SetsockoptString(int(fd), level, opt, custom.Value); err != nil {
} return errors.New("failed to set CustomSockoptString", opt, custom.Value, err)
if custom.Type == "int" {
value, _ := strconv.Atoi(custom.Value)
if err := syscall.SetsockoptInt(int(fd), level, opt, value); err != nil {
return errors.New("failed to set CustomSockoptInt", opt, value, err)
}
} else if custom.Type == "str" {
if err := syscall.SetsockoptString(int(fd), level, opt, custom.Value); err != nil {
return errors.New("failed to set CustomSockoptString", opt, custom.Value, err)
}
} else {
return errors.New("unknown CustomSockopt type:", custom.Type)
} }
} else {
return errors.New("unknown CustomSockopt type:", custom.Type)
} }
} }
} }
@@ -140,6 +151,8 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
return nil return nil
} }
// applyInboundSocketOptions applies socket options for inbound listener.
// note that unlike other part of Xray, this function needs network with speified network stack(tcp4/tcp6/udp4/udp6)
func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) error { func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) error {
if config.Mark != 0 { if config.Mark != 0 {
if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, int(config.Mark)); err != nil { if err := syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, syscall.SO_MARK, int(config.Mark)); err != nil {

View File

@@ -13,6 +13,9 @@ const (
TCP_FASTOPEN = 15 TCP_FASTOPEN = 15
IP_UNICAST_IF = 31 IP_UNICAST_IF = 31
IPV6_UNICAST_IF = 31 IPV6_UNICAST_IF = 31
IP_MULTICAST_IF = 9
IPV6_MULTICAST_IF = 9
IPV6_V6ONLY = 27
) )
func setTFO(fd syscall.Handle, tfo int) error { func setTFO(fd syscall.Handle, tfo int) error {
@@ -33,7 +36,7 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
if err != nil { if err != nil {
return errors.New("failed to find the interface").Base(err) return errors.New("failed to find the interface").Base(err)
} }
isV4 := (network == "tcp4") isV4 := (network == "tcp4" || network == "udp4")
if isV4 { if isV4 {
var bytes [4]byte var bytes [4]byte
binary.BigEndian.PutUint32(bytes[:], uint32(inf.Index)) binary.BigEndian.PutUint32(bytes[:], uint32(inf.Index))
@@ -41,10 +44,16 @@ func applyOutboundSocketOptions(network string, address string, fd uintptr, conf
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, IP_UNICAST_IF, int(idx)); err != nil { if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, IP_UNICAST_IF, int(idx)); err != nil {
return errors.New("failed to set IP_UNICAST_IF").Base(err) return errors.New("failed to set IP_UNICAST_IF").Base(err)
} }
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IP, IP_MULTICAST_IF, int(idx)); err != nil {
return errors.New("failed to set IP_MULTICAST_IF").Base(err)
}
} else { } else {
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IPV6, IPV6_UNICAST_IF, inf.Index); err != nil { if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IPV6, IPV6_UNICAST_IF, inf.Index); err != nil {
return errors.New("failed to set IPV6_UNICAST_IF").Base(err) return errors.New("failed to set IPV6_UNICAST_IF").Base(err)
} }
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IPV6, IPV6_MULTICAST_IF, inf.Index); err != nil {
return errors.New("failed to set IPV6_MULTICAST_IF").Base(err)
}
} }
} }
@@ -82,6 +91,12 @@ func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig)
} }
} }
if config.V6Only {
if err := syscall.SetsockoptInt(syscall.Handle(fd), syscall.IPPROTO_IPV6, IPV6_V6ONLY, 1); err != nil {
return errors.New("failed to set IPV6_V6ONLY").Base(err)
}
}
return nil return nil
} }

View File

@@ -1,13 +1,12 @@
package splithttp package splithttp
import ( import (
"crypto/rand"
"math/big"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"github.com/xtls/xray-core/common" "github.com/xtls/xray-core/common"
"github.com/xtls/xray-core/common/crypto"
"github.com/xtls/xray-core/transport/internet" "github.com/xtls/xray-core/transport/internet"
) )
@@ -184,9 +183,5 @@ func init() {
} }
func (c RangeConfig) rand() int32 { func (c RangeConfig) rand() int32 {
if c.From == c.To { return int32(crypto.RandBetween(int64(c.From), int64(c.To)))
return c.From
}
bigInt, _ := rand.Int(rand.Reader, big.NewInt(int64(c.To-c.From)))
return c.From + int32(bigInt.Int64())
} }

View File

@@ -30,16 +30,6 @@ import (
"golang.org/x/net/http2" "golang.org/x/net/http2"
) )
// defines the maximum time an idle TCP session can survive in the tunnel, so
// it should be consistent across HTTP versions and with other transports.
const connIdleTimeout = 300 * time.Second
// consistent with quic-go
const quicgoH3KeepAlivePeriod = 10 * time.Second
// consistent with chrome
const chromeH2KeepAlivePeriod = 45 * time.Second
type dialerConf struct { type dialerConf struct {
net.Destination net.Destination
*internet.MemoryStreamConfig *internet.MemoryStreamConfig
@@ -154,13 +144,13 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
if httpVersion == "3" { if httpVersion == "3" {
if keepAlivePeriod == 0 { if keepAlivePeriod == 0 {
keepAlivePeriod = quicgoH3KeepAlivePeriod keepAlivePeriod = net.QuicgoH3KeepAlivePeriod
} }
if keepAlivePeriod < 0 { if keepAlivePeriod < 0 {
keepAlivePeriod = 0 keepAlivePeriod = 0
} }
quicConfig := &quic.Config{ quicConfig := &quic.Config{
MaxIdleTimeout: connIdleTimeout, MaxIdleTimeout: net.ConnIdleTimeout,
// these two are defaults of quic-go/http3. the default of quic-go (no // these two are defaults of quic-go/http3. the default of quic-go (no
// http3) is different, so it is hardcoded here for clarity. // http3) is different, so it is hardcoded here for clarity.
@@ -168,7 +158,7 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
MaxIncomingStreams: -1, MaxIncomingStreams: -1,
KeepAlivePeriod: keepAlivePeriod, KeepAlivePeriod: keepAlivePeriod,
} }
transport = &http3.RoundTripper{ transport = &http3.Transport{
QUICConfig: quicConfig, QUICConfig: quicConfig,
TLSClientConfig: gotlsConfig, TLSClientConfig: gotlsConfig,
Dial: func(ctx context.Context, addr string, tlsCfg *gotls.Config, cfg *quic.Config) (quic.EarlyConnection, error) { Dial: func(ctx context.Context, addr string, tlsCfg *gotls.Config, cfg *quic.Config) (quic.EarlyConnection, error) {
@@ -198,7 +188,7 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
return nil, err return nil, err
} }
default: default:
udpConn = &internet.FakePacketConn{c} udpConn = &internet.FakePacketConn{Conn: c}
udpAddr, err = net.ResolveUDPAddr("udp", c.RemoteAddr().String()) udpAddr, err = net.ResolveUDPAddr("udp", c.RemoteAddr().String())
if err != nil { if err != nil {
return nil, err return nil, err
@@ -210,7 +200,7 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
} }
} else if httpVersion == "2" { } else if httpVersion == "2" {
if keepAlivePeriod == 0 { if keepAlivePeriod == 0 {
keepAlivePeriod = chromeH2KeepAlivePeriod keepAlivePeriod = net.ChromeH2KeepAlivePeriod
} }
if keepAlivePeriod < 0 { if keepAlivePeriod < 0 {
keepAlivePeriod = 0 keepAlivePeriod = 0
@@ -219,7 +209,7 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
DialTLSContext: func(ctxInner context.Context, network string, addr string, cfg *gotls.Config) (net.Conn, error) { DialTLSContext: func(ctxInner context.Context, network string, addr string, cfg *gotls.Config) (net.Conn, error) {
return dialContext(ctxInner) return dialContext(ctxInner)
}, },
IdleConnTimeout: connIdleTimeout, IdleConnTimeout: net.ConnIdleTimeout,
ReadIdleTimeout: keepAlivePeriod, ReadIdleTimeout: keepAlivePeriod,
} }
} else { } else {
@@ -230,7 +220,7 @@ func createHTTPClient(dest net.Destination, streamSettings *internet.MemoryStrea
transport = &http.Transport{ transport = &http.Transport{
DialTLSContext: httpDialContext, DialTLSContext: httpDialContext,
DialContext: httpDialContext, DialContext: httpDialContext,
IdleConnTimeout: connIdleTimeout, IdleConnTimeout: net.ConnIdleTimeout,
// chunked transfer download with KeepAlives is buggy with // chunked transfer download with KeepAlives is buggy with
// http.Client and our custom dial context. // http.Client and our custom dial context.
DisableKeepAlives: true, DisableKeepAlives: true,

View File

@@ -24,8 +24,6 @@ import (
"github.com/xtls/xray-core/transport/internet/reality" "github.com/xtls/xray-core/transport/internet/reality"
"github.com/xtls/xray-core/transport/internet/stat" "github.com/xtls/xray-core/transport/internet/stat"
"github.com/xtls/xray-core/transport/internet/tls" "github.com/xtls/xray-core/transport/internet/tls"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
) )
type requestHandler struct { type requestHandler struct {
@@ -47,21 +45,6 @@ type httpSession struct {
isFullyConnected *done.Instance isFullyConnected *done.Instance
} }
func (h *requestHandler) maybeReapSession(isFullyConnected *done.Instance, sessionId string) {
shouldReap := done.New()
go func() {
time.Sleep(30 * time.Second)
shouldReap.Close()
}()
select {
case <-isFullyConnected.Wait():
return
case <-shouldReap.Wait():
h.sessions.Delete(sessionId)
}
}
func (h *requestHandler) upsertSession(sessionId string) *httpSession { func (h *requestHandler) upsertSession(sessionId string) *httpSession {
// fast path // fast path
currentSessionAny, ok := h.sessions.Load(sessionId) currentSessionAny, ok := h.sessions.Load(sessionId)
@@ -84,7 +67,21 @@ func (h *requestHandler) upsertSession(sessionId string) *httpSession {
} }
h.sessions.Store(sessionId, s) h.sessions.Store(sessionId, s)
go h.maybeReapSession(s.isFullyConnected, sessionId)
shouldReap := done.New()
go func() {
time.Sleep(30 * time.Second)
shouldReap.Close()
}()
go func() {
select {
case <-shouldReap.Wait():
h.sessions.Delete(sessionId)
s.uploadQueue.Close()
case <-s.isFullyConnected.Wait():
}
}()
return s return s
} }
@@ -183,12 +180,13 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
writer.WriteHeader(http.StatusBadRequest) writer.WriteHeader(http.StatusBadRequest)
return return
} }
uploadDone := done.New() httpSC := &httpServerConn{
Instance: done.New(),
Reader: request.Body,
ResponseWriter: writer,
}
err = currentSession.uploadQueue.Push(Packet{ err = currentSession.uploadQueue.Push(Packet{
Reader: &httpRequestBodyReader{ Reader: httpSC,
requestReader: request.Body,
uploadDone: uploadDone,
},
}) })
if err != nil { if err != nil {
errors.LogInfoInner(context.Background(), err, "failed to upload (PushReader)") errors.LogInfoInner(context.Background(), err, "failed to upload (PushReader)")
@@ -200,25 +198,21 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs() scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs()
if referrer != "" && scStreamUpServerSecs.To > 0 { if referrer != "" && scStreamUpServerSecs.To > 0 {
go func() { go func() {
defer func() {
recover()
}()
for { for {
_, err := writer.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand()))) _, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand())))
if err != nil { if err != nil {
break break
} }
writer.(http.Flusher).Flush()
time.Sleep(time.Duration(scStreamUpServerSecs.rand()) * time.Second) time.Sleep(time.Duration(scStreamUpServerSecs.rand()) * time.Second)
} }
}() }()
} }
select { select {
case <-request.Context().Done(): case <-request.Context().Done():
case <-uploadDone.Wait(): case <-httpSC.Wait():
} }
} }
uploadDone.Close() httpSC.Close()
return return
} }
@@ -262,11 +256,6 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
writer.WriteHeader(http.StatusOK) writer.WriteHeader(http.StatusOK)
} else if request.Method == "GET" || sessionId == "" { // stream-down, stream-one } else if request.Method == "GET" || sessionId == "" { // stream-down, stream-one
responseFlusher, ok := writer.(http.Flusher)
if !ok {
panic("expected http.ResponseWriter to be an http.Flusher")
}
if sessionId != "" { if sessionId != "" {
// after GET is done, the connection is finished. disable automatic // after GET is done, the connection is finished. disable automatic
// session reaping, and handle it in defer // session reaping, and handle it in defer
@@ -287,20 +276,18 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
} }
writer.WriteHeader(http.StatusOK) writer.WriteHeader(http.StatusOK)
writer.(http.Flusher).Flush()
responseFlusher.Flush() httpSC := &httpServerConn{
Instance: done.New(),
downloadDone := done.New() Reader: request.Body,
ResponseWriter: writer,
}
conn := splitConn{ conn := splitConn{
writer: &httpResponseBodyWriter{ writer: httpSC,
responseWriter: writer, reader: httpSC,
downloadDone: downloadDone,
responseFlusher: responseFlusher,
},
reader: request.Body,
localAddr: h.localAddr,
remoteAddr: remoteAddr, remoteAddr: remoteAddr,
localAddr: h.localAddr,
} }
if sessionId != "" { // if not stream-one if sessionId != "" { // if not stream-one
conn.reader = currentSession.uploadQueue conn.reader = currentSession.uploadQueue
@@ -311,7 +298,7 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
// "A ResponseWriter may not be used after [Handler.ServeHTTP] has returned." // "A ResponseWriter may not be used after [Handler.ServeHTTP] has returned."
select { select {
case <-request.Context().Done(): case <-request.Context().Done():
case <-downloadDone.Wait(): case <-httpSC.Wait():
} }
conn.Close() conn.Close()
@@ -321,45 +308,30 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
} }
} }
type httpRequestBodyReader struct { type httpServerConn struct {
requestReader io.ReadCloser
uploadDone *done.Instance
}
func (c *httpRequestBodyReader) Read(b []byte) (int, error) {
return c.requestReader.Read(b)
}
func (c *httpRequestBodyReader) Close() error {
defer c.uploadDone.Close()
return c.requestReader.Close()
}
type httpResponseBodyWriter struct {
sync.Mutex sync.Mutex
responseWriter http.ResponseWriter *done.Instance
responseFlusher http.Flusher io.Reader // no need to Close request.Body
downloadDone *done.Instance http.ResponseWriter
} }
func (c *httpResponseBodyWriter) Write(b []byte) (int, error) { func (c *httpServerConn) Write(b []byte) (int, error) {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
if c.downloadDone.Done() { if c.Done() {
return 0, io.ErrClosedPipe return 0, io.ErrClosedPipe
} }
n, err := c.responseWriter.Write(b) n, err := c.ResponseWriter.Write(b)
if err == nil { if err == nil {
c.responseFlusher.Flush() c.ResponseWriter.(http.Flusher).Flush()
} }
return n, err return n, err
} }
func (c *httpResponseBodyWriter) Close() error { func (c *httpServerConn) Close() error {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
c.downloadDone.Close() return c.Instance.Close()
return nil
} }
type Listener struct { type Listener struct {
@@ -452,11 +424,15 @@ func ListenXH(ctx context.Context, address net.Address, port net.Port, streamSet
handler.localAddr = l.listener.Addr() handler.localAddr = l.listener.Addr()
// h2cHandler can handle both plaintext HTTP/1.1 and h2c // server can handle both plaintext HTTP/1.1 and h2c
protocols := new(http.Protocols)
protocols.SetHTTP1(true)
protocols.SetUnencryptedHTTP2(true)
l.server = http.Server{ l.server = http.Server{
Handler: h2c.NewHandler(handler, &http2.Server{}), Handler: handler,
ReadHeaderTimeout: time.Second * 4, ReadHeaderTimeout: time.Second * 4,
MaxHeaderBytes: 8192, MaxHeaderBytes: 8192,
Protocols: protocols,
} }
go func() { go func() {
if err := l.server.Serve(l.listener); err != nil { if err := l.server.Serve(l.listener); err != nil {

View File

@@ -3,10 +3,8 @@ package splithttp_test
import ( import (
"context" "context"
"crypto/rand" "crypto/rand"
gotls "crypto/tls"
"fmt" "fmt"
"io" "io"
gonet "net"
"net/http" "net/http"
"runtime" "runtime"
"testing" "testing"
@@ -23,7 +21,6 @@ import (
. "github.com/xtls/xray-core/transport/internet/splithttp" . "github.com/xtls/xray-core/transport/internet/splithttp"
"github.com/xtls/xray-core/transport/internet/stat" "github.com/xtls/xray-core/transport/internet/stat"
"github.com/xtls/xray-core/transport/internet/tls" "github.com/xtls/xray-core/transport/internet/tls"
"golang.org/x/net/http2"
) )
func Test_ListenXHAndDial(t *testing.T) { func Test_ListenXHAndDial(t *testing.T) {
@@ -201,17 +198,11 @@ func Test_ListenXHAndDial_H2C(t *testing.T) {
common.Must(err) common.Must(err)
defer listen.Close() defer listen.Close()
protocols := new(http.Protocols)
protocols.SetUnencryptedHTTP2(true)
client := http.Client{ client := http.Client{
Transport: &http2.Transport{ Transport: &http.Transport{
// So http2.Transport doesn't complain the URL scheme isn't 'https' Protocols: protocols,
AllowHTTP: true,
// even with AllowHTTP, http2.Transport will attempt to establish
// the connection using DialTLSContext. Disable TLS with custom
// dial context.
DialTLSContext: func(ctx context.Context, network, addr string, cfg *gotls.Config) (gonet.Conn, error) {
var d gonet.Dialer
return d.DialContext(ctx, network, addr)
},
}, },
} }

View File

@@ -20,6 +20,7 @@ type Packet struct {
type uploadQueue struct { type uploadQueue struct {
reader io.ReadCloser reader io.ReadCloser
nomore bool
pushedPackets chan Packet pushedPackets chan Packet
writeCloseMutex sync.Mutex writeCloseMutex sync.Mutex
heap uploadHeap heap uploadHeap
@@ -42,19 +43,15 @@ func (h *uploadQueue) Push(p Packet) error {
h.writeCloseMutex.Lock() h.writeCloseMutex.Lock()
defer h.writeCloseMutex.Unlock() defer h.writeCloseMutex.Unlock()
runtime.Gosched()
if h.reader != nil && p.Reader != nil {
p.Reader.Close()
return errors.New("h.reader already exists")
}
if h.closed { if h.closed {
if p.Reader != nil {
p.Reader.Close()
}
return errors.New("packet queue closed") return errors.New("packet queue closed")
} }
if h.nomore {
return errors.New("h.reader already exists")
}
if p.Reader != nil {
h.nomore = true
}
h.pushedPackets <- p h.pushedPackets <- p
return nil return nil
} }
@@ -65,9 +62,20 @@ func (h *uploadQueue) Close() error {
if !h.closed { if !h.closed {
h.closed = true h.closed = true
runtime.Gosched() // hope Read() gets the packet
f:
for {
select {
case p := <-h.pushedPackets:
if p.Reader != nil {
h.reader = p.Reader
}
default:
break f
}
}
close(h.pushedPackets) close(h.pushedPackets)
} }
runtime.Gosched()
if h.reader != nil { if h.reader != nil {
return h.reader.Close() return h.reader.Close()
} }

View File

@@ -59,7 +59,17 @@ func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest ne
Port: 0, Port: 0,
} }
} }
packetConn, err := ListenSystemPacket(ctx, srcAddr, sockopt) var lc net.ListenConfig
lc.Control = func(network, address string, c syscall.RawConn) error {
return c.Control(func(fd uintptr) {
if sockopt != nil {
if err := applyOutboundSocketOptions(network, "", fd, sockopt); err != nil {
errors.LogInfo(ctx, err, "failed to apply socket options")
}
}
})
}
packetConn, err := lc.ListenPacket(ctx, srcAddr.Network(), srcAddr.String())
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -67,17 +77,6 @@ func (d *DefaultSystemDialer) Dial(ctx context.Context, src net.Address, dest ne
if err != nil { if err != nil {
return nil, err return nil, err
} }
if sockopt != nil {
sys, err := packetConn.(*net.UDPConn).SyscallConn()
if err != nil {
return nil, err
}
sys.Control(func(fd uintptr) {
if err := applyOutboundSocketOptions("udp", dest.NetAddr(), fd, sockopt); err != nil {
errors.LogInfo(ctx, err, "failed to apply socket options")
}
})
}
return &PacketConnWrapper{ return &PacketConnWrapper{
Conn: packetConn, Conn: packetConn,
Dest: destAddr, Dest: destAddr,

View File

@@ -44,32 +44,32 @@ func getControlFunc(ctx context.Context, sockopt *SocketConfig, controllers []co
// For some reason, other component of ray will assume the listener is a TCP listener and have valid remote address. // For some reason, other component of ray will assume the listener is a TCP listener and have valid remote address.
// But in fact it doesn't. So we need to wrap the listener to make it return 0.0.0.0(unspecified) as remote address. // But in fact it doesn't. So we need to wrap the listener to make it return 0.0.0.0(unspecified) as remote address.
// If other issues encountered, we should able to fix it here. // If other issues encountered, we should able to fix it here.
type listenUDSWrapper struct { type UnixListenerWrapper struct {
net.Listener *net.UnixListener
locker *FileLocker locker *FileLocker
} }
func (l *listenUDSWrapper) Accept() (net.Conn, error) { func (l *UnixListenerWrapper) Accept() (net.Conn, error) {
conn, err := l.Listener.Accept() conn, err := l.UnixListener.Accept()
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &UDSWrapperConn{Conn: conn}, nil return &UnixConnWrapper{UnixConn: conn.(*net.UnixConn)}, nil
} }
func (l *listenUDSWrapper) Close() error { func (l *UnixListenerWrapper) Close() error {
if l.locker != nil { if l.locker != nil {
l.locker.Release() l.locker.Release()
l.locker = nil l.locker = nil
} }
return l.Listener.Close() return l.UnixListener.Close()
} }
type UDSWrapperConn struct { type UnixConnWrapper struct {
net.Conn *net.UnixConn
} }
func (conn *UDSWrapperConn) RemoteAddr() net.Addr { func (conn *UnixConnWrapper) RemoteAddr() net.Addr {
return &net.TCPAddr{ return &net.TCPAddr{
IP: []byte{0, 0, 0, 0}, IP: []byte{0, 0, 0, 0},
} }
@@ -136,7 +136,7 @@ func (dl *DefaultListener) Listen(ctx context.Context, addr net.Addr, sockopt *S
locker.Release() locker.Release()
return nil, err return nil, err
} }
l = &listenUDSWrapper{Listener: l, locker: locker} l = &UnixListenerWrapper{UnixListener: l.(*net.UnixListener), locker: locker}
if filePerm == nil { if filePerm == nil {
return l, nil return l, nil
} }

View File

@@ -109,12 +109,12 @@ func setupOcspTicker(entry *Certificate, callback func(isReloaded, isOcspstaplin
for { for {
var isReloaded bool var isReloaded bool
if entry.CertificatePath != "" && entry.KeyPath != "" { if entry.CertificatePath != "" && entry.KeyPath != "" {
newCert, err := filesystem.ReadFile(entry.CertificatePath) newCert, err := filesystem.ReadCert(entry.CertificatePath)
if err != nil { if err != nil {
errors.LogErrorInner(context.Background(), err, "failed to parse certificate") errors.LogErrorInner(context.Background(), err, "failed to parse certificate")
return return
} }
newKey, err := filesystem.ReadFile(entry.KeyPath) newKey, err := filesystem.ReadCert(entry.KeyPath)
if err != nil { if err != nil {
errors.LogErrorInner(context.Background(), err, "failed to parse key") errors.LogErrorInner(context.Background(), err, "failed to parse key")
return return

View File

@@ -207,7 +207,7 @@ type Config struct {
// @Critical // @Critical
PinnedPeerCertificateChainSha256 [][]byte `protobuf:"bytes,13,rep,name=pinned_peer_certificate_chain_sha256,json=pinnedPeerCertificateChainSha256,proto3" json:"pinned_peer_certificate_chain_sha256,omitempty"` PinnedPeerCertificateChainSha256 [][]byte `protobuf:"bytes,13,rep,name=pinned_peer_certificate_chain_sha256,json=pinnedPeerCertificateChainSha256,proto3" json:"pinned_peer_certificate_chain_sha256,omitempty"`
// @Document Some certificate public key sha256 hashes. // @Document Some certificate public key sha256 hashes.
// @Document After normal validation (required), if the verified cert's public key hash does not match any of these values, the connection will be aborted. // @Document After normal validation (required), if one of certs in verified chain matches one of these values, the connection will be eventually accepted.
// @Critical // @Critical
PinnedPeerCertificatePublicKeySha256 [][]byte `protobuf:"bytes,14,rep,name=pinned_peer_certificate_public_key_sha256,json=pinnedPeerCertificatePublicKeySha256,proto3" json:"pinned_peer_certificate_public_key_sha256,omitempty"` PinnedPeerCertificatePublicKeySha256 [][]byte `protobuf:"bytes,14,rep,name=pinned_peer_certificate_public_key_sha256,json=pinnedPeerCertificatePublicKeySha256,proto3" json:"pinned_peer_certificate_public_key_sha256,omitempty"`
MasterKeyLog string `protobuf:"bytes,15,opt,name=master_key_log,json=masterKeyLog,proto3" json:"master_key_log,omitempty"` MasterKeyLog string `protobuf:"bytes,15,opt,name=master_key_log,json=masterKeyLog,proto3" json:"master_key_log,omitempty"`

View File

@@ -76,7 +76,7 @@ message Config {
repeated bytes pinned_peer_certificate_chain_sha256 = 13; repeated bytes pinned_peer_certificate_chain_sha256 = 13;
/* @Document Some certificate public key sha256 hashes. /* @Document Some certificate public key sha256 hashes.
@Document After normal validation (required), if the verified cert's public key hash does not match any of these values, the connection will be aborted. @Document After normal validation (required), if one of certs in verified chain matches one of these values, the connection will be eventually accepted.
@Critical @Critical
*/ */
repeated bytes pinned_peer_certificate_public_key_sha256 = 14; repeated bytes pinned_peer_certificate_public_key_sha256 = 14;

View File

@@ -151,10 +151,14 @@ func init() {
weights := utls.DefaultWeights weights := utls.DefaultWeights
weights.TLSVersMax_Set_VersionTLS13 = 1 weights.TLSVersMax_Set_VersionTLS13 = 1
weights.FirstKeyShare_Set_CurveP256 = 0 weights.FirstKeyShare_Set_CurveP256 = 0
randomized := utls.HelloRandomized randomized := utls.HelloRandomizedALPN
randomized.Seed, _ = utls.NewPRNGSeed() randomized.Seed, _ = utls.NewPRNGSeed()
randomized.Weights = &weights randomized.Weights = &weights
randomizednoalpn := utls.HelloRandomizedNoALPN
randomizednoalpn.Seed, _ = utls.NewPRNGSeed()
randomizednoalpn.Weights = &weights
PresetFingerprints["randomized"] = &randomized PresetFingerprints["randomized"] = &randomized
PresetFingerprints["randomizednoalpn"] = &randomizednoalpn
} }
func GetFingerprint(name string) (fingerprint *utls.ClientHelloID) { func GetFingerprint(name string) (fingerprint *utls.ClientHelloID) {
@@ -175,17 +179,18 @@ func GetFingerprint(name string) (fingerprint *utls.ClientHelloID) {
var PresetFingerprints = map[string]*utls.ClientHelloID{ var PresetFingerprints = map[string]*utls.ClientHelloID{
// Recommended preset options in GUI clients // Recommended preset options in GUI clients
"chrome": &utls.HelloChrome_Auto, "chrome": &utls.HelloChrome_Auto,
"firefox": &utls.HelloFirefox_Auto, "firefox": &utls.HelloFirefox_Auto,
"safari": &utls.HelloSafari_Auto, "safari": &utls.HelloSafari_Auto,
"ios": &utls.HelloIOS_Auto, "ios": &utls.HelloIOS_Auto,
"android": &utls.HelloAndroid_11_OkHttp, "android": &utls.HelloAndroid_11_OkHttp,
"edge": &utls.HelloEdge_Auto, "edge": &utls.HelloEdge_Auto,
"360": &utls.Hello360_Auto, "360": &utls.Hello360_Auto,
"qq": &utls.HelloQQ_Auto, "qq": &utls.HelloQQ_Auto,
"random": nil, "random": nil,
"randomized": nil, "randomized": nil,
"unsafe": nil, "randomizednoalpn": nil,
"unsafe": nil,
} }
var ModernFingerprints = map[string]*utls.ClientHelloID{ var ModernFingerprints = map[string]*utls.ClientHelloID{
@@ -193,12 +198,14 @@ var ModernFingerprints = map[string]*utls.ClientHelloID{
"hellofirefox_99": &utls.HelloFirefox_99, "hellofirefox_99": &utls.HelloFirefox_99,
"hellofirefox_102": &utls.HelloFirefox_102, "hellofirefox_102": &utls.HelloFirefox_102,
"hellofirefox_105": &utls.HelloFirefox_105, "hellofirefox_105": &utls.HelloFirefox_105,
"hellofirefox_120": &utls.HelloFirefox_120,
"hellochrome_83": &utls.HelloChrome_83, "hellochrome_83": &utls.HelloChrome_83,
"hellochrome_87": &utls.HelloChrome_87, "hellochrome_87": &utls.HelloChrome_87,
"hellochrome_96": &utls.HelloChrome_96, "hellochrome_96": &utls.HelloChrome_96,
"hellochrome_100": &utls.HelloChrome_100, "hellochrome_100": &utls.HelloChrome_100,
"hellochrome_102": &utls.HelloChrome_102, "hellochrome_102": &utls.HelloChrome_102,
"hellochrome_106_shuffle": &utls.HelloChrome_106_Shuffle, "hellochrome_106_shuffle": &utls.HelloChrome_106_Shuffle,
"hellochrome_120": &utls.HelloChrome_120,
"helloios_13": &utls.HelloIOS_13, "helloios_13": &utls.HelloIOS_13,
"helloios_14": &utls.HelloIOS_14, "helloios_14": &utls.HelloIOS_14,
"helloedge_85": &utls.HelloEdge_85, "helloedge_85": &utls.HelloEdge_85,