mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-10-02 20:08:12 +03:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d1d8200d9 | ||
|
|
2440f53cdd | ||
|
|
1c52c65872 | ||
|
|
5724db08f4 | ||
|
|
3d3306503d | ||
|
|
5e1bb92b98 | ||
|
|
459301d42e | ||
|
|
3982028a9c | ||
|
|
70b8e9a61d | ||
|
|
219f758060 | ||
|
|
9628003594 | ||
|
|
72d9ab50b9 | ||
|
|
235843c5d2 | ||
|
|
60e2a0c502 | ||
|
|
7d3e44fee2 | ||
|
|
9927942aaa | ||
|
|
a308ded2e6 | ||
|
|
7741e9e77e | ||
|
|
d562d8947d | ||
|
|
dbb1ea30ba | ||
|
|
efc9e6da62 | ||
|
|
8267cf953a | ||
|
|
24e6f6d551 | ||
|
|
dcdfc57ccd | ||
|
|
3461c511aa | ||
|
|
c412e77a9b | ||
|
|
ccb69ea5e2 | ||
|
|
52a412d9e2 | ||
|
|
18a1b5042a | ||
|
|
c26d2eda24 | ||
|
|
a1bf968be9 | ||
|
|
c037ccd98d | ||
|
|
37ceb8b4b6 | ||
|
|
fd2ca74822 | ||
|
|
47cfe9994a | ||
|
|
3e2f040cd8 | ||
|
|
c7245c0336 | ||
|
|
eef6e63bc1 | ||
|
|
6ce8dc53e7 | ||
|
|
01a034be53 | ||
|
|
de2caf3cef | ||
|
|
cecc88f43c | ||
|
|
cd4ce973e9 | ||
|
|
fc7b980636 | ||
|
|
8ee131cbbb | ||
|
|
2776ea6d74 | ||
|
|
5e245b082e | ||
|
|
d9c54026c5 | ||
|
|
c1958dba04 | ||
|
|
540b9070f5 | ||
|
|
ada99a4eb0 | ||
|
|
65458e919f | ||
|
|
aa3d6589da | ||
|
|
25c11e2d2b | ||
|
|
dffc7ada5e | ||
|
|
77f98eba09 | ||
|
|
f124daf5a3 | ||
|
|
598bde7412 | ||
|
|
9b373e39ca | ||
|
|
c7e569b037 | ||
|
|
f02a357861 | ||
|
|
5fe6d6217a | ||
|
|
0604ffa957 | ||
|
|
d3f1a24285 | ||
|
|
2323273e37 | ||
|
|
09107b71dc | ||
|
|
7021606ad3 | ||
|
|
7d214f8b09 | ||
|
|
8b419d833d | ||
|
|
a12801c13b | ||
|
|
a000371b2a | ||
|
|
bc6e966af8 | ||
|
|
fc5620de98 | ||
|
|
b02bdcf4cc | ||
|
|
2b329b3675 | ||
|
|
5ca6f4b7d4 | ||
|
|
18e283909c | ||
|
|
6ab123bf8f | ||
|
|
4aba687dd3 | ||
|
|
5b1b41058e | ||
|
|
6e3322d219 | ||
|
|
1d8eb81d70 | ||
|
|
e78d8ef184 | ||
|
|
6ce924ad56 | ||
|
|
035d438979 | ||
|
|
50231eaff9 | ||
|
|
1f74c480d6 | ||
|
|
af7eb68028 | ||
|
|
35387572e0 | ||
|
|
8f15190c23 | ||
|
|
64fada32b5 | ||
|
|
0bafca9486 | ||
|
|
d5bc58dc6b | ||
|
|
c18b39ed80 | ||
|
|
e2ad0acf60 | ||
|
|
c320e89108 | ||
|
|
412898fed7 | ||
|
|
5c62d50d43 | ||
|
|
1aabe7ea78 | ||
|
|
e4e7614c62 | ||
|
|
987290ba48 | ||
|
|
d7fa2076c3 | ||
|
|
fb548f54d2 | ||
|
|
0495b17650 | ||
|
|
65f6f0a43b | ||
|
|
3263ae9255 | ||
|
|
3dc8bf3d8b | ||
|
|
695e68ef9e | ||
|
|
dfdbcf86cc | ||
|
|
2b828b7bc2 | ||
|
|
45cf2898ab | ||
|
|
18b85adb4e | ||
|
|
452b719504 | ||
|
|
345c76f9a8 | ||
|
|
f496437b84 | ||
|
|
b12bc504c8 | ||
|
|
dda2b10c9d | ||
|
|
241aa38ac0 | ||
|
|
7e7e820763 | ||
|
|
f9eb1597ad | ||
|
|
ac04c445bd | ||
|
|
e7e9254630 | ||
|
|
fab4bcc1ed | ||
|
|
b99c3e5657 | ||
|
|
583bb4a63f | ||
|
|
9cd9382e3d | ||
|
|
567500c4af | ||
|
|
5aefcb41fb | ||
|
|
be8009c625 | ||
|
|
8734774e4a | ||
|
|
1e036ce1c5 | ||
|
|
c815c2f2df | ||
|
|
986c512e0f | ||
|
|
711aea4e34 | ||
|
|
6412738486 | ||
|
|
ad2e4cb0e1 | ||
|
|
829d54d7be | ||
|
|
862631172d | ||
|
|
d27b3e46e2 | ||
|
|
da21a8f77f | ||
|
|
e10347bf01 | ||
|
|
26a022c905 | ||
|
|
95e9816223 | ||
|
|
3239d21168 | ||
|
|
06b4931743 | ||
|
|
6189d2bfd5 | ||
|
|
a0e9347f1b | ||
|
|
83cf229909 | ||
|
|
2249f8b5c6 | ||
|
|
fdb9b616fc | ||
|
|
d792fba59c | ||
|
|
55956f8d70 | ||
|
|
94ffd50060 | ||
|
|
c4dfcd4c1a | ||
|
|
cb8cd048c1 | ||
|
|
455f6bc2d5 | ||
|
|
ba538619eb | ||
|
|
d43a808ea5 | ||
|
|
ca4b156b57 | ||
|
|
aba22722a6 | ||
|
|
569459c54c | ||
|
|
2b42699623 | ||
|
|
66a8100737 | ||
|
|
36303694d1 | ||
|
|
4dcf802ae3 | ||
|
|
a2cec2e580 | ||
|
|
1cd7d25fec | ||
|
|
09002ab763 | ||
|
|
cb206ddc74 | ||
|
|
fa466f8174 | ||
|
|
e26f5e9548 | ||
|
|
787aa7677b | ||
|
|
d878fc83f8 | ||
|
|
ee2b2c5ab6 | ||
|
|
81d993f49d | ||
|
|
4c3842711d | ||
|
|
ab69985fcc | ||
|
|
56bb63668c | ||
|
|
359a28f876 | ||
|
|
da9ba693cb | ||
|
|
5488b86c67 | ||
|
|
a3c054a54c | ||
|
|
1bdb488c9e | ||
|
|
d38ba9d507 | ||
|
|
9d9eaf399f | ||
|
|
eb32d166af | ||
|
|
1dbafe629a | ||
|
|
c42deab55c | ||
|
|
906d49a271 | ||
|
|
4192ca0827 | ||
|
|
228f1e13aa | ||
|
|
15968585f3 | ||
|
|
4951994ebe | ||
|
|
756a2d1327 | ||
|
|
b279076ba1 | ||
|
|
e61eeae258 | ||
|
|
958eb9ea8f | ||
|
|
8381a5a8a6 | ||
|
|
1ead940a71 | ||
|
|
bdff2fa72e | ||
|
|
1d62941bd2 | ||
|
|
52cf9ef5d6 | ||
|
|
16568314d8 | ||
|
|
1fc6850dc4 | ||
|
|
4e87f59628 | ||
|
|
7ab0a3ccb7 | ||
|
|
2fff03720d | ||
|
|
7f7fc5a829 | ||
|
|
ff6c060168 | ||
|
|
5b552db781 | ||
|
|
108bf7ff82 | ||
|
|
1836b1c6e4 | ||
|
|
b4f08981be | ||
|
|
cd4d0baacd | ||
|
|
3bc24a3d5d | ||
|
|
fa07b34956 | ||
|
|
85a8bf5f39 | ||
|
|
d0f533f94a | ||
|
|
d1db1d6a27 | ||
|
|
1a14ffcec6 | ||
|
|
454c930d13 | ||
|
|
bc590bcb56 | ||
|
|
7cf25970de | ||
|
|
d837687368 | ||
|
|
b4650360d6 | ||
|
|
d52f15060b | ||
|
|
31ab22c33d | ||
|
|
d42c981f9c | ||
|
|
cb1106c2fb | ||
|
|
df4b97097c | ||
|
|
a9cec25b8d |
@@ -0,0 +1 @@
|
|||||||
|
powershell.exe -ExecutionPolicy Bypass -File ".\xray_no_window.ps1"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Start-Process -FilePath ".\xray.exe" -ArgumentList "-config .\config.json" -WindowStyle Hidden
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
CreateObject("Wscript.Shell").Run "xray.exe -config config.json",0
|
||||||
@@ -32,9 +32,13 @@ RUN echo '{}' >/tmp/usr/local/etc/xray/03_routing.json
|
|||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/04_policy.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/04_policy.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/05_inbounds.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/05_inbounds.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/06_outbounds.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/06_outbounds.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/07_transport.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/07_stats.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/08_stats.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/08_fakedns.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/09_reverse.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/09_metrics.json
|
||||||
|
RUN echo '{}' >/tmp/usr/local/etc/xray/10_observatory.json
|
||||||
|
RUN echo '{}' >/tmp/usr/local/etc/xray/11_geodata.json
|
||||||
|
RUN echo '{}' >/tmp/usr/local/etc/xray/12_env.json
|
||||||
|
RUN echo '{}' >/tmp/usr/local/etc/xray/99_version.json
|
||||||
|
|
||||||
# Create log files
|
# Create log files
|
||||||
RUN mkdir -p /tmp/var/log/xray && touch \
|
RUN mkdir -p /tmp/var/log/xray && touch \
|
||||||
@@ -45,8 +49,8 @@ RUN mkdir -p /tmp/var/log/xray && touch \
|
|||||||
FROM gcr.io/distroless/static:nonroot
|
FROM gcr.io/distroless/static:nonroot
|
||||||
|
|
||||||
COPY --from=build --chown=0:0 --chmod=755 /src/xray /usr/local/bin/xray
|
COPY --from=build --chown=0:0 --chmod=755 /src/xray /usr/local/bin/xray
|
||||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /usr/local/share/xray
|
COPY --from=build --chown=65532:65532 --chmod=755 /tmp/empty /usr/local/share/xray
|
||||||
COPY --from=build --chown=0:0 --chmod=644 /tmp/geodat/*.dat /usr/local/share/xray/
|
COPY --from=build --chown=65532:65532 --chmod=644 /tmp/geodat/*.dat /usr/local/share/xray/
|
||||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /usr/local/etc/xray
|
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /usr/local/etc/xray
|
||||||
COPY --from=build --chown=0:0 --chmod=644 /tmp/usr/local/etc/xray/*.json /usr/local/etc/xray/
|
COPY --from=build --chown=0:0 --chmod=644 /tmp/usr/local/etc/xray/*.json /usr/local/etc/xray/
|
||||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /var/log/xray
|
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /var/log/xray
|
||||||
|
|||||||
@@ -32,9 +32,13 @@ RUN echo '{}' >/tmp/usr/local/etc/xray/03_routing.json
|
|||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/04_policy.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/04_policy.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/05_inbounds.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/05_inbounds.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/06_outbounds.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/06_outbounds.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/07_transport.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/07_stats.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/08_stats.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/08_fakedns.json
|
||||||
RUN echo '{}' >/tmp/usr/local/etc/xray/09_reverse.json
|
RUN echo '{}' >/tmp/usr/local/etc/xray/09_metrics.json
|
||||||
|
RUN echo '{}' >/tmp/usr/local/etc/xray/10_observatory.json
|
||||||
|
RUN echo '{}' >/tmp/usr/local/etc/xray/11_geodata.json
|
||||||
|
RUN echo '{}' >/tmp/usr/local/etc/xray/12_env.json
|
||||||
|
RUN echo '{}' >/tmp/usr/local/etc/xray/99_version.json
|
||||||
|
|
||||||
# Create log files
|
# Create log files
|
||||||
RUN mkdir -p /tmp/var/log/xray && touch \
|
RUN mkdir -p /tmp/var/log/xray && touch \
|
||||||
@@ -54,8 +58,8 @@ RUN mkdir -p /tmp/var/log/xray && touch \
|
|||||||
FROM --platform=linux/amd64 gcr.io/distroless/static:nonroot
|
FROM --platform=linux/amd64 gcr.io/distroless/static:nonroot
|
||||||
|
|
||||||
COPY --from=build --chown=0:0 --chmod=755 /src/xray /usr/local/bin/xray
|
COPY --from=build --chown=0:0 --chmod=755 /src/xray /usr/local/bin/xray
|
||||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /usr/local/share/xray
|
COPY --from=build --chown=65532:65532 --chmod=755 /tmp/empty /usr/local/share/xray
|
||||||
COPY --from=build --chown=0:0 --chmod=644 /tmp/geodat/*.dat /usr/local/share/xray/
|
COPY --from=build --chown=65532:65532 --chmod=644 /tmp/geodat/*.dat /usr/local/share/xray/
|
||||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /usr/local/etc/xray
|
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /usr/local/etc/xray
|
||||||
COPY --from=build --chown=0:0 --chmod=644 /tmp/usr/local/etc/xray/*.json /usr/local/etc/xray/
|
COPY --from=build --chown=0:0 --chmod=644 /tmp/usr/local/etc/xray/*.json /usr/local/etc/xray/
|
||||||
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /var/log/xray
|
COPY --from=build --chown=0:0 --chmod=755 /tmp/empty /var/log/xray
|
||||||
|
|||||||
@@ -64,8 +64,16 @@ jobs:
|
|||||||
echo "Latest: '$LATEST'."
|
echo "Latest: '$LATEST'."
|
||||||
echo "LATEST=$LATEST" >>${GITHUB_ENV}
|
echo "LATEST=$LATEST" >>${GITHUB_ENV}
|
||||||
|
|
||||||
|
NEWEST=false
|
||||||
|
if [[ "${{ github.event_name }}" == "release" ]]; then
|
||||||
|
NEWEST=true
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Newest: '$NEWEST'."
|
||||||
|
echo "NEWEST=$NEWEST" >>${GITHUB_ENV}
|
||||||
|
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v4
|
uses: docker/setup-qemu-action@v4
|
||||||
@@ -74,7 +82,7 @@ jobs:
|
|||||||
uses: docker/setup-buildx-action@v4
|
uses: docker/setup-buildx-action@v4
|
||||||
|
|
||||||
- name: Login to GitHub Container Registry
|
- name: Login to GitHub Container Registry
|
||||||
uses: docker/login-action@v4
|
uses: docker/login-action@v4.6.0
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.repository_owner }}
|
username: ${{ github.repository_owner }}
|
||||||
@@ -124,6 +132,13 @@ jobs:
|
|||||||
${{ env.FULL_IMAGE_NAME }}:${{ env.IMAGE_TAG }}
|
${{ env.FULL_IMAGE_NAME }}:${{ env.IMAGE_TAG }}
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [[ "${{ env.NEWEST }}" == "true" ]]; then
|
||||||
|
echo "Adding 'pre-release' tag to manifest: '${{ env.FULL_IMAGE_NAME }}:pre-release'."
|
||||||
|
docker buildx imagetools create \
|
||||||
|
--tag ${{ env.FULL_IMAGE_NAME }}:pre-release \
|
||||||
|
${{ env.FULL_IMAGE_NAME }}:${{ env.IMAGE_TAG }}
|
||||||
|
fi
|
||||||
|
|
||||||
- name: Inspect image
|
- name: Inspect image
|
||||||
run: |
|
run: |
|
||||||
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ env.IMAGE_TAG }}
|
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ env.IMAGE_TAG }}
|
||||||
@@ -131,3 +146,7 @@ jobs:
|
|||||||
if [[ "${{ env.LATEST }}" == "true" ]]; then
|
if [[ "${{ env.LATEST }}" == "true" ]]; then
|
||||||
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:latest
|
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:latest
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [[ "${{ env.NEWEST }}" == "true" ]]; then
|
||||||
|
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:pre-release
|
||||||
|
fi
|
||||||
|
|||||||
@@ -11,15 +11,16 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
check-assets:
|
check-assets:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
steps:
|
steps:
|
||||||
- name: Restore Geodat Cache
|
- name: Restore Geodat Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-geodat-
|
key: xray-geodat-
|
||||||
|
|
||||||
- name: Restore Wintun Cache
|
- name: Restore Wintun Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-wintun-
|
key: xray-wintun-
|
||||||
@@ -75,13 +76,14 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
env:
|
env:
|
||||||
GOOS: ${{ matrix.goos}}
|
GOOS: ${{ matrix.goos}}
|
||||||
GOARCH: ${{ matrix.goarch }}
|
GOARCH: ${{ matrix.goarch }}
|
||||||
CGO_ENABLED: 0
|
CGO_ENABLED: 0
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout codebase
|
- name: Checkout codebase
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Show workflow information
|
- name: Show workflow information
|
||||||
run: |
|
run: |
|
||||||
@@ -90,7 +92,7 @@ jobs:
|
|||||||
echo "ASSET_NAME=$_NAME" >> $GITHUB_ENV
|
echo "ASSET_NAME=$_NAME" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v6
|
uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version-file: go.mod
|
go-version-file: go.mod
|
||||||
check-latest: true
|
check-latest: true
|
||||||
@@ -117,13 +119,13 @@ jobs:
|
|||||||
# go build -o build_assets/wxray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-H windowsgui -X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
# go build -o build_assets/wxray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-H windowsgui -X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||||
|
|
||||||
- name: Restore Geodat Cache
|
- name: Restore Geodat Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-geodat-
|
key: xray-geodat-
|
||||||
|
|
||||||
- name: Restore Wintun Cache
|
- name: Restore Wintun Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-wintun-
|
key: xray-wintun-
|
||||||
@@ -132,15 +134,17 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
mv -f resources/geo* build_assets/
|
mv -f resources/geo* build_assets/
|
||||||
if [[ ${GOOS} == 'windows' ]]; then
|
if [[ ${GOOS} == 'windows' ]]; then
|
||||||
echo 'CreateObject("Wscript.Shell").Run "xray.exe -config config.json",0' > build_assets/xray_no_window.vbs
|
cp .github/build/windows/* build_assets/
|
||||||
echo 'Start-Process -FilePath ".\xray.exe" -ArgumentList "-config .\config.json" -WindowStyle Hidden' > build_assets/xray_no_window.ps1
|
fi
|
||||||
|
if [[ ${GOOS} == 'windows' ]]; then
|
||||||
|
echo 'Adding Wintun into packages'
|
||||||
if [[ ${GOARCH} == 'amd64' ]]; then
|
if [[ ${GOARCH} == 'amd64' ]]; then
|
||||||
mv resources/wintun/bin/amd64/wintun.dll build_assets/
|
mv resources/wintun/bin/amd64/wintun.dll build_assets/
|
||||||
fi
|
fi
|
||||||
if [[ ${GOARCH} == '386' ]]; then
|
if [[ ${GOARCH} == '386' ]]; then
|
||||||
mv resources/wintun/bin/x86/wintun.dll build_assets/
|
mv resources/wintun/bin/x86/wintun.dll build_assets/
|
||||||
fi
|
fi
|
||||||
mv resources/wintun/LICENSE.txt build_assets/LICENSE-wintun.txt
|
mv resources/wintun/LICENSE.txt build_assets/LICENSE-Wintun
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Copy README.md & LICENSE
|
- name: Copy README.md & LICENSE
|
||||||
|
|||||||
@@ -11,15 +11,16 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
check-assets:
|
check-assets:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
steps:
|
steps:
|
||||||
- name: Restore Geodat Cache
|
- name: Restore Geodat Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-geodat-
|
key: xray-geodat-
|
||||||
|
|
||||||
- name: Restore Wintun Cache
|
- name: Restore Wintun Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-wintun-
|
key: xray-wintun-
|
||||||
@@ -161,6 +162,7 @@ jobs:
|
|||||||
fail-fast: false
|
fail-fast: false
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
env:
|
env:
|
||||||
GOOS: ${{ matrix.goos }}
|
GOOS: ${{ matrix.goos }}
|
||||||
GOARCH: ${{ matrix.goarch }}
|
GOARCH: ${{ matrix.goarch }}
|
||||||
@@ -168,7 +170,7 @@ jobs:
|
|||||||
CGO_ENABLED: 0
|
CGO_ENABLED: 0
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout codebase
|
- name: Checkout codebase
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Set up NDK
|
- name: Set up NDK
|
||||||
if: matrix.goos == 'android'
|
if: matrix.goos == 'android'
|
||||||
@@ -191,7 +193,7 @@ jobs:
|
|||||||
echo "ASSET_NAME=$_NAME" >> $GITHUB_ENV
|
echo "ASSET_NAME=$_NAME" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v6
|
uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version-file: go.mod
|
go-version-file: go.mod
|
||||||
check-latest: true
|
check-latest: true
|
||||||
@@ -208,6 +210,9 @@ jobs:
|
|||||||
go build -o build_assets/xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
go build -o build_assets/xray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||||
# The line below is for without running conhost.exe version. Commented for not being used. Provided for reference.
|
# The line below is for without running conhost.exe version. Commented for not being used. Provided for reference.
|
||||||
# go build -o build_assets/wxray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-H windowsgui -X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
# go build -o build_assets/wxray.exe -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-H windowsgui -X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid=" -v ./main
|
||||||
|
elif [[ ${GOOS} == 'android' ]]; then
|
||||||
|
echo 'Building Xray for Android...'
|
||||||
|
go build -o build_assets/xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=${COMMID} -s -w -buildid= -checklinkname=0" -v ./main
|
||||||
else
|
else
|
||||||
echo 'Building Xray...'
|
echo 'Building Xray...'
|
||||||
if [[ ${GOARCH} == 'mips' || ${GOARCH} == 'mipsle' ]]; then
|
if [[ ${GOARCH} == 'mips' || ${GOARCH} == 'mipsle' ]]; then
|
||||||
@@ -220,14 +225,14 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Restore Geodat Cache
|
- name: Restore Geodat Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-geodat-
|
key: xray-geodat-
|
||||||
|
|
||||||
- name: Restore Wintun Cache
|
- name: Restore Wintun Cache
|
||||||
if: matrix.goos == 'windows'
|
if: matrix.goos == 'windows'
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-wintun-
|
key: xray-wintun-
|
||||||
@@ -236,8 +241,10 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
mv -f resources/geo* build_assets/
|
mv -f resources/geo* build_assets/
|
||||||
if [[ ${GOOS} == 'windows' ]]; then
|
if [[ ${GOOS} == 'windows' ]]; then
|
||||||
echo 'CreateObject("Wscript.Shell").Run "xray.exe -config config.json",0' > build_assets/xray_no_window.vbs
|
cp .github/build/windows/* build_assets/
|
||||||
echo 'Start-Process -FilePath ".\xray.exe" -ArgumentList "-config .\config.json" -WindowStyle Hidden' > build_assets/xray_no_window.ps1
|
fi
|
||||||
|
if [[ ${GOOS} == 'windows' ]]; then
|
||||||
|
echo 'Adding Wintun into packages'
|
||||||
if [[ ${GOARCH} == 'amd64' ]]; then
|
if [[ ${GOARCH} == 'amd64' ]]; then
|
||||||
mv resources/wintun/bin/amd64/wintun.dll build_assets/
|
mv resources/wintun/bin/amd64/wintun.dll build_assets/
|
||||||
fi
|
fi
|
||||||
@@ -247,7 +254,7 @@ jobs:
|
|||||||
if [[ ${GOARCH} == 'arm64' ]]; then
|
if [[ ${GOARCH} == 'arm64' ]]; then
|
||||||
mv resources/wintun/bin/arm64/wintun.dll build_assets/
|
mv resources/wintun/bin/arm64/wintun.dll build_assets/
|
||||||
fi
|
fi
|
||||||
mv resources/wintun/LICENSE.txt build_assets/LICENSE-wintun.txt
|
mv resources/wintun/LICENSE.txt build_assets/LICENSE-Wintun
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Copy README.md & LICENSE
|
- name: Copy README.md & LICENSE
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Restore Geodat Cache
|
- name: Restore Geodat Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-geodat-
|
key: xray-geodat-
|
||||||
@@ -59,7 +59,7 @@ jobs:
|
|||||||
done
|
done
|
||||||
|
|
||||||
- name: Save Geodat Cache
|
- name: Save Geodat Cache
|
||||||
uses: actions/cache/save@v5
|
uses: actions/cache/save@v6
|
||||||
if: ${{ steps.update.outputs.unhit }}
|
if: ${{ steps.update.outputs.unhit }}
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
@@ -68,9 +68,12 @@ jobs:
|
|||||||
wintun:
|
wintun:
|
||||||
if: github.event.schedule == '30 22 * * *' || github.event_name == 'push' || github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
|
if: github.event.schedule == '30 22 * * *' || github.event_name == 'push' || github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch'
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
ASSETVER: 0.14.1
|
||||||
|
ASSETHASH: 07c256185d6ee3652e09fa55c0b673e2624b565e02c4b9091c79ca7d2f24ef51
|
||||||
steps:
|
steps:
|
||||||
- name: Restore Wintun Cache
|
- name: Restore Wintun Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-wintun-
|
key: xray-wintun-
|
||||||
@@ -96,7 +99,6 @@ jobs:
|
|||||||
echo -e "Checking if wintun.dll for ${ARCHITECTURE} exists..."
|
echo -e "Checking if wintun.dll for ${ARCHITECTURE} exists..."
|
||||||
if [ -s "./resources/wintun/bin/${ARCHITECTURE}/wintun.dll" ]; then
|
if [ -s "./resources/wintun/bin/${ARCHITECTURE}/wintun.dll" ]; then
|
||||||
echo -e "wintun.dll for ${ARCHITECTURE} exists"
|
echo -e "wintun.dll for ${ARCHITECTURE} exists"
|
||||||
continue
|
|
||||||
else
|
else
|
||||||
echo -e "wintun.dll for ${ARCHITECTURE} is missing"
|
echo -e "wintun.dll for ${ARCHITECTURE} is missing"
|
||||||
missing=true
|
missing=true
|
||||||
@@ -113,16 +115,21 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
if [[ "$missing" == true ]]; then
|
if [[ "$missing" == true ]]; then
|
||||||
FILENAME=wintun.zip
|
FILENAME=wintun.zip
|
||||||
DOWNLOAD_FILE=wintun-0.14.1.zip
|
DOWNLOAD_FILE=wintun-${ASSETVER}.zip
|
||||||
echo -e "Downloading https://www.wintun.net/builds/${DOWNLOAD_FILE}..."
|
echo -e "Downloading https://www.wintun.net/builds/${DOWNLOAD_FILE}..."
|
||||||
curl -L "https://www.wintun.net/builds/${DOWNLOAD_FILE}" -o "${FILENAME}"
|
curl -L "https://www.wintun.net/builds/${DOWNLOAD_FILE}" -o "${FILENAME}"
|
||||||
|
if [[ "$(sha256sum "./${FILENAME}" | awk -F ' ' '{print $1}')" == "${ASSETHASH}" ]]; then
|
||||||
echo -e "Unpacking wintun..."
|
echo -e "Unpacking wintun..."
|
||||||
unzip -u ${FILENAME} -d resources/
|
unzip -u ${FILENAME} -d resources/
|
||||||
echo "unhit=true" >> $GITHUB_OUTPUT
|
echo "unhit=true" >> $GITHUB_OUTPUT
|
||||||
|
else
|
||||||
|
echo -e "Digest of ${FILENAME} mismatch."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Save Wintun Cache
|
- name: Save Wintun Cache
|
||||||
uses: actions/cache/save@v5
|
uses: actions/cache/save@v6
|
||||||
if: ${{ steps.update.outputs.unhit }}
|
if: ${{ steps.update.outputs.unhit }}
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
name: Test
|
name: Tests and Checkings
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
@@ -8,9 +8,10 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
check-assets:
|
check-assets:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
steps:
|
steps:
|
||||||
- name: Restore Geodat Cache
|
- name: Restore Geodat Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-geodat-
|
key: xray-geodat-
|
||||||
@@ -36,9 +37,10 @@ jobs:
|
|||||||
|
|
||||||
check-proto:
|
check-proto:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout codebase
|
- name: Checkout codebase
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
- name: Check Proto Version Header
|
- name: Check Proto Version Header
|
||||||
run: |
|
run: |
|
||||||
head -n 4 core/config.pb.go > ref.txt
|
head -n 4 core/config.pb.go > ref.txt
|
||||||
@@ -50,8 +52,26 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
|
check-format:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
steps:
|
||||||
|
- name: Checkout codebase
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v7
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
check-latest: true
|
||||||
|
cache: false
|
||||||
|
- name: Check Format
|
||||||
|
run: go run ./infra/vformat/main.go -mode check -pwd ./
|
||||||
|
|
||||||
test:
|
test:
|
||||||
needs: check-assets
|
needs: check-assets
|
||||||
|
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
@@ -61,14 +81,14 @@ jobs:
|
|||||||
os: [windows-latest, ubuntu-latest, macos-latest]
|
os: [windows-latest, ubuntu-latest, macos-latest]
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout codebase
|
- name: Checkout codebase
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v6
|
uses: actions/setup-go@v7
|
||||||
with:
|
with:
|
||||||
go-version-file: go.mod
|
go-version-file: go.mod
|
||||||
check-latest: true
|
check-latest: true
|
||||||
- name: Restore Geodat Cache
|
- name: Restore Geodat Cache
|
||||||
uses: actions/cache/restore@v5
|
uses: actions/cache/restore@v6
|
||||||
with:
|
with:
|
||||||
path: resources
|
path: resources
|
||||||
key: xray-geodat-
|
key: xray-geodat-
|
||||||
|
|||||||
@@ -73,8 +73,7 @@
|
|||||||
- [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey), [XTool](https://github.com/LordPenguin666/XTool), [VPainLess](https://github.com/vpainless/vpainless)
|
- [Xray_bash_onekey](https://github.com/hello-yunshu/Xray_bash_onekey), [XTool](https://github.com/LordPenguin666/XTool), [VPainLess](https://github.com/vpainless/vpainless)
|
||||||
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey), [ProxySU](https://github.com/proxysu/ProxySU)
|
- [v2ray-agent](https://github.com/mack-a/v2ray-agent), [Xray_onekey](https://github.com/wulabing/Xray_onekey), [ProxySU](https://github.com/proxysu/ProxySU)
|
||||||
- Magisk
|
- Magisk
|
||||||
- [NetProxy-Magisk](https://github.com/Fanju6/NetProxy-Magisk)
|
- [Magic_V2Ray](https://github.com/vincentng295/Magic_V2Ray)
|
||||||
- [Xray4Magisk](https://github.com/Asterisk4Magisk/Xray4Magisk)
|
|
||||||
- [Xray_For_Magisk](https://github.com/E7KMbb/Xray_For_Magisk)
|
- [Xray_For_Magisk](https://github.com/E7KMbb/Xray_For_Magisk)
|
||||||
- Homebrew
|
- Homebrew
|
||||||
- `brew install xray`
|
- `brew install xray`
|
||||||
@@ -111,6 +110,8 @@
|
|||||||
- [Invisible Man - Xray](https://github.com/InvisibleManVPN/InvisibleMan-XRayClient)
|
- [Invisible Man - Xray](https://github.com/InvisibleManVPN/InvisibleMan-XRayClient)
|
||||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||||
|
- [OneXray](https://github.com/OneXray/OneXray)
|
||||||
|
- [XrayUI-dev](https://github.com/PhoenixNil/XrayUI-dev)
|
||||||
- Android
|
- Android
|
||||||
- [v2rayNG](https://github.com/2dust/v2rayNG)
|
- [v2rayNG](https://github.com/2dust/v2rayNG)
|
||||||
- [X-flutter](https://github.com/XTLS/X-flutter)
|
- [X-flutter](https://github.com/XTLS/X-flutter)
|
||||||
@@ -118,7 +119,8 @@
|
|||||||
- [SimpleXray](https://github.com/lhear/SimpleXray)
|
- [SimpleXray](https://github.com/lhear/SimpleXray)
|
||||||
- [XrayFA](https://github.com/Q7DF1/XrayFA)
|
- [XrayFA](https://github.com/Q7DF1/XrayFA)
|
||||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||||
- [NetProxy-Magisk](https://github.com/Fanju6/NetProxy-Magisk)
|
- [OneXray](https://github.com/OneXray/OneXray)
|
||||||
|
- [AsteriskNG](https://github.com/Asterisk4Magisk/AsteriskNG)
|
||||||
- iOS & macOS arm64 & tvOS
|
- iOS & macOS arm64 & tvOS
|
||||||
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
|
- [Happ](https://apps.apple.com/app/happ-proxy-utility/id6504287215) | [Happ RU](https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973) | [Happ tvOS](https://apps.apple.com/us/app/happ-proxy-utility-for-tv/id6748297274)
|
||||||
- [Streisand](https://apps.apple.com/app/streisand/id6450534064)
|
- [Streisand](https://apps.apple.com/app/streisand/id6450534064)
|
||||||
@@ -143,10 +145,14 @@
|
|||||||
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
- [AnyPortal](https://github.com/AnyPortal/AnyPortal)
|
||||||
- [v2rayN](https://github.com/2dust/v2rayN)
|
- [v2rayN](https://github.com/2dust/v2rayN)
|
||||||
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
- [GenyConnect](https://github.com/genyleap/GenyConnect)
|
||||||
|
- [OneXray](https://github.com/OneXray/OneXray)
|
||||||
|
- HarmonyOS
|
||||||
|
- [Hey](https://github.com/popsiclelmlm/Hey)
|
||||||
|
|
||||||
## Others that support VLESS, XTLS, REALITY, XUDP, PLUX...
|
## Others that support VLESS, XTLS, REALITY, XUDP, PLUX...
|
||||||
|
|
||||||
- iOS & macOS arm64 & tvOS
|
- iOS & macOS arm64 & tvOS
|
||||||
|
- [Anywhere](https://github.com/NodePassProject/Anywhere)
|
||||||
- [Shadowrocket](https://apps.apple.com/app/shadowrocket/id932747118)
|
- [Shadowrocket](https://apps.apple.com/app/shadowrocket/id932747118)
|
||||||
- [Loon](https://apps.apple.com/us/app/loon/id1373567447)
|
- [Loon](https://apps.apple.com/us/app/loon/id1373567447)
|
||||||
- [Egern](https://apps.apple.com/us/app/egern/id1616105820)
|
- [Egern](https://apps.apple.com/us/app/egern/id1616105820)
|
||||||
@@ -159,6 +165,7 @@
|
|||||||
- [xtls-sdk](https://github.com/remnawave/xtls-sdk)
|
- [xtls-sdk](https://github.com/remnawave/xtls-sdk)
|
||||||
- [xtlsapi](https://github.com/hiddify/xtlsapi)
|
- [xtlsapi](https://github.com/hiddify/xtlsapi)
|
||||||
- [AndroidLibXrayLite](https://github.com/2dust/AndroidLibXrayLite)
|
- [AndroidLibXrayLite](https://github.com/2dust/AndroidLibXrayLite)
|
||||||
|
- [flutter_vless](https://github.com/XIIIFOX/flutter_vless)
|
||||||
- [Xray-core-python](https://github.com/LorenEteval/Xray-core-python)
|
- [Xray-core-python](https://github.com/LorenEteval/Xray-core-python)
|
||||||
- [xray-api](https://github.com/XVGuardian/xray-api)
|
- [xray-api](https://github.com/XVGuardian/xray-api)
|
||||||
- [XrayR](https://github.com/XrayR-project/XrayR)
|
- [XrayR](https://github.com/XrayR-project/XrayR)
|
||||||
@@ -180,6 +187,27 @@
|
|||||||
- [Xray-core v1.0.0](https://github.com/XTLS/Xray-core/releases/tag/v1.0.0) was forked from [v2fly-core 9a03cc5](https://github.com/v2fly/v2ray-core/commit/9a03cc5c98d04cc28320fcee26dbc236b3291256), and we have made & accumulated a huge number of enhancements over time, check [the release notes for each version](https://github.com/XTLS/Xray-core/releases).
|
- [Xray-core v1.0.0](https://github.com/XTLS/Xray-core/releases/tag/v1.0.0) was forked from [v2fly-core 9a03cc5](https://github.com/v2fly/v2ray-core/commit/9a03cc5c98d04cc28320fcee26dbc236b3291256), and we have made & accumulated a huge number of enhancements over time, check [the release notes for each version](https://github.com/XTLS/Xray-core/releases).
|
||||||
- For third-party projects used in [Xray-core](https://github.com/XTLS/Xray-core), check your local or [the latest go.mod](https://github.com/XTLS/Xray-core/blob/main/go.mod).
|
- For third-party projects used in [Xray-core](https://github.com/XTLS/Xray-core), check your local or [the latest go.mod](https://github.com/XTLS/Xray-core/blob/main/go.mod).
|
||||||
|
|
||||||
|
### Bundled Third-Party Components Redistribution
|
||||||
|
|
||||||
|
**Certain optional features dynamically load third-party components. These optional components are separate works distributed under their own licenses, and are bundled into the ZIP package for ease of use. Users may replace these components under the licenses from these components.**
|
||||||
|
|
||||||
|
These components include:
|
||||||
|
|
||||||
|
#### Wintun
|
||||||
|
|
||||||
|
This distribution contains unmodified official precompiled and pre-signed Wintun binaries.
|
||||||
|
|
||||||
|
- Project: Wintun
|
||||||
|
- Copyright: Copyright (C) 2018-2021 WireGuard LLC. All Rights Reserved.
|
||||||
|
- Redistribution License: Prebuilt Binaries License (PBL) bundled with official precompiled and pre-signed binaries from wintun.net
|
||||||
|
- Component(s): wintun.dll
|
||||||
|
- Source: https://www.wintun.net/
|
||||||
|
- Included in:
|
||||||
|
- Windows x86 (windows-32, win7-32)
|
||||||
|
- Windows x86-64 (windows-64, win7-64)
|
||||||
|
- Windows AArch64 (windows-arm64)
|
||||||
|
- Notes: Wintun is an optional runtime-loaded component only used for TUN inbound functionality on supported Windows platforms.
|
||||||
|
|
||||||
## One-line Compilation
|
## One-line Compilation
|
||||||
|
|
||||||
### Windows (PowerShell)
|
### Windows (PowerShell)
|
||||||
@@ -203,6 +231,13 @@ Make sure that you are using the same Go version, and remember to set the git co
|
|||||||
CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
CGO_ENABLED=0 go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid=" -v ./main
|
||||||
```
|
```
|
||||||
|
|
||||||
|
For Android:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
GOOS=android GOARCH=arm64 CGO_ENABLED=1 CC=/path/to/aarch64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0" -v ./main
|
||||||
|
GOOS=android GOARCH=amd64 CGO_ENABLED=1 CC=/path/to/x86_64-linux-android24-clang go build -o xray -trimpath -buildvcs=false -gcflags="all=-l=4" -ldflags="-X github.com/xtls/xray-core/core.build=REPLACE -s -w -buildid= -checklinkname=0" -v ./main
|
||||||
|
```
|
||||||
|
|
||||||
If you are compiling a 32-bit MIPS/MIPSLE target, use this command instead:
|
If you are compiling a 32-bit MIPS/MIPSLE target, use this command instead:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package commander
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common"
|
"github.com/xtls/xray-core/common"
|
||||||
@@ -10,6 +11,7 @@ import (
|
|||||||
"github.com/xtls/xray-core/common/signal/done"
|
"github.com/xtls/xray-core/common/signal/done"
|
||||||
core "github.com/xtls/xray-core/core"
|
core "github.com/xtls/xray-core/core"
|
||||||
"github.com/xtls/xray-core/features/outbound"
|
"github.com/xtls/xray-core/features/outbound"
|
||||||
|
"github.com/xtls/xray-core/transport/internet"
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -67,20 +69,32 @@ func (c *Commander) Start() error {
|
|||||||
}
|
}
|
||||||
c.Unlock()
|
c.Unlock()
|
||||||
|
|
||||||
var listen = func(listener net.Listener) {
|
listen := func(listener net.Listener) {
|
||||||
if err := c.server.Serve(listener); err != nil {
|
if err := c.server.Serve(listener); err != nil {
|
||||||
errors.LogErrorInner(context.Background(), err, "failed to start grpc server")
|
errors.LogErrorInner(context.Background(), err, "failed to start grpc server")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(c.listen) > 0 {
|
if len(c.listen) > 0 {
|
||||||
if l, err := net.Listen("tcp", c.listen); err != nil {
|
var addr net.Addr
|
||||||
|
|
||||||
|
if strings.HasPrefix(c.listen, "/") || strings.HasPrefix(c.listen, "@") {
|
||||||
|
addr = &net.UnixAddr{Name: c.listen, Net: "unix"}
|
||||||
|
} else {
|
||||||
|
tcpAddr, err := net.ResolveTCPAddr("tcp", c.listen)
|
||||||
|
if err != nil {
|
||||||
|
errors.LogErrorInner(context.Background(), err, "API server failed to parse listen address ", c.listen)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
addr = tcpAddr
|
||||||
|
}
|
||||||
|
l, err := internet.ListenSystem(context.Background(), addr, nil)
|
||||||
|
if err != nil {
|
||||||
errors.LogErrorInner(context.Background(), err, "API server failed to listen on ", c.listen)
|
errors.LogErrorInner(context.Background(), err, "API server failed to listen on ", c.listen)
|
||||||
return err
|
return err
|
||||||
} else {
|
}
|
||||||
errors.LogInfo(context.Background(), "API server listening on ", l.Addr())
|
errors.LogInfo(context.Background(), "API server listening on ", l.Addr())
|
||||||
go listen(l)
|
go listen(l)
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -162,7 +162,7 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran
|
|||||||
p := d.policy.ForLevel(user.Level)
|
p := d.policy.ForLevel(user.Level)
|
||||||
if p.Stats.UserUplink {
|
if p.Stats.UserUplink {
|
||||||
name := "user>>>" + user.Email + ">>>traffic>>>uplink"
|
name := "user>>>" + user.Email + ">>>traffic>>>uplink"
|
||||||
if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
|
if c, _ := d.stats.GetOrRegisterCounter(name); c != nil {
|
||||||
inboundLink.Writer = &SizeStatWriter{
|
inboundLink.Writer = &SizeStatWriter{
|
||||||
Counter: c,
|
Counter: c,
|
||||||
Writer: inboundLink.Writer,
|
Writer: inboundLink.Writer,
|
||||||
@@ -171,7 +171,7 @@ func (d *DefaultDispatcher) getLink(ctx context.Context) (*transport.Link, *tran
|
|||||||
}
|
}
|
||||||
if p.Stats.UserDownlink {
|
if p.Stats.UserDownlink {
|
||||||
name := "user>>>" + user.Email + ">>>traffic>>>downlink"
|
name := "user>>>" + user.Email + ">>>traffic>>>downlink"
|
||||||
if c, _ := stats.GetOrRegisterCounter(d.stats, name); c != nil {
|
if c, _ := d.stats.GetOrRegisterCounter(name); c != nil {
|
||||||
outboundLink.Writer = &SizeStatWriter{
|
outboundLink.Writer = &SizeStatWriter{
|
||||||
Counter: c,
|
Counter: c,
|
||||||
Writer: outboundLink.Writer,
|
Writer: outboundLink.Writer,
|
||||||
@@ -200,13 +200,13 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
|
|||||||
p := policyManager.ForLevel(user.Level)
|
p := policyManager.ForLevel(user.Level)
|
||||||
if p.Stats.UserUplink {
|
if p.Stats.UserUplink {
|
||||||
name := "user>>>" + user.Email + ">>>traffic>>>uplink"
|
name := "user>>>" + user.Email + ">>>traffic>>>uplink"
|
||||||
if c, _ := stats.GetOrRegisterCounter(statsManager, name); c != nil {
|
if c, _ := statsManager.GetOrRegisterCounter(name); c != nil {
|
||||||
link.Reader.(*buf.TimeoutWrapperReader).Counter = c
|
link.Reader.(*buf.TimeoutWrapperReader).Counter = c
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if p.Stats.UserDownlink {
|
if p.Stats.UserDownlink {
|
||||||
name := "user>>>" + user.Email + ">>>traffic>>>downlink"
|
name := "user>>>" + user.Email + ">>>traffic>>>downlink"
|
||||||
if c, _ := stats.GetOrRegisterCounter(statsManager, name); c != nil {
|
if c, _ := statsManager.GetOrRegisterCounter(name); c != nil {
|
||||||
link.Writer = &SizeStatWriter{
|
link.Writer = &SizeStatWriter{
|
||||||
Counter: c,
|
Counter: c,
|
||||||
Writer: link.Writer,
|
Writer: link.Writer,
|
||||||
@@ -223,7 +223,7 @@ func WrapLink(ctx context.Context, policyManager policy.Manager, statsManager st
|
|||||||
|
|
||||||
func trackOnlineIP(ctx context.Context, sm stats.Manager, email, ip string) {
|
func trackOnlineIP(ctx context.Context, sm stats.Manager, email, ip string) {
|
||||||
name := "user>>>" + email + ">>>online"
|
name := "user>>>" + email + ">>>online"
|
||||||
if om, _ := stats.GetOrRegisterOnlineMap(sm, name); om != nil {
|
if om, _ := sm.GetOrRegisterOnlineMap(name); om != nil {
|
||||||
om.AddIP(ip)
|
om.AddIP(ip)
|
||||||
context.AfterFunc(ctx, func() { om.RemoveIP(ip) })
|
context.AfterFunc(ctx, func() { om.RemoveIP(ip) })
|
||||||
}
|
}
|
||||||
@@ -470,6 +470,9 @@ func (d *DefaultDispatcher) routedDispatch(ctx context.Context, link *transport.
|
|||||||
return // DO NOT CHANGE: the traffic shouldn't be processed by default outbound if the specified outbound tag doesn't exist (yet), e.g., VLESS Reverse Proxy
|
return // DO NOT CHANGE: the traffic shouldn't be processed by default outbound if the specified outbound tag doesn't exist (yet), e.g., VLESS Reverse Proxy
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
if err != common.ErrNoClue {
|
||||||
|
errors.LogErrorInner(ctx, err, "failed to pick route for ", destination)
|
||||||
|
}
|
||||||
errors.LogInfo(ctx, "default route for ", destination)
|
errors.LogInfo(ctx, "default route for ", destination)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -139,7 +139,8 @@ func (c *CacheController) writeAndShrink(expiredKeys []string) {
|
|||||||
|
|
||||||
if lenAfter == 0 {
|
if lenAfter == 0 {
|
||||||
if c.highWatermark >= minSizeForEmptyRebuild {
|
if c.highWatermark >= minSizeForEmptyRebuild {
|
||||||
errors.LogDebug(context.Background(), c.name,
|
errors.LogDebug(
|
||||||
|
context.Background(), c.name,
|
||||||
" rebuilding empty cache map to reclaim memory.",
|
" rebuilding empty cache map to reclaim memory.",
|
||||||
" size_before_cleanup=", lenBefore,
|
" size_before_cleanup=", lenBefore,
|
||||||
" peak_size_before_rebuild=", c.highWatermark,
|
" peak_size_before_rebuild=", c.highWatermark,
|
||||||
@@ -153,7 +154,8 @@ func (c *CacheController) writeAndShrink(expiredKeys []string) {
|
|||||||
|
|
||||||
if reductionFromPeak := c.highWatermark - lenAfter; reductionFromPeak > shrinkAbsoluteThreshold &&
|
if reductionFromPeak := c.highWatermark - lenAfter; reductionFromPeak > shrinkAbsoluteThreshold &&
|
||||||
float64(reductionFromPeak) > float64(c.highWatermark)*shrinkRatioThreshold {
|
float64(reductionFromPeak) > float64(c.highWatermark)*shrinkRatioThreshold {
|
||||||
errors.LogDebug(context.Background(), c.name,
|
errors.LogDebug(
|
||||||
|
context.Background(), c.name,
|
||||||
" shrinking cache map to reclaim memory.",
|
" shrinking cache map to reclaim memory.",
|
||||||
" new_size=", lenAfter,
|
" new_size=", lenAfter,
|
||||||
" peak_size_before_shrink=", c.highWatermark,
|
" peak_size_before_shrink=", c.highWatermark,
|
||||||
@@ -165,7 +167,6 @@ func (c *CacheController) writeAndShrink(expiredKeys []string) {
|
|||||||
c.highWatermark = lenAfter
|
c.highWatermark = lenAfter
|
||||||
go c.migrate()
|
go c.migrate()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type migrationEntry struct {
|
type migrationEntry struct {
|
||||||
|
|||||||
+23
-4
@@ -93,6 +93,7 @@ type NameServer struct {
|
|||||||
UnexpectedIp []*geodata.IPRule `protobuf:"bytes,13,rep,name=unexpected_ip,json=unexpectedIp,proto3" json:"unexpected_ip,omitempty"`
|
UnexpectedIp []*geodata.IPRule `protobuf:"bytes,13,rep,name=unexpected_ip,json=unexpectedIp,proto3" json:"unexpected_ip,omitempty"`
|
||||||
ActUnprior bool `protobuf:"varint,14,opt,name=actUnprior,proto3" json:"actUnprior,omitempty"`
|
ActUnprior bool `protobuf:"varint,14,opt,name=actUnprior,proto3" json:"actUnprior,omitempty"`
|
||||||
PolicyID uint32 `protobuf:"varint,17,opt,name=policyID,proto3" json:"policyID,omitempty"`
|
PolicyID uint32 `protobuf:"varint,17,opt,name=policyID,proto3" json:"policyID,omitempty"`
|
||||||
|
Id string `protobuf:"bytes,18,opt,name=id,proto3" json:"id,omitempty"`
|
||||||
unknownFields protoimpl.UnknownFields
|
unknownFields protoimpl.UnknownFields
|
||||||
sizeCache protoimpl.SizeCache
|
sizeCache protoimpl.SizeCache
|
||||||
}
|
}
|
||||||
@@ -239,6 +240,13 @@ func (x *NameServer) GetPolicyID() uint32 {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (x *NameServer) GetId() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Id
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
state protoimpl.MessageState `protogen:"open.v1"`
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
// NameServer list used by this DNS client.
|
// NameServer list used by this DNS client.
|
||||||
@@ -258,6 +266,8 @@ type Config struct {
|
|||||||
DisableFallback bool `protobuf:"varint,10,opt,name=disableFallback,proto3" json:"disableFallback,omitempty"`
|
DisableFallback bool `protobuf:"varint,10,opt,name=disableFallback,proto3" json:"disableFallback,omitempty"`
|
||||||
DisableFallbackIfMatch bool `protobuf:"varint,11,opt,name=disableFallbackIfMatch,proto3" json:"disableFallbackIfMatch,omitempty"`
|
DisableFallbackIfMatch bool `protobuf:"varint,11,opt,name=disableFallbackIfMatch,proto3" json:"disableFallbackIfMatch,omitempty"`
|
||||||
EnableParallelQuery bool `protobuf:"varint,14,opt,name=enableParallelQuery,proto3" json:"enableParallelQuery,omitempty"`
|
EnableParallelQuery bool `protobuf:"varint,14,opt,name=enableParallelQuery,proto3" json:"enableParallelQuery,omitempty"`
|
||||||
|
// Absolute path to the Lua DNS query script.
|
||||||
|
Script string `protobuf:"bytes,15,opt,name=script,proto3" json:"script,omitempty"`
|
||||||
unknownFields protoimpl.UnknownFields
|
unknownFields protoimpl.UnknownFields
|
||||||
sizeCache protoimpl.SizeCache
|
sizeCache protoimpl.SizeCache
|
||||||
}
|
}
|
||||||
@@ -369,6 +379,13 @@ func (x *Config) GetEnableParallelQuery() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (x *Config) GetScript() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Script
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
type Config_HostMapping struct {
|
type Config_HostMapping struct {
|
||||||
state protoimpl.MessageState `protogen:"open.v1"`
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
Domain *geodata.DomainRule `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
|
Domain *geodata.DomainRule `protobuf:"bytes,2,opt,name=domain,proto3" json:"domain,omitempty"`
|
||||||
@@ -435,7 +452,7 @@ var File_app_dns_config_proto protoreflect.FileDescriptor
|
|||||||
|
|
||||||
const file_app_dns_config_proto_rawDesc = "" +
|
const file_app_dns_config_proto_rawDesc = "" +
|
||||||
"\n" +
|
"\n" +
|
||||||
"\x14app/dns/config.proto\x12\fxray.app.dns\x1a\x1ccommon/net/destination.proto\x1a\x1bcommon/geodata/geodat.proto\"\xde\x05\n" +
|
"\x14app/dns/config.proto\x12\fxray.app.dns\x1a\x1ccommon/net/destination.proto\x1a\x1bcommon/geodata/geodat.proto\"\xee\x05\n" +
|
||||||
"\n" +
|
"\n" +
|
||||||
"NameServer\x123\n" +
|
"NameServer\x123\n" +
|
||||||
"\aaddress\x18\x01 \x01(\v2\x19.xray.common.net.EndpointR\aaddress\x12\x1b\n" +
|
"\aaddress\x18\x01 \x01(\v2\x19.xray.common.net.EndpointR\aaddress\x12\x1b\n" +
|
||||||
@@ -461,10 +478,11 @@ const file_app_dns_config_proto_rawDesc = "" +
|
|||||||
"\n" +
|
"\n" +
|
||||||
"actUnprior\x18\x0e \x01(\bR\n" +
|
"actUnprior\x18\x0e \x01(\bR\n" +
|
||||||
"actUnprior\x12\x1a\n" +
|
"actUnprior\x12\x1a\n" +
|
||||||
"\bpolicyID\x18\x11 \x01(\rR\bpolicyIDB\x0f\n" +
|
"\bpolicyID\x18\x11 \x01(\rR\bpolicyID\x12\x0e\n" +
|
||||||
|
"\x02id\x18\x12 \x01(\tR\x02idB\x0f\n" +
|
||||||
"\r_disableCacheB\r\n" +
|
"\r_disableCacheB\r\n" +
|
||||||
"\v_serveStaleB\x12\n" +
|
"\v_serveStaleB\x12\n" +
|
||||||
"\x10_serveExpiredTTLJ\x04\b\x04\x10\x05\"\x82\x05\n" +
|
"\x10_serveExpiredTTLJ\x04\b\x04\x10\x05\"\x9a\x05\n" +
|
||||||
"\x06Config\x129\n" +
|
"\x06Config\x129\n" +
|
||||||
"\vname_server\x18\x05 \x03(\v2\x18.xray.app.dns.NameServerR\n" +
|
"\vname_server\x18\x05 \x03(\v2\x18.xray.app.dns.NameServerR\n" +
|
||||||
"nameServer\x12\x1b\n" +
|
"nameServer\x12\x1b\n" +
|
||||||
@@ -480,7 +498,8 @@ const file_app_dns_config_proto_rawDesc = "" +
|
|||||||
"\x0fdisableFallback\x18\n" +
|
"\x0fdisableFallback\x18\n" +
|
||||||
" \x01(\bR\x0fdisableFallback\x126\n" +
|
" \x01(\bR\x0fdisableFallback\x126\n" +
|
||||||
"\x16disableFallbackIfMatch\x18\v \x01(\bR\x16disableFallbackIfMatch\x120\n" +
|
"\x16disableFallbackIfMatch\x18\v \x01(\bR\x16disableFallbackIfMatch\x120\n" +
|
||||||
"\x13enableParallelQuery\x18\x0e \x01(\bR\x13enableParallelQuery\x1a}\n" +
|
"\x13enableParallelQuery\x18\x0e \x01(\bR\x13enableParallelQuery\x12\x16\n" +
|
||||||
|
"\x06script\x18\x0f \x01(\tR\x06script\x1a}\n" +
|
||||||
"\vHostMapping\x127\n" +
|
"\vHostMapping\x127\n" +
|
||||||
"\x06domain\x18\x02 \x01(\v2\x1f.xray.common.geodata.DomainRuleR\x06domain\x12\x0e\n" +
|
"\x06domain\x18\x02 \x01(\v2\x1f.xray.common.geodata.DomainRuleR\x06domain\x12\x0e\n" +
|
||||||
"\x02ip\x18\x03 \x03(\fR\x02ip\x12%\n" +
|
"\x02ip\x18\x03 \x03(\fR\x02ip\x12%\n" +
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ message NameServer {
|
|||||||
repeated xray.common.geodata.IPRule unexpected_ip = 13;
|
repeated xray.common.geodata.IPRule unexpected_ip = 13;
|
||||||
bool actUnprior = 14;
|
bool actUnprior = 14;
|
||||||
uint32 policyID = 17;
|
uint32 policyID = 17;
|
||||||
|
string id = 18;
|
||||||
}
|
}
|
||||||
|
|
||||||
enum QueryStrategy {
|
enum QueryStrategy {
|
||||||
@@ -73,4 +74,7 @@ message Config {
|
|||||||
bool disableFallbackIfMatch = 11;
|
bool disableFallbackIfMatch = 11;
|
||||||
|
|
||||||
bool enableParallelQuery = 14;
|
bool enableParallelQuery = 14;
|
||||||
|
|
||||||
|
// Absolute path to the Lua DNS query script.
|
||||||
|
string script = 15;
|
||||||
}
|
}
|
||||||
|
|||||||
+30
-75
@@ -5,18 +5,16 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
go_errors "errors"
|
go_errors "errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"runtime"
|
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common"
|
"github.com/xtls/xray-core/common"
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/geodata"
|
"github.com/xtls/xray-core/common/geodata"
|
||||||
"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/session"
|
||||||
|
"github.com/xtls/xray-core/common/utils"
|
||||||
"github.com/xtls/xray-core/features/dns"
|
"github.com/xtls/xray-core/features/dns"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -33,6 +31,8 @@ type DNS struct {
|
|||||||
domainMatcher geodata.DomainMatcher
|
domainMatcher geodata.DomainMatcher
|
||||||
matcherInfos []*DomainMatcherInfo
|
matcherInfos []*DomainMatcherInfo
|
||||||
checkSystem bool
|
checkSystem bool
|
||||||
|
script *scriptEngine
|
||||||
|
scriptPath string
|
||||||
}
|
}
|
||||||
|
|
||||||
// DomainMatcherInfo contains information attached to index returned by Server.domainMatcher.
|
// DomainMatcherInfo contains information attached to index returned by Server.domainMatcher.
|
||||||
@@ -88,7 +88,7 @@ func New(ctx context.Context, config *Config) (*DNS, error) {
|
|||||||
return nil, errors.New("failed to create hosts").Base(err)
|
return nil, errors.New("failed to create hosts").Base(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var defaultTag = config.Tag
|
defaultTag := config.Tag
|
||||||
if len(config.Tag) == 0 {
|
if len(config.Tag) == 0 {
|
||||||
defaultTag = generateRandomTag()
|
defaultTag = generateRandomTag()
|
||||||
}
|
}
|
||||||
@@ -141,7 +141,7 @@ func New(ctx context.Context, config *Config) (*DNS, error) {
|
|||||||
serveExpiredTTL = *ns.ServeExpiredTTL
|
serveExpiredTTL = *ns.ServeExpiredTTL
|
||||||
}
|
}
|
||||||
|
|
||||||
var tag = defaultTag
|
tag := defaultTag
|
||||||
if len(ns.Tag) > 0 {
|
if len(ns.Tag) > 0 {
|
||||||
tag = ns.Tag
|
tag = ns.Tag
|
||||||
}
|
}
|
||||||
@@ -158,10 +158,13 @@ func New(ctx context.Context, config *Config) (*DNS, error) {
|
|||||||
clients = append(clients, client)
|
clients = append(clients, client)
|
||||||
}
|
}
|
||||||
|
|
||||||
domainMatcher, err := geodata.DomainReg.BuildDomainMatcher(effectiveRules)
|
var domainMatcher geodata.DomainMatcher
|
||||||
|
if len(effectiveRules) > 0 {
|
||||||
|
domainMatcher, err = geodata.DomainReg.BuildDomainMatcher(effectiveRules)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// If there is no DNS client in config, add a `localhost` DNS client
|
// If there is no DNS client in config, add a `localhost` DNS client
|
||||||
if len(clients) == 0 {
|
if len(clients) == 0 {
|
||||||
@@ -179,6 +182,7 @@ func New(ctx context.Context, config *Config) (*DNS, error) {
|
|||||||
disableFallbackIfMatch: config.DisableFallbackIfMatch,
|
disableFallbackIfMatch: config.DisableFallbackIfMatch,
|
||||||
enableParallelQuery: config.EnableParallelQuery,
|
enableParallelQuery: config.EnableParallelQuery,
|
||||||
checkSystem: checkSystem,
|
checkSystem: checkSystem,
|
||||||
|
scriptPath: config.Script,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,11 +193,21 @@ func (*DNS) Type() interface{} {
|
|||||||
|
|
||||||
// Start implements common.Runnable.
|
// Start implements common.Runnable.
|
||||||
func (s *DNS) Start() error {
|
func (s *DNS) Start() error {
|
||||||
|
if s.scriptPath != "" {
|
||||||
|
engine, err := newScriptEngine(s.scriptPath, s)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("failed to initialize DNS script").Base(err)
|
||||||
|
}
|
||||||
|
s.script = engine
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close implements common.Closable.
|
// Close implements common.Closable.
|
||||||
func (s *DNS) Close() error {
|
func (s *DNS) Close() error {
|
||||||
|
if s.script != nil {
|
||||||
|
s.script.close()
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,7 +234,7 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, uint32, er
|
|||||||
}
|
}
|
||||||
|
|
||||||
if s.checkSystem {
|
if s.checkSystem {
|
||||||
supportIPv4, supportIPv6 := checkRoutes()
|
supportIPv4, supportIPv6 := utils.CheckRoutes()
|
||||||
option.IPv4Enable = option.IPv4Enable && supportIPv4
|
option.IPv4Enable = option.IPv4Enable && supportIPv4
|
||||||
option.IPv6Enable = option.IPv6Enable && supportIPv6
|
option.IPv6Enable = option.IPv6Enable && supportIPv6
|
||||||
} else {
|
} else {
|
||||||
@@ -256,6 +270,9 @@ func (s *DNS) LookupIP(domain string, option dns.IPOption) ([]net.IP, uint32, er
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Name servers lookup
|
// Name servers lookup
|
||||||
|
if s.script != nil {
|
||||||
|
return s.script.query(domain, option)
|
||||||
|
}
|
||||||
if s.enableParallelQuery {
|
if s.enableParallelQuery {
|
||||||
return s.parallelQuery(domain, option)
|
return s.parallelQuery(domain, option)
|
||||||
} else {
|
} else {
|
||||||
@@ -271,11 +288,12 @@ func (s *DNS) sortClients(domain string) []*Client {
|
|||||||
|
|
||||||
// Priority domain matching
|
// Priority domain matching
|
||||||
hasMatch := false
|
hasMatch := false
|
||||||
MatchSlice := s.domainMatcher.Match(strings.ToLower(domain))
|
if s.domainMatcher != nil {
|
||||||
sort.Slice(MatchSlice, func(i, j int) bool {
|
matchSlice := s.domainMatcher.Match(strings.ToLower(domain))
|
||||||
return MatchSlice[i] < MatchSlice[j]
|
sort.Slice(matchSlice, func(i, j int) bool {
|
||||||
|
return matchSlice[i] < matchSlice[j]
|
||||||
})
|
})
|
||||||
for _, match := range MatchSlice {
|
for _, match := range matchSlice {
|
||||||
info := s.matcherInfos[match]
|
info := s.matcherInfos[match]
|
||||||
client := s.clients[info.clientIdx]
|
client := s.clients[info.clientIdx]
|
||||||
domainRule := info.domainRule
|
domainRule := info.domainRule
|
||||||
@@ -292,6 +310,7 @@ func (s *DNS) sortClients(domain string) []*Client {
|
|||||||
return clients
|
return clients
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if !(s.disableFallback || s.disableFallbackIfMatch && hasMatch) {
|
if !(s.disableFallback || s.disableFallbackIfMatch && hasMatch) {
|
||||||
// Default round-robin query
|
// Default round-robin query
|
||||||
@@ -534,67 +553,3 @@ func init() {
|
|||||||
return New(ctx, config.(*Config))
|
return New(ctx, config.(*Config))
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
func probeRoutes() (ipv4 bool, ipv6 bool) {
|
|
||||||
if conn, err := net.Dial("udp4", "192.33.4.12:53"); err == nil {
|
|
||||||
ipv4 = true
|
|
||||||
conn.Close()
|
|
||||||
}
|
|
||||||
if conn, err := net.Dial("udp6", "[2001:500:2::c]:53"); err == nil {
|
|
||||||
ipv6 = true
|
|
||||||
conn.Close()
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var routeCache struct {
|
|
||||||
sync.Once
|
|
||||||
sync.RWMutex
|
|
||||||
expire time.Time
|
|
||||||
ipv4, ipv6 bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func checkRoutes() (bool, bool) {
|
|
||||||
if !isGUIPlatform {
|
|
||||||
routeCache.Once.Do(func() {
|
|
||||||
routeCache.ipv4, routeCache.ipv6 = probeRoutes()
|
|
||||||
})
|
|
||||||
return routeCache.ipv4, routeCache.ipv6
|
|
||||||
}
|
|
||||||
|
|
||||||
routeCache.RWMutex.RLock()
|
|
||||||
now := time.Now()
|
|
||||||
if routeCache.expire.After(now) {
|
|
||||||
routeCache.RWMutex.RUnlock()
|
|
||||||
return routeCache.ipv4, routeCache.ipv6
|
|
||||||
}
|
|
||||||
routeCache.RWMutex.RUnlock()
|
|
||||||
|
|
||||||
routeCache.RWMutex.Lock()
|
|
||||||
defer routeCache.RWMutex.Unlock()
|
|
||||||
|
|
||||||
now = time.Now()
|
|
||||||
if routeCache.expire.After(now) { // double-check
|
|
||||||
return routeCache.ipv4, routeCache.ipv6
|
|
||||||
}
|
|
||||||
routeCache.ipv4, routeCache.ipv6 = probeRoutes() // ~2ms
|
|
||||||
routeCache.expire = now.Add(100 * time.Millisecond) // ttl
|
|
||||||
return routeCache.ipv4, routeCache.ipv6
|
|
||||||
}
|
|
||||||
|
|
||||||
var isGUIPlatform = detectGUIPlatform()
|
|
||||||
|
|
||||||
func detectGUIPlatform() bool {
|
|
||||||
switch runtime.GOOS {
|
|
||||||
case "android", "ios", "windows", "darwin":
|
|
||||||
return true
|
|
||||||
case "linux", "freebsd", "openbsd":
|
|
||||||
if t := os.Getenv("XDG_SESSION_TYPE"); t == "wayland" || t == "x11" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if os.Getenv("DISPLAY") != "" || os.Getenv("WAYLAND_DISPLAY") != "" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|||||||
+19
-75
@@ -148,7 +148,7 @@ func TestUDPServerSubnet(t *testing.T) {
|
|||||||
Outbound: []*core.OutboundHandlerConfig{
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
{
|
{
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||||
IpsBlocked: &freedom.IPRules{},
|
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -210,7 +210,7 @@ func TestUDPServer(t *testing.T) {
|
|||||||
Outbound: []*core.OutboundHandlerConfig{
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
{
|
{
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||||
IpsBlocked: &freedom.IPRules{},
|
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -350,7 +350,7 @@ func TestPrioritizedDomain(t *testing.T) {
|
|||||||
Outbound: []*core.OutboundHandlerConfig{
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
{
|
{
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||||
IpsBlocked: &freedom.IPRules{},
|
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -421,7 +421,7 @@ func TestUDPServerIPv6(t *testing.T) {
|
|||||||
Outbound: []*core.OutboundHandlerConfig{
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
{
|
{
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||||
IpsBlocked: &freedom.IPRules{},
|
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -490,7 +490,7 @@ func TestStaticHostDomain(t *testing.T) {
|
|||||||
Outbound: []*core.OutboundHandlerConfig{
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
{
|
{
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||||
IpsBlocked: &freedom.IPRules{},
|
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -548,15 +548,8 @@ func TestIPMatch(t *testing.T) {
|
|||||||
Port: uint32(port),
|
Port: uint32(port),
|
||||||
},
|
},
|
||||||
ExpectedIp: []*geodata.IPRule{
|
ExpectedIp: []*geodata.IPRule{
|
||||||
{
|
|
||||||
Value: &geodata.IPRule_Custom{
|
|
||||||
Custom: &geodata.CIDR{
|
|
||||||
// inner ip, will not match
|
// inner ip, will not match
|
||||||
Ip: []byte{192, 168, 11, 1},
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{192, 168, 11, 1}, Prefix: 32}}}},
|
||||||
Prefix: 32,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
// second dns, match ip
|
// second dns, match ip
|
||||||
@@ -571,22 +564,8 @@ func TestIPMatch(t *testing.T) {
|
|||||||
Port: uint32(port),
|
Port: uint32(port),
|
||||||
},
|
},
|
||||||
ExpectedIp: []*geodata.IPRule{
|
ExpectedIp: []*geodata.IPRule{
|
||||||
{
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{8, 8, 8, 8}, Prefix: 32}}}},
|
||||||
Value: &geodata.IPRule_Custom{
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{8, 8, 8, 4}, Prefix: 32}}}},
|
||||||
Custom: &geodata.CIDR{
|
|
||||||
Ip: []byte{8, 8, 8, 8},
|
|
||||||
Prefix: 32,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Value: &geodata.IPRule_Custom{
|
|
||||||
Custom: &geodata.CIDR{
|
|
||||||
Ip: []byte{8, 8, 8, 4},
|
|
||||||
Prefix: 32,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -598,7 +577,7 @@ func TestIPMatch(t *testing.T) {
|
|||||||
Outbound: []*core.OutboundHandlerConfig{
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
{
|
{
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||||
IpsBlocked: &freedom.IPRules{},
|
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -676,9 +655,9 @@ func TestLocalDomain(t *testing.T) {
|
|||||||
},
|
},
|
||||||
ExpectedIp: []*geodata.IPRule{
|
ExpectedIp: []*geodata.IPRule{
|
||||||
// Will match localhost, localhost-a and localhost-b,
|
// Will match localhost, localhost-a and localhost-b,
|
||||||
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDR{Ip: []byte{127, 0, 0, 2}, Prefix: 32}}},
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{127, 0, 0, 2}, Prefix: 32}}}},
|
||||||
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDR{Ip: []byte{127, 0, 0, 3}, Prefix: 32}}},
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{127, 0, 0, 3}, Prefix: 32}}}},
|
||||||
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDR{Ip: []byte{127, 0, 0, 4}, Prefix: 32}}},
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{127, 0, 0, 4}, Prefix: 32}}}},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -717,7 +696,7 @@ func TestLocalDomain(t *testing.T) {
|
|||||||
Outbound: []*core.OutboundHandlerConfig{
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
{
|
{
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||||
IpsBlocked: &freedom.IPRules{},
|
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -901,22 +880,8 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
|
|||||||
},
|
},
|
||||||
ExpectedIp: []*geodata.IPRule{
|
ExpectedIp: []*geodata.IPRule{
|
||||||
// Will only match 8.8.8.8 and 8.8.4.4
|
// Will only match 8.8.8.8 and 8.8.4.4
|
||||||
{
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{8, 8, 8, 8}, Prefix: 32}}}},
|
||||||
Value: &geodata.IPRule_Custom{
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{8, 8, 4, 4}, Prefix: 32}}}},
|
||||||
Custom: &geodata.CIDR{
|
|
||||||
Ip: []byte{8, 8, 8, 8},
|
|
||||||
Prefix: 32,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Value: &geodata.IPRule_Custom{
|
|
||||||
Custom: &geodata.CIDR{
|
|
||||||
Ip: []byte{8, 8, 4, 4},
|
|
||||||
Prefix: 32,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -936,14 +901,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
|
|||||||
},
|
},
|
||||||
ExpectedIp: []*geodata.IPRule{
|
ExpectedIp: []*geodata.IPRule{
|
||||||
// Will match 8.8.8.8 and 8.8.8.7, etc
|
// Will match 8.8.8.8 and 8.8.8.7, etc
|
||||||
{
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{8, 8, 8, 7}, Prefix: 24}}}},
|
||||||
Value: &geodata.IPRule_Custom{
|
|
||||||
Custom: &geodata.CIDR{
|
|
||||||
Ip: []byte{8, 8, 8, 7},
|
|
||||||
Prefix: 24,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -963,14 +921,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
|
|||||||
},
|
},
|
||||||
ExpectedIp: []*geodata.IPRule{
|
ExpectedIp: []*geodata.IPRule{
|
||||||
// Will only match 8.8.7.7 (api.google.com)
|
// Will only match 8.8.7.7 (api.google.com)
|
||||||
{
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{8, 8, 7, 7}, Prefix: 32}}}},
|
||||||
Value: &geodata.IPRule_Custom{
|
|
||||||
Custom: &geodata.CIDR{
|
|
||||||
Ip: []byte{8, 8, 7, 7},
|
|
||||||
Prefix: 32,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -990,14 +941,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
|
|||||||
},
|
},
|
||||||
ExpectedIp: []*geodata.IPRule{
|
ExpectedIp: []*geodata.IPRule{
|
||||||
// Will only match 8.8.7.8 (v2.api.google.com)
|
// Will only match 8.8.7.8 (v2.api.google.com)
|
||||||
{
|
{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{8, 8, 7, 8}, Prefix: 32}}}},
|
||||||
Value: &geodata.IPRule_Custom{
|
|
||||||
Custom: &geodata.CIDR{
|
|
||||||
Ip: []byte{8, 8, 7, 8},
|
|
||||||
Prefix: 32,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -1009,7 +953,7 @@ func TestMultiMatchPrioritizedDomain(t *testing.T) {
|
|||||||
Outbound: []*core.OutboundHandlerConfig{
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
{
|
{
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||||
IpsBlocked: &freedom.IPRules{},
|
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
+16
-6
@@ -127,15 +127,20 @@ func genEDNS0Options(clientIP net.IP, padding int) *dnsmessage.Resource {
|
|||||||
return opt
|
return opt
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildReqMsgs(domain string, option dns_feature.IPOption, reqIDGen func() uint16, reqOpts *dnsmessage.Resource) []*dnsRequest {
|
func buildReqMsgs(domain string, option dns_feature.IPOption, reqIDGen func() uint16, reqOpts *dnsmessage.Resource) ([]*dnsRequest, error) {
|
||||||
|
name, err := dnsmessage.NewName(domain)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
qA := dnsmessage.Question{
|
qA := dnsmessage.Question{
|
||||||
Name: dnsmessage.MustNewName(domain),
|
Name: name,
|
||||||
Type: dnsmessage.TypeA,
|
Type: dnsmessage.TypeA,
|
||||||
Class: dnsmessage.ClassINET,
|
Class: dnsmessage.ClassINET,
|
||||||
}
|
}
|
||||||
|
|
||||||
qAAAA := dnsmessage.Question{
|
qAAAA := dnsmessage.Question{
|
||||||
Name: dnsmessage.MustNewName(domain),
|
Name: name,
|
||||||
Type: dnsmessage.TypeAAAA,
|
Type: dnsmessage.TypeAAAA,
|
||||||
Class: dnsmessage.ClassINET,
|
Class: dnsmessage.ClassINET,
|
||||||
}
|
}
|
||||||
@@ -175,7 +180,7 @@ func buildReqMsgs(domain string, option dns_feature.IPOption, reqIDGen func() ui
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return reqs
|
return reqs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseResponse parses DNS answers from the returned payload
|
// parseResponse parses DNS answers from the returned payload
|
||||||
@@ -193,9 +198,14 @@ func parseResponse(payload []byte) (*IPRecord, error) {
|
|||||||
ipRecord := &IPRecord{
|
ipRecord := &IPRecord{
|
||||||
ReqID: h.ID,
|
ReqID: h.ID,
|
||||||
RCode: h.RCode,
|
RCode: h.RCode,
|
||||||
Expire: now.Add(time.Second * dns_feature.DefaultTTL),
|
|
||||||
RawHeader: &h,
|
RawHeader: &h,
|
||||||
}
|
}
|
||||||
|
defer func() {
|
||||||
|
// set to default TTL if no valid TTL is found
|
||||||
|
if ipRecord.Expire.IsZero() {
|
||||||
|
ipRecord.Expire = now.Add(time.Second * dns_feature.DefaultTTL)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
L:
|
L:
|
||||||
for {
|
for {
|
||||||
@@ -212,7 +222,7 @@ L:
|
|||||||
ttl = 1
|
ttl = 1
|
||||||
}
|
}
|
||||||
expire := now.Add(time.Duration(ttl) * time.Second)
|
expire := now.Add(time.Duration(ttl) * time.Second)
|
||||||
if ipRecord.Expire.After(expire) {
|
if ipRecord.Expire.IsZero() || ipRecord.Expire.After(expire) {
|
||||||
ipRecord.Expire = expire
|
ipRecord.Expire = expire
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package dns
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"math/rand"
|
"math/rand"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -24,7 +25,8 @@ func Test_parseResponse(t *testing.T) {
|
|||||||
|
|
||||||
ans = new(dns.Msg)
|
ans = new(dns.Msg)
|
||||||
ans.Id = 1
|
ans.Id = 1
|
||||||
ans.Answer = append(ans.Answer,
|
ans.Answer = append(
|
||||||
|
ans.Answer,
|
||||||
common.Must2(dns.NewRR("google.com. IN CNAME m.test.google.com")),
|
common.Must2(dns.NewRR("google.com. IN CNAME m.test.google.com")),
|
||||||
common.Must2(dns.NewRR("google.com. IN CNAME fake.google.com")),
|
common.Must2(dns.NewRR("google.com. IN CNAME fake.google.com")),
|
||||||
common.Must2(dns.NewRR("google.com. IN A 8.8.8.8")),
|
common.Must2(dns.NewRR("google.com. IN A 8.8.8.8")),
|
||||||
@@ -34,7 +36,8 @@ func Test_parseResponse(t *testing.T) {
|
|||||||
|
|
||||||
ans = new(dns.Msg)
|
ans = new(dns.Msg)
|
||||||
ans.Id = 2
|
ans.Id = 2
|
||||||
ans.Answer = append(ans.Answer,
|
ans.Answer = append(
|
||||||
|
ans.Answer,
|
||||||
common.Must2(dns.NewRR("google.com. IN CNAME m.test.google.com")),
|
common.Must2(dns.NewRR("google.com. IN CNAME m.test.google.com")),
|
||||||
common.Must2(dns.NewRR("google.com. IN CNAME fake.google.com")),
|
common.Must2(dns.NewRR("google.com. IN CNAME fake.google.com")),
|
||||||
common.Must2(dns.NewRR("google.com. IN CNAME m.test.google.com")),
|
common.Must2(dns.NewRR("google.com. IN CNAME m.test.google.com")),
|
||||||
@@ -131,10 +134,15 @@ func Test_buildReqMsgs(t *testing.T) {
|
|||||||
IPv6Enable: false,
|
IPv6Enable: false,
|
||||||
FakeEnable: false,
|
FakeEnable: false,
|
||||||
}, nil}, 0},
|
}, nil}, 0},
|
||||||
|
{"name too long", args{strings.Repeat("a", 256), dns_feature.IPOption{
|
||||||
|
IPv4Enable: true,
|
||||||
|
IPv6Enable: true,
|
||||||
|
FakeEnable: false,
|
||||||
|
}, nil}, 0},
|
||||||
}
|
}
|
||||||
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 := buildReqMsgs(tt.args.domain, tt.args.option, stubID, tt.args.reqOpts); !(len(got) == tt.want) {
|
if got, _ := buildReqMsgs(tt.args.domain, tt.args.option, stubID, tt.args.reqOpts); !(len(got) == tt.want) {
|
||||||
t.Errorf("buildReqMsgs() = %v, want %v", got, tt.want)
|
t.Errorf("buildReqMsgs() = %v, want %v", got, tt.want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
+8
-12
@@ -17,7 +17,7 @@ import (
|
|||||||
type Holder struct {
|
type Holder struct {
|
||||||
domainToIP cache.Lru
|
domainToIP cache.Lru
|
||||||
ipRange *net.IPNet
|
ipRange *net.IPNet
|
||||||
mu *sync.Mutex
|
mu sync.Mutex
|
||||||
|
|
||||||
config *FakeDnsPool
|
config *FakeDnsPool
|
||||||
}
|
}
|
||||||
@@ -49,9 +49,7 @@ func (fkdns *Holder) Start() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (fkdns *Holder) Close() error {
|
func (fkdns *Holder) Close() error {
|
||||||
fkdns.domainToIP = nil
|
// nothing to do for now, just wait GC
|
||||||
fkdns.ipRange = nil
|
|
||||||
fkdns.mu = nil
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,7 +68,7 @@ func NewFakeDNSHolder() (*Holder, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewFakeDNSHolderConfigOnly(conf *FakeDnsPool) (*Holder, error) {
|
func NewFakeDNSHolderConfigOnly(conf *FakeDnsPool) (*Holder, error) {
|
||||||
return &Holder{nil, nil, nil, conf}, nil
|
return &Holder{config: conf}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fkdns *Holder) initializeFromConfig() error {
|
func (fkdns *Holder) initializeFromConfig() error {
|
||||||
@@ -92,7 +90,6 @@ func (fkdns *Holder) initialize(ipPoolCidr string, lruSize int) error {
|
|||||||
}
|
}
|
||||||
fkdns.domainToIP = cache.NewLru(lruSize)
|
fkdns.domainToIP = cache.NewLru(lruSize)
|
||||||
fkdns.ipRange = ipRange
|
fkdns.ipRange = ipRange
|
||||||
fkdns.mu = new(sync.Mutex)
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,7 +100,7 @@ func (fkdns *Holder) GetFakeIPForDomain(domain string) []net.Address {
|
|||||||
if v, ok := fkdns.domainToIP.Get(domain); ok {
|
if v, ok := fkdns.domainToIP.Get(domain); ok {
|
||||||
return []net.Address{v.(net.Address)}
|
return []net.Address{v.(net.Address)}
|
||||||
}
|
}
|
||||||
currentTimeMillis := uint64(time.Now().UnixNano() / 1e6)
|
currentTimeMillis := uint64(time.Now().UnixMilli())
|
||||||
ones, bits := fkdns.ipRange.Mask.Size()
|
ones, bits := fkdns.ipRange.Mask.Size()
|
||||||
rooms := bits - ones
|
rooms := bits - ones
|
||||||
if rooms < 64 {
|
if rooms < 64 {
|
||||||
@@ -202,12 +199,11 @@ func (h *HolderMulti) Start() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (h *HolderMulti) Close() error {
|
func (h *HolderMulti) Close() error {
|
||||||
|
var errs []error
|
||||||
for _, v := range h.holders {
|
for _, v := range h.holders {
|
||||||
if err := v.Close(); err != nil {
|
errs = append(errs, v.Close())
|
||||||
return errors.New("Cannot close all fake dns pools").Base(err)
|
|
||||||
}
|
}
|
||||||
}
|
return errors.Combine(errs...)
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *HolderMulti) createHolderGroups() error {
|
func (h *HolderMulti) createHolderGroups() error {
|
||||||
@@ -222,7 +218,7 @@ func (h *HolderMulti) createHolderGroups() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewFakeDNSHolderMulti(conf *FakeDnsPoolMulti) (*HolderMulti, error) {
|
func NewFakeDNSHolderMulti(conf *FakeDnsPoolMulti) (*HolderMulti, error) {
|
||||||
holderMulti := &HolderMulti{nil, conf}
|
holderMulti := &HolderMulti{config: conf}
|
||||||
if err := holderMulti.createHolderGroups(); err != nil {
|
if err := holderMulti.createHolderGroups(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -129,7 +129,8 @@ func TestFakeDnsHolderCreateMappingAndRollOver(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestFakeDNSMulti(t *testing.T) {
|
func TestFakeDNSMulti(t *testing.T) {
|
||||||
fakeMulti, err := NewFakeDNSHolderMulti(&FakeDnsPoolMulti{
|
fakeMulti, err := NewFakeDNSHolderMulti(
|
||||||
|
&FakeDnsPoolMulti{
|
||||||
Pools: []*FakeDnsPool{{
|
Pools: []*FakeDnsPool{{
|
||||||
IpPool: "240.0.0.0/12",
|
IpPool: "240.0.0.0/12",
|
||||||
LruSize: 256,
|
LruSize: 256,
|
||||||
|
|||||||
+12
-9
@@ -13,7 +13,7 @@ import (
|
|||||||
|
|
||||||
// StaticHosts represents static domain-ip mapping in DNS server.
|
// StaticHosts represents static domain-ip mapping in DNS server.
|
||||||
type StaticHosts struct {
|
type StaticHosts struct {
|
||||||
reps [][]net.Address
|
responses [][]net.Address
|
||||||
matcher geodata.DomainMatcher
|
matcher geodata.DomainMatcher
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,20 +45,20 @@ func NewStaticHosts(hosts []*Config_HostMapping) (*StaticHosts, error) {
|
|||||||
rep = append(rep, addr)
|
rep = append(rep, addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// if len(rep) == 0 {
|
|
||||||
// errors.LogError(context.Background(), "empty value in static hosts, ignore this rule: ", mapping.Domain)
|
|
||||||
// continue
|
|
||||||
// }
|
|
||||||
reps = append(reps, rep)
|
reps = append(reps, rep)
|
||||||
rules = append(rules, mapping.Domain)
|
rules = append(rules, mapping.Domain)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(rules) == 0 {
|
||||||
|
return &StaticHosts{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
matcher, err := geodata.DomainReg.BuildDomainMatcher(rules)
|
matcher, err := geodata.DomainReg.BuildDomainMatcher(rules)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &StaticHosts{
|
return &StaticHosts{
|
||||||
reps: reps,
|
responses: reps,
|
||||||
matcher: matcher,
|
matcher: matcher,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -76,8 +76,8 @@ func filterIP(ips []net.Address, option dns.IPOption) []net.Address {
|
|||||||
func (h *StaticHosts) lookupInternal(domain string) ([]net.Address, error) {
|
func (h *StaticHosts) lookupInternal(domain string) ([]net.Address, error) {
|
||||||
ips := make([]net.Address, 0)
|
ips := make([]net.Address, 0)
|
||||||
found := false
|
found := false
|
||||||
for _, ruleIdx := range h.matcher.Match(domain) {
|
for _, idx := range h.matcher.Match(domain) {
|
||||||
for _, rep := range h.reps[ruleIdx] {
|
for _, rep := range h.responses[idx] {
|
||||||
if err, ok := rep.(dns.RCodeError); ok {
|
if err, ok := rep.(dns.RCodeError); ok {
|
||||||
if uint16(err) == 0 {
|
if uint16(err) == 0 {
|
||||||
return nil, dns.ErrEmptyResponse
|
return nil, dns.ErrEmptyResponse
|
||||||
@@ -85,7 +85,7 @@ func (h *StaticHosts) lookupInternal(domain string) ([]net.Address, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ips = append(ips, h.reps[ruleIdx]...)
|
ips = append(ips, h.responses[idx]...)
|
||||||
found = true
|
found = true
|
||||||
}
|
}
|
||||||
if !found {
|
if !found {
|
||||||
@@ -122,5 +122,8 @@ func (h *StaticHosts) lookup(domain string, option dns.IPOption, maxDepth int) (
|
|||||||
|
|
||||||
// Lookup returns IP addresses or proxied domain for the given domain, if exists in this StaticHosts.
|
// Lookup returns IP addresses or proxied domain for the given domain, if exists in this StaticHosts.
|
||||||
func (h *StaticHosts) Lookup(domain string, option dns.IPOption) ([]net.Address, error) {
|
func (h *StaticHosts) Lookup(domain string, option dns.IPOption) ([]net.Address, error) {
|
||||||
|
if h.matcher == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
return h.lookup(domain, option, 5)
|
return h.lookup(domain, option, 5)
|
||||||
}
|
}
|
||||||
|
|||||||
+201
@@ -0,0 +1,201 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
featureDNS "github.com/xtls/xray-core/features/dns"
|
||||||
|
"github.com/xtls/xray-core/features/dns/localdns"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
)
|
||||||
|
|
||||||
|
// luaDNSServer adapts configured and local DNS to the same Lua API.
|
||||||
|
type luaDNSServer struct {
|
||||||
|
id string
|
||||||
|
name string
|
||||||
|
query func(context.Context, string, featureDNS.IPOption) ([]net.IP, uint32, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterLua makes xray.dns available to scripts backed by client.
|
||||||
|
func RegisterLua(L *lua.LState, client featureDNS.Client) {
|
||||||
|
var servers []luaDNSServer
|
||||||
|
switch client := client.(type) {
|
||||||
|
case *DNS:
|
||||||
|
servers = luaServers(client)
|
||||||
|
case *localdns.Client:
|
||||||
|
servers = []luaDNSServer{{
|
||||||
|
id: "localhost",
|
||||||
|
name: "localhost",
|
||||||
|
query: func(_ context.Context, domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
return client.LookupIP(domain, option)
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
registerLua(L, servers, client)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterLua makes xray.dns available to DNS scripts.
|
||||||
|
func (s *DNS) RegisterLua(L *lua.LState) {
|
||||||
|
registerLua(L, luaServers(s), nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func luaServers(s *DNS) []luaDNSServer {
|
||||||
|
servers := make([]luaDNSServer, len(s.clients))
|
||||||
|
for i, client := range s.clients {
|
||||||
|
servers[i] = luaDNSServer{id: client.id, name: client.Name(), query: client.QueryIP}
|
||||||
|
}
|
||||||
|
return servers
|
||||||
|
}
|
||||||
|
|
||||||
|
func registerLua(L *lua.LState, servers []luaDNSServer, client featureDNS.Client) {
|
||||||
|
L.PreloadModule("xray.dns", func(L *lua.LState) int {
|
||||||
|
serverList := L.NewTable()
|
||||||
|
for i, client := range servers {
|
||||||
|
server := L.NewTable()
|
||||||
|
|
||||||
|
server.RawSetString("ID", lua.LString(client.id))
|
||||||
|
|
||||||
|
server.RawSetString("Query", L.NewFunction(func(L *lua.LState) int {
|
||||||
|
domain, ok := L.Get(2).(lua.LString)
|
||||||
|
if !ok {
|
||||||
|
L.RaiseError("server:Query requires a domain")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
option := featureDNS.IPOption{
|
||||||
|
IPv4Enable: L.CheckBool(3),
|
||||||
|
IPv6Enable: L.CheckBool(4),
|
||||||
|
FakeEnable: L.CheckBool(5),
|
||||||
|
}
|
||||||
|
ctx := L.Context()
|
||||||
|
if ctx == nil {
|
||||||
|
L.RaiseError("server:Query requires an active DNS query")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var ips []net.IP
|
||||||
|
var ttl uint32
|
||||||
|
var err error
|
||||||
|
if !option.FakeEnable && strings.EqualFold(client.name, "FakeDNS") {
|
||||||
|
err = featureDNS.ErrEmptyResponse
|
||||||
|
} else {
|
||||||
|
ips, ttl, err = client.query(ctx, string(domain), option)
|
||||||
|
}
|
||||||
|
addresses := L.NewUserData()
|
||||||
|
addresses.Value = ips
|
||||||
|
L.Push(addresses)
|
||||||
|
L.Push(lua.LNumber(ttl))
|
||||||
|
if err != nil {
|
||||||
|
ud := L.NewUserData()
|
||||||
|
ud.Value = err
|
||||||
|
L.Push(ud)
|
||||||
|
} else {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
}
|
||||||
|
return 3
|
||||||
|
}))
|
||||||
|
serverList.RawSetInt(i+1, server)
|
||||||
|
}
|
||||||
|
|
||||||
|
module := L.NewTable()
|
||||||
|
if servers != nil {
|
||||||
|
module.RawSetString("Servers", serverList)
|
||||||
|
}
|
||||||
|
if client != nil {
|
||||||
|
module.RawSetString("Query", newLuaClientQuery(L, client))
|
||||||
|
}
|
||||||
|
L.Push(module)
|
||||||
|
return 1
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func newLuaClientQuery(L *lua.LState, client featureDNS.Client) *lua.LFunction {
|
||||||
|
return L.NewFunction(func(L *lua.LState) int {
|
||||||
|
domain, ok := L.Get(1).(lua.LString)
|
||||||
|
if !ok {
|
||||||
|
L.RaiseError("dns.Query requires a domain")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
option := featureDNS.IPOption{
|
||||||
|
IPv4Enable: L.CheckBool(2),
|
||||||
|
IPv6Enable: L.CheckBool(3),
|
||||||
|
FakeEnable: L.CheckBool(4),
|
||||||
|
}
|
||||||
|
if L.Context() == nil {
|
||||||
|
L.RaiseError("dns.Query requires an active DNS query")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
ips, ttl, err := client.LookupIP(string(domain), option)
|
||||||
|
addresses := L.NewUserData()
|
||||||
|
addresses.Value = ips
|
||||||
|
L.Push(addresses)
|
||||||
|
L.Push(lua.LNumber(ttl))
|
||||||
|
if err != nil {
|
||||||
|
ud := L.NewUserData()
|
||||||
|
ud.Value = err
|
||||||
|
L.Push(ud)
|
||||||
|
} else {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
}
|
||||||
|
return 3
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// CallLuaHook invokes HandleDNSQuery in the supplied state.
|
||||||
|
// Returned slices and IP bytes may share storage with DNS caches or matcher inputs.
|
||||||
|
func (s *DNS) CallLuaHook(L *lua.LState, ctx context.Context, domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
previous, top := L.Context(), L.GetTop()
|
||||||
|
L.SetContext(ctx)
|
||||||
|
defer func() {
|
||||||
|
L.SetTop(top)
|
||||||
|
if previous == nil {
|
||||||
|
L.RemoveContext()
|
||||||
|
} else {
|
||||||
|
L.SetContext(previous)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
fn := L.GetGlobal("HandleDNSQuery")
|
||||||
|
if fn.Type() != lua.LTFunction {
|
||||||
|
return nil, 0, errors.New("DNS script must define HandleDNSQuery(domain, ipv4, ipv6, fake)")
|
||||||
|
}
|
||||||
|
if err := L.CallByParam(lua.P{Fn: fn, NRet: 3, Protect: true},
|
||||||
|
lua.LString(strings.ToLower(domain)), lua.LBool(option.IPv4Enable),
|
||||||
|
lua.LBool(option.IPv6Enable), lua.LBool(option.FakeEnable)); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
return readLuaDNSResult(L.Get(-3), L.Get(-2), L.Get(-1))
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLuaDNSResult(addresses, ttlValue, errorValue lua.LValue) ([]net.IP, uint32, error) {
|
||||||
|
if errorValue != lua.LNil {
|
||||||
|
if ud, ok := errorValue.(*lua.LUserData); ok {
|
||||||
|
if err, ok := ud.Value.(error); ok {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s, ok := errorValue.(lua.LString); ok {
|
||||||
|
return nil, 0, errors.New(string(s))
|
||||||
|
}
|
||||||
|
return nil, 0, errors.New("DNS script error must be an error or string")
|
||||||
|
}
|
||||||
|
ttl, ok := ttlValue.(lua.LNumber)
|
||||||
|
if !ok || ttl < 0 || ttl > math.MaxUint32 || math.Trunc(float64(ttl)) != float64(ttl) {
|
||||||
|
return nil, 0, errors.New("DNS script returned invalid TTL")
|
||||||
|
}
|
||||||
|
if addresses == lua.LNil {
|
||||||
|
return nil, 0, featureDNS.ErrEmptyResponse
|
||||||
|
}
|
||||||
|
ud, ok := addresses.(*lua.LUserData)
|
||||||
|
if !ok {
|
||||||
|
return nil, 0, errors.New("DNS script IPs must be native IP slice userdata")
|
||||||
|
}
|
||||||
|
ips, ok := ud.Value.([]net.IP)
|
||||||
|
if !ok {
|
||||||
|
return nil, 0, errors.New("DNS script IPs must be native IP slice userdata")
|
||||||
|
}
|
||||||
|
if len(ips) == 0 {
|
||||||
|
return nil, 0, featureDNS.ErrEmptyResponse
|
||||||
|
}
|
||||||
|
return ips, uint32(ttl), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,296 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
go_errors "errors"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/geodata"
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
featureDNS "github.com/xtls/xray-core/features/dns"
|
||||||
|
"github.com/xtls/xray-core/features/dns/localdns"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestReadLuaDNSResult(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
want := []net.IP{net.ParseIP("8.8.8.8"), {127, 0, 0, 1}, net.ParseIP("::1")}
|
||||||
|
addresses := L.NewUserData()
|
||||||
|
addresses.Value = want
|
||||||
|
ips, ttl, err := readLuaDNSResult(addresses, lua.LNumber(45), lua.LNil)
|
||||||
|
if err != nil || ttl != 45 || len(ips) != len(want) {
|
||||||
|
t.Fatalf("readLuaDNSResult() = %v, TTL %d, %v", ips, ttl, err)
|
||||||
|
}
|
||||||
|
for i := range want {
|
||||||
|
if !ips[i].Equal(want[i]) {
|
||||||
|
t.Fatalf("IP %d = %v, want %v", i, ips[i], want[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadLuaDNSResultValidation(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
change func(*[3]lua.LValue)
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"fractional TTL", func(v *[3]lua.LValue) { v[1] = lua.LNumber(1.5) }, "invalid TTL"},
|
||||||
|
{"oversized TTL", func(v *[3]lua.LValue) { v[1] = lua.LNumber(4294967296) }, "invalid TTL"},
|
||||||
|
{"negative TTL", func(v *[3]lua.LValue) { v[1] = lua.LNumber(-1) }, "invalid TTL"},
|
||||||
|
{"NaN TTL", func(v *[3]lua.LValue) { v[1] = lua.LNumber(math.NaN()) }, "invalid TTL"},
|
||||||
|
{"missing TTL", func(v *[3]lua.LValue) { v[1] = lua.LNil }, "invalid TTL"},
|
||||||
|
{"string IPs", func(v *[3]lua.LValue) { v[0] = lua.LString("127.0.0.1") }, "native IP slice"},
|
||||||
|
{"wrong userdata", func(v *[3]lua.LValue) { v[0].(*lua.LUserData).Value = net.ParseIP("127.0.0.1") }, "native IP slice"},
|
||||||
|
{"script error", func(v *[3]lua.LValue) { v[2] = lua.LString("blocked by script") }, "blocked by script"},
|
||||||
|
{"invalid error", func(v *[3]lua.LValue) { v[2] = lua.LTrue }, "error or string"},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
addresses := L.NewUserData()
|
||||||
|
addresses.Value = []net.IP{net.ParseIP("127.0.0.1")}
|
||||||
|
values := [3]lua.LValue{addresses, lua.LNumber(60), lua.LNil}
|
||||||
|
tc.change(&values)
|
||||||
|
_, _, err := readLuaDNSResult(values[0], values[1], values[2])
|
||||||
|
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||||
|
t.Fatalf("readLuaDNSResult error = %v, want %q", err, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
addresses := L.NewUserData()
|
||||||
|
addresses.Value = []net.IP(nil)
|
||||||
|
for _, empty := range []lua.LValue{addresses, lua.LNil} {
|
||||||
|
if _, _, err := readLuaDNSResult(empty, lua.LNumber(0), lua.LNil); !go_errors.Is(err, featureDNS.ErrEmptyResponse) {
|
||||||
|
t.Fatalf("empty result error = %v, want ErrEmptyResponse", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wantErr := go_errors.New("upstream failed")
|
||||||
|
errorValue := L.NewUserData()
|
||||||
|
errorValue.Value = wantErr
|
||||||
|
if _, _, err := readLuaDNSResult(lua.LNil, lua.LNil, errorValue); err != wantErr {
|
||||||
|
t.Fatalf("upstream error = %v, want original error %v", err, wantErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCallLuaHookCancellation(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
if err := L.DoString(`function HandleDNSQuery(domain, ipv4, ipv6, fake) while true do end end`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
_, _, err := (&DNS{}).CallLuaHook(L, ctx, "example.com", featureDNS.IPOption{IPv4Enable: true})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("CallLuaHook did not stop after context cancellation")
|
||||||
|
}
|
||||||
|
if L.Context() != nil {
|
||||||
|
t.Fatal("CallLuaHook left the canceled context on the Lua state")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCallLuaHookNormalizesDomain(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
addresses := L.NewUserData()
|
||||||
|
addresses.Value = []net.IP{net.ParseIP("127.0.0.1")}
|
||||||
|
L.SetGlobal("ips", addresses)
|
||||||
|
if err := L.DoString(`
|
||||||
|
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||||
|
assert(domain == "example.com")
|
||||||
|
assert(ipv4 and not ipv6 and not fake)
|
||||||
|
return ips, 60, nil
|
||||||
|
end
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s := &DNS{}
|
||||||
|
if _, _, err := s.CallLuaHook(L, context.Background(), "ExAmPlE.CoM", featureDNS.IPOption{IPv4Enable: true}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCallLuaHookRestoresState(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"success", `return ips, 60`, false},
|
||||||
|
{"error", `error("failed")`, true},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
addresses := L.NewUserData()
|
||||||
|
addresses.Value = []net.IP{net.ParseIP("127.0.0.1")}
|
||||||
|
L.SetGlobal("ips", addresses)
|
||||||
|
if err := L.DoString("function HandleDNSQuery() " + tc.body + " end"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
previous, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
L.SetContext(previous)
|
||||||
|
L.Push(lua.LTrue)
|
||||||
|
_, _, err := (&DNS{}).CallLuaHook(L, context.Background(), "example.com", featureDNS.IPOption{IPv4Enable: true})
|
||||||
|
if (err != nil) != tc.wantErr {
|
||||||
|
t.Fatalf("hook error = %v, want error %t", err, tc.wantErr)
|
||||||
|
}
|
||||||
|
if L.Context() != previous || L.GetTop() != 1 || L.Get(1) != lua.LTrue {
|
||||||
|
t.Fatal("hook did not restore the previous context and stack")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLuaDNSServerQuery(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
geodata.RegisterLua(L)
|
||||||
|
option := featureDNS.IPOption{IPv4Enable: true}
|
||||||
|
ips := []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("8.8.8.8")}
|
||||||
|
server := &DNS{clients: []*Client{{server: &benchmarkLuaNameServer{ips: ips}, ipOption: &option, timeoutMs: time.Second}}}
|
||||||
|
server.RegisterLua(L)
|
||||||
|
if err := L.DoString(`
|
||||||
|
local server = require("xray.dns").Servers[1]
|
||||||
|
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.0/8")
|
||||||
|
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||||
|
local ips, ttl, err = server:Query(domain, ipv4, ipv6, fake)
|
||||||
|
assert(type(ips) == "userdata" and not err)
|
||||||
|
assert(matcher:AnyMatch(ips))
|
||||||
|
local matched = matcher:FilterIPs(ips)
|
||||||
|
return matched, ttl, err
|
||||||
|
end
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, ttl, err := server.CallLuaHook(L, context.Background(), "example.com", option)
|
||||||
|
if err != nil || ttl != 60 || len(got) != 1 || !got[0].Equal(ips[0]) {
|
||||||
|
t.Fatalf("server query = %v, TTL %d, %v", got, ttl, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type luaDNSClient struct {
|
||||||
|
featureDNS.Client
|
||||||
|
lookup func(string, featureDNS.IPOption) ([]net.IP, uint32, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *luaDNSClient) LookupIP(domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
return c.lookup(domain, option)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLuaDNSClientQuery(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
L.SetContext(context.Background())
|
||||||
|
defer L.RemoveContext()
|
||||||
|
geodata.RegisterLua(L)
|
||||||
|
want := []net.IP{{127, 0, 0, 1}}
|
||||||
|
client := &luaDNSClient{lookup: func(domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
if domain != "MiXeD.Example." || !option.IPv4Enable || option.IPv6Enable || !option.FakeEnable {
|
||||||
|
t.Fatalf("dns.Query arguments = %q, %+v", domain, option)
|
||||||
|
}
|
||||||
|
return want, 42, nil
|
||||||
|
}}
|
||||||
|
RegisterLua(L, client)
|
||||||
|
if err := L.DoString(`
|
||||||
|
local dns = require("xray.dns")
|
||||||
|
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.1")
|
||||||
|
assert(dns.Servers == nil)
|
||||||
|
ips, ttl, err = dns.Query("MiXeD.Example.", true, false, true)
|
||||||
|
assert(not err and ttl == 42 and matcher:AnyMatch(ips))
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := L.GetGlobal("ips").(*lua.LUserData).Value.([]net.IP)
|
||||||
|
if &got[0] != &want[0] {
|
||||||
|
t.Fatal("dns.Query copied the IP slice")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLuaDNSLocalClient(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
L.SetContext(context.Background())
|
||||||
|
defer L.RemoveContext()
|
||||||
|
RegisterLua(L, localdns.New())
|
||||||
|
if err := L.DoString(`
|
||||||
|
local dns = require("xray.dns")
|
||||||
|
assert(dns.Servers[1].ID == "localhost")
|
||||||
|
serverIPs, _, serverErr = dns.Servers[1]:Query("127.0.0.1", true, false, false)
|
||||||
|
clientIPs, _, clientErr = dns.Query("127.0.0.1", true, false, false)
|
||||||
|
assert(not serverErr and not clientErr)
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, name := range []string{"serverIPs", "clientIPs"} {
|
||||||
|
ips := L.GetGlobal(name).(*lua.LUserData).Value.([]net.IP)
|
||||||
|
if len(ips) != 1 || !ips[0].Equal(net.ParseIP("127.0.0.1")) {
|
||||||
|
t.Fatalf("%s = %v", name, ips)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type benchmarkLuaNameServer struct {
|
||||||
|
ips []net.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*benchmarkLuaNameServer) Name() string { return "benchmark" }
|
||||||
|
func (*benchmarkLuaNameServer) IsDisableCache() bool { return true }
|
||||||
|
func (s *benchmarkLuaNameServer) QueryIP(context.Context, string, featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
return s.ips, 60, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BenchmarkLuaDNSHookCall isolates a preloaded Lua hook and its server:Query bridge.
|
||||||
|
// The direct case measures the same DNS client without Lua.
|
||||||
|
func BenchmarkLuaDNSHookCall(b *testing.B) {
|
||||||
|
option := featureDNS.IPOption{IPv4Enable: true}
|
||||||
|
ip := net.ParseIP("127.0.0.1")
|
||||||
|
upstream := &benchmarkLuaNameServer{ips: []net.IP{ip}}
|
||||||
|
client := &Client{server: upstream, ipOption: &option, timeoutMs: time.Second}
|
||||||
|
server := &DNS{clients: []*Client{client}}
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
server.RegisterLua(L)
|
||||||
|
if err := L.DoString(`
|
||||||
|
local server = require("xray.dns").Servers[1]
|
||||||
|
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||||
|
return server:Query(domain, ipv4, ipv6, fake)
|
||||||
|
end
|
||||||
|
`); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
for _, bench := range []struct {
|
||||||
|
name string
|
||||||
|
query func() ([]net.IP, uint32, error)
|
||||||
|
}{
|
||||||
|
{"direct", func() ([]net.IP, uint32, error) { return client.QueryIP(ctx, "example.com", option) }},
|
||||||
|
{"lua_hook", func() ([]net.IP, uint32, error) { return server.CallLuaHook(L, ctx, "example.com", option) }},
|
||||||
|
} {
|
||||||
|
b.Run(bench.name, func(b *testing.B) {
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.ResetTimer()
|
||||||
|
var ips []net.IP
|
||||||
|
var ttl uint32
|
||||||
|
var err error
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
ips, ttl, err = bench.query()
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.StopTimer()
|
||||||
|
if ttl != 60 || len(ips) != 1 || !ips[0].Equal(ip) {
|
||||||
|
b.Fatalf("query() = %v, TTL %d; want %v, TTL 60", ips, ttl, ip)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"github.com/xtls/xray-core/common/geodata"
|
"github.com/xtls/xray-core/common/geodata"
|
||||||
"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/session"
|
||||||
|
"github.com/xtls/xray-core/common/utils"
|
||||||
"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"
|
||||||
"github.com/xtls/xray-core/features/routing"
|
"github.com/xtls/xray-core/features/routing"
|
||||||
@@ -28,6 +29,7 @@ type Server interface {
|
|||||||
|
|
||||||
// Client is the interface for DNS client.
|
// Client is the interface for DNS client.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
|
id string
|
||||||
server Server
|
server Server
|
||||||
skipFallback bool
|
skipFallback bool
|
||||||
expectedIPs geodata.IPMatcher
|
expectedIPs geodata.IPMatcher
|
||||||
@@ -96,7 +98,7 @@ func NewClient(
|
|||||||
ipOption dns.IPOption,
|
ipOption dns.IPOption,
|
||||||
updateRules func(bool),
|
updateRules func(bool),
|
||||||
) (*Client, error) {
|
) (*Client, error) {
|
||||||
client := &Client{}
|
client := &Client{id: ns.Id}
|
||||||
err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
|
err := core.RequireFeatures(ctx, func(dispatcher routing.Dispatcher) error {
|
||||||
// Create a new server for each client for now
|
// Create a new server for each client for now
|
||||||
server, err := NewServer(ctx, ns.Address.AsDestination(), dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
|
server, err := NewServer(ctx, ns.Address.AsDestination(), dispatcher, disableCache, serveStale, serveExpiredTTL, clientIP)
|
||||||
@@ -134,7 +136,7 @@ func NewClient(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var timeoutMs = 4000 * time.Millisecond
|
timeoutMs := 4000 * time.Millisecond
|
||||||
if ns.TimeoutMs > 0 {
|
if ns.TimeoutMs > 0 {
|
||||||
timeoutMs = time.Duration(ns.TimeoutMs) * time.Millisecond
|
timeoutMs = time.Duration(ns.TimeoutMs) * time.Millisecond
|
||||||
}
|
}
|
||||||
@@ -166,7 +168,7 @@ 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) ([]net.IP, uint32, error) {
|
func (c *Client) QueryIP(ctx context.Context, domain string, option dns.IPOption) ([]net.IP, uint32, error) {
|
||||||
if c.checkSystem {
|
if c.checkSystem {
|
||||||
supportIPv4, supportIPv6 := checkRoutes()
|
supportIPv4, supportIPv6 := utils.CheckRoutes()
|
||||||
option.IPv4Enable = option.IPv4Enable && supportIPv4
|
option.IPv4Enable = option.IPv4Enable && supportIPv4
|
||||||
option.IPv6Enable = option.IPv6Enable && supportIPv6
|
option.IPv6Enable = option.IPv6Enable && supportIPv6
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -137,14 +137,32 @@ func (s *DoHNameServer) sendQuery(ctx context.Context, noResponseErrCh chan<- er
|
|||||||
if s.Name()+"." == "DOH//"+fqdn {
|
if s.Name()+"." == "DOH//"+fqdn {
|
||||||
errors.LogError(ctx, s.Name(), " tries to resolve itself! Use IP or set \"hosts\" instead")
|
errors.LogError(ctx, s.Name(), " tries to resolve itself! Use IP or set \"hosts\" instead")
|
||||||
if noResponseErrCh != nil {
|
if noResponseErrCh != nil {
|
||||||
noResponseErrCh <- errors.New("tries to resolve itself!", s.Name())
|
err := errors.New("tries to resolve itself!", s.Name())
|
||||||
|
if option.IPv4Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
|
if option.IPv6Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
// 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
|
// 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(fqdn, option, s.newReqID, genEDNS0Options(s.clientIP, int(crypto.RandBetween(100, 300))))
|
reqs, err := buildReqMsgs(fqdn, option, s.newReqID, genEDNS0Options(s.clientIP, int(crypto.RandBetween(100, 300))))
|
||||||
|
if err != nil {
|
||||||
|
errors.LogErrorInner(ctx, err, "failed to build dns query for ", fqdn)
|
||||||
|
if noResponseErrCh != nil {
|
||||||
|
if option.IPv4Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
|
if option.IPv6Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var deadline time.Time
|
var deadline time.Time
|
||||||
if d, ok := ctx.Deadline(); ok {
|
if d, ok := ctx.Deadline(); ok {
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ type LocalNameServer struct {
|
|||||||
|
|
||||||
// QueryIP implements Server.
|
// QueryIP implements Server.
|
||||||
func (s *LocalNameServer) QueryIP(ctx context.Context, domain string, option dns.IPOption) (ips []net.IP, ttl uint32, err error) {
|
func (s *LocalNameServer) QueryIP(ctx context.Context, domain string, option dns.IPOption) (ips []net.IP, ttl uint32, err error) {
|
||||||
|
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
ips, ttl, err = s.client.LookupIP(domain, option)
|
ips, ttl, err = s.client.LookupIP(domain, option)
|
||||||
|
|
||||||
@@ -50,5 +49,5 @@ func NewLocalNameServer() *LocalNameServer {
|
|||||||
|
|
||||||
// NewLocalDNSClient creates localdns client object for directly lookup in system DNS.
|
// NewLocalDNSClient creates localdns client object for directly lookup in system DNS.
|
||||||
func NewLocalDNSClient(ipOption dns.IPOption) *Client {
|
func NewLocalDNSClient(ipOption dns.IPOption) *Client {
|
||||||
return &Client{server: NewLocalNameServer(), ipOption: &ipOption}
|
return &Client{id: "localhost", server: NewLocalNameServer(), ipOption: &ipOption}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,7 +78,19 @@ func (s *QUICNameServer) getCacheController() *CacheController { return s.cacheC
|
|||||||
func (s *QUICNameServer) sendQuery(ctx context.Context, noResponseErrCh chan<- error, fqdn string, option dns_feature.IPOption) {
|
func (s *QUICNameServer) sendQuery(ctx context.Context, noResponseErrCh chan<- error, fqdn string, option dns_feature.IPOption) {
|
||||||
errors.LogInfo(ctx, s.Name(), " querying: ", fqdn)
|
errors.LogInfo(ctx, s.Name(), " querying: ", fqdn)
|
||||||
|
|
||||||
reqs := buildReqMsgs(fqdn, option, s.newReqID, genEDNS0Options(s.clientIP, 0))
|
reqs, err := buildReqMsgs(fqdn, option, s.newReqID, genEDNS0Options(s.clientIP, 0))
|
||||||
|
if err != nil {
|
||||||
|
errors.LogErrorInner(ctx, err, "failed to build dns query for ", fqdn)
|
||||||
|
if noResponseErrCh != nil {
|
||||||
|
if option.IPv4Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
|
if option.IPv6Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var deadline time.Time
|
var deadline time.Time
|
||||||
if d, ok := ctx.Deadline(); ok {
|
if d, ok := ctx.Deadline(); ok {
|
||||||
|
|||||||
@@ -113,7 +113,19 @@ func (s *TCPNameServer) getCacheController() *CacheController {
|
|||||||
func (s *TCPNameServer) sendQuery(ctx context.Context, noResponseErrCh chan<- error, fqdn string, option dns_feature.IPOption) {
|
func (s *TCPNameServer) sendQuery(ctx context.Context, noResponseErrCh chan<- error, fqdn string, option dns_feature.IPOption) {
|
||||||
errors.LogInfo(ctx, s.Name(), " querying DNS for: ", fqdn)
|
errors.LogInfo(ctx, s.Name(), " querying DNS for: ", fqdn)
|
||||||
|
|
||||||
reqs := buildReqMsgs(fqdn, option, s.newReqID, genEDNS0Options(s.clientIP, 0))
|
reqs, err := buildReqMsgs(fqdn, option, s.newReqID, genEDNS0Options(s.clientIP, 0))
|
||||||
|
if err != nil {
|
||||||
|
errors.LogErrorInner(ctx, err, "failed to build dns query for ", fqdn)
|
||||||
|
if noResponseErrCh != nil {
|
||||||
|
if option.IPv4Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
|
if option.IPv6Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var deadline time.Time
|
var deadline time.Time
|
||||||
if d, ok := ctx.Deadline(); ok {
|
if d, ok := ctx.Deadline(); ok {
|
||||||
|
|||||||
@@ -131,8 +131,6 @@ func (s *ClassicNameServer) HandleResponse(ctx context.Context, packet *udp_prot
|
|||||||
newReq.msg = &newMsg
|
newReq.msg = &newMsg
|
||||||
s.addPendingRequest(&newReq)
|
s.addPendingRequest(&newReq)
|
||||||
b, _ := dns.PackMessage(newReq.msg)
|
b, _ := dns.PackMessage(newReq.msg)
|
||||||
copyDest := net.UDPDestination(s.address.Address, s.address.Port)
|
|
||||||
b.UDP = ©Dest
|
|
||||||
s.udpServer.Dispatch(toDnsContext(newReq.ctx, s.address.String()), *s.address, b)
|
s.udpServer.Dispatch(toDnsContext(newReq.ctx, s.address.String()), *s.address, b)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -163,7 +161,19 @@ func (s *ClassicNameServer) getCacheController() *CacheController {
|
|||||||
func (s *ClassicNameServer) sendQuery(ctx context.Context, noResponseErrCh chan<- error, fqdn string, option dns_feature.IPOption) {
|
func (s *ClassicNameServer) sendQuery(ctx context.Context, noResponseErrCh chan<- error, fqdn string, option dns_feature.IPOption) {
|
||||||
errors.LogInfo(ctx, s.Name(), " querying DNS for: ", fqdn)
|
errors.LogInfo(ctx, s.Name(), " querying DNS for: ", fqdn)
|
||||||
|
|
||||||
reqs := buildReqMsgs(fqdn, option, s.newReqID, genEDNS0Options(s.clientIP, 0))
|
reqs, err := buildReqMsgs(fqdn, option, s.newReqID, genEDNS0Options(s.clientIP, 0))
|
||||||
|
if err != nil {
|
||||||
|
errors.LogErrorInner(ctx, err, "failed to build dns query for ", fqdn)
|
||||||
|
if noResponseErrCh != nil {
|
||||||
|
if option.IPv4Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
|
if option.IPv6Enable {
|
||||||
|
noResponseErrCh <- err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
for _, req := range reqs {
|
for _, req := range reqs {
|
||||||
udpReq := &udpDnsRequest{
|
udpReq := &udpDnsRequest{
|
||||||
@@ -179,8 +189,6 @@ func (s *ClassicNameServer) sendQuery(ctx context.Context, noResponseErrCh chan<
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
copyDest := net.UDPDestination(s.address.Address, s.address.Port)
|
|
||||||
b.UDP = ©Dest
|
|
||||||
s.udpServer.Dispatch(toDnsContext(ctx, s.address.String()), *s.address, b)
|
s.udpServer.Dispatch(toDnsContext(ctx, s.address.String()), *s.address, b)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
"github.com/xtls/xray-core/common/geodata"
|
||||||
|
"github.com/xtls/xray-core/common/log"
|
||||||
|
luamgr "github.com/xtls/xray-core/common/lua"
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
"github.com/xtls/xray-core/features/dns"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
)
|
||||||
|
|
||||||
|
const scriptExecutionTimeout = 10 * time.Second
|
||||||
|
|
||||||
|
type scriptEngine struct {
|
||||||
|
dns *DNS
|
||||||
|
pool *luamgr.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newScriptEngine(path string, server *DNS) (*scriptEngine, error) {
|
||||||
|
program, err := luamgr.CompileFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
e := &scriptEngine{dns: server}
|
||||||
|
e.pool, err = luamgr.NewPool(server.ctx, func(poolCtx context.Context) (*lua.LState, error) {
|
||||||
|
initCtx, cancel := context.WithTimeout(poolCtx, scriptExecutionTimeout)
|
||||||
|
defer cancel()
|
||||||
|
L, err := program.NewState(initCtx, func(L *lua.LState) {
|
||||||
|
geodata.RegisterLua(L)
|
||||||
|
log.RegisterLua(L)
|
||||||
|
server.RegisterLua(L)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if L.GetGlobal("HandleDNSQuery").Type() != lua.LTFunction {
|
||||||
|
L.Close()
|
||||||
|
return nil, errors.New("DNS script must define HandleDNSQuery(domain, ipv4, ipv6, fake)")
|
||||||
|
}
|
||||||
|
return L, nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
errors.LogInfo(server.ctx, "DNS script initialized from ", path)
|
||||||
|
return e, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *scriptEngine) close() {
|
||||||
|
e.pool.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *scriptEngine) query(domain string, option dns.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
L, err := e.pool.Acquire()
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
reusable := false
|
||||||
|
defer func() {
|
||||||
|
e.pool.Release(L, reusable)
|
||||||
|
}()
|
||||||
|
queryCtx, cancel := context.WithTimeout(e.pool.Context(), scriptExecutionTimeout)
|
||||||
|
defer cancel()
|
||||||
|
ips, ttl, err := e.dns.CallLuaHook(L, queryCtx, domain, option)
|
||||||
|
if err == nil {
|
||||||
|
reusable = true
|
||||||
|
}
|
||||||
|
return ips, ttl, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
featureDNS "github.com/xtls/xray-core/features/dns"
|
||||||
|
)
|
||||||
|
|
||||||
|
type geoIPScriptNameServer struct {
|
||||||
|
name string
|
||||||
|
answers map[string]net.IP
|
||||||
|
ttl uint32
|
||||||
|
calls int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *geoIPScriptNameServer) Name() string { return s.name }
|
||||||
|
func (s *geoIPScriptNameServer) IsDisableCache() bool { return true }
|
||||||
|
|
||||||
|
func (s *geoIPScriptNameServer) QueryIP(ctx context.Context, domain string, _ featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
s.calls++
|
||||||
|
ip, ok := s.answers[domain]
|
||||||
|
if !ok {
|
||||||
|
return nil, 0, featureDNS.ErrEmptyResponse
|
||||||
|
}
|
||||||
|
return []net.IP{ip}, s.ttl, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDNSScriptGeoIPFallback(t *testing.T) {
|
||||||
|
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||||
|
script := `
|
||||||
|
local servers = require("xray.dns").Servers
|
||||||
|
local us_ips = require("xray.geodata").BuildIPMatcher("geoip:us")
|
||||||
|
|
||||||
|
local by_id = {}
|
||||||
|
for _, server in ipairs(servers) do
|
||||||
|
by_id[server.ID] = server
|
||||||
|
end
|
||||||
|
assert(by_id.primary and by_id.fallback, "primary and fallback DNS servers are required")
|
||||||
|
|
||||||
|
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||||
|
local ips, ttl, err = by_id.primary:Query(domain, ipv4, ipv6, fake)
|
||||||
|
if not err and us_ips:AnyMatch(ips) then
|
||||||
|
return ips, ttl, nil
|
||||||
|
end
|
||||||
|
return by_id.fallback:Query(domain, ipv4, ipv6, fake)
|
||||||
|
end
|
||||||
|
`
|
||||||
|
scriptPath := filepath.Join(t.TempDir(), "geoip_fallback.lua")
|
||||||
|
if err := os.WriteFile(scriptPath, []byte(script), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
primary := &geoIPScriptNameServer{
|
||||||
|
name: "primary",
|
||||||
|
answers: map[string]net.IP{
|
||||||
|
"us.example": net.ParseIP("2001:4860:4860::8888"),
|
||||||
|
"other.example": net.ParseIP("127.0.0.1"),
|
||||||
|
},
|
||||||
|
ttl: 30,
|
||||||
|
}
|
||||||
|
fallback := &geoIPScriptNameServer{
|
||||||
|
name: "fallback",
|
||||||
|
answers: map[string]net.IP{"other.example": net.ParseIP("9.9.9.9")},
|
||||||
|
ttl: 60,
|
||||||
|
}
|
||||||
|
option := featureDNS.IPOption{IPv4Enable: true, IPv6Enable: true}
|
||||||
|
hosts, err := NewStaticHosts(nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
server := &DNS{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hosts: hosts,
|
||||||
|
ipOption: &option,
|
||||||
|
scriptPath: scriptPath,
|
||||||
|
clients: []*Client{
|
||||||
|
{id: "primary", server: primary, ipOption: &option, timeoutMs: 2 * time.Second},
|
||||||
|
{id: "fallback", server: fallback, ipOption: &option, timeoutMs: 2 * time.Second},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if err := server.Start(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
for _, tc := range []struct {
|
||||||
|
domain string
|
||||||
|
ip net.IP
|
||||||
|
ttl uint32
|
||||||
|
}{
|
||||||
|
{"Us.Example.", net.ParseIP("2001:4860:4860::8888"), 30},
|
||||||
|
{"other.example", net.ParseIP("9.9.9.9"), 60},
|
||||||
|
} {
|
||||||
|
ips, ttl, err := server.LookupIP(tc.domain, option)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("LookupIP(%q): %v", tc.domain, err)
|
||||||
|
}
|
||||||
|
if ttl != tc.ttl || len(ips) != 1 || !ips[0].Equal(tc.ip) {
|
||||||
|
t.Fatalf("LookupIP(%q) = %v, TTL %d; want %v, TTL %d", tc.domain, ips, ttl, tc.ip, tc.ttl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if primary.calls != 2 || fallback.calls != 1 {
|
||||||
|
t.Fatalf("upstream calls: primary %d, fallback %d; want 2 and 1", primary.calls, fallback.calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDNSScriptRejectsInvalidStartup(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
script string
|
||||||
|
}{
|
||||||
|
{"syntax", "function HandleDNSQuery("},
|
||||||
|
{"missing hook", "value = 1"},
|
||||||
|
{"top-level error", `error("setup failed")`},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "script.lua")
|
||||||
|
if err := os.WriteFile(path, []byte(tc.script), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
server := &DNS{ctx: context.Background(), scriptPath: path}
|
||||||
|
if err := server.Start(); err == nil {
|
||||||
|
t.Fatal("Start accepted an invalid DNS script")
|
||||||
|
}
|
||||||
|
if server.script != nil {
|
||||||
|
t.Fatal("Start retained a script engine after failure")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDNSScriptHookErrorAndFakeDNSOption(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "script.lua")
|
||||||
|
script := `
|
||||||
|
local server = require("xray.dns").Servers[1]
|
||||||
|
local log = require("xray.log")
|
||||||
|
log.Info("DNS script loaded")
|
||||||
|
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||||
|
log.Debug("DNS query: ", domain)
|
||||||
|
if domain == "bad.example" then error("script failure") end
|
||||||
|
local ips, ttl, err = server:Query(domain, ipv4, ipv6, fake)
|
||||||
|
if err then log.Error("DNS failed: ", err) end
|
||||||
|
return ips, ttl, err
|
||||||
|
end
|
||||||
|
`
|
||||||
|
if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
option := featureDNS.IPOption{IPv4Enable: true}
|
||||||
|
hosts, err := NewStaticHosts(nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
upstream := &geoIPScriptNameServer{
|
||||||
|
name: "FakeDNS",
|
||||||
|
answers: map[string]net.IP{"good.example": net.ParseIP("198.18.0.1")},
|
||||||
|
ttl: 30,
|
||||||
|
}
|
||||||
|
server := &DNS{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hosts: hosts,
|
||||||
|
ipOption: &option,
|
||||||
|
scriptPath: path,
|
||||||
|
clients: []*Client{{id: "fake", server: upstream, ipOption: &option, timeoutMs: time.Second}},
|
||||||
|
}
|
||||||
|
if err := server.Start(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer server.Close()
|
||||||
|
|
||||||
|
if _, _, err := server.LookupIP("bad.example", option); err == nil || !strings.Contains(err.Error(), "script failure") {
|
||||||
|
t.Fatalf("hook failure = %v, want script failure", err)
|
||||||
|
}
|
||||||
|
if _, _, err := server.LookupIP("good.example", option); err != featureDNS.ErrEmptyResponse {
|
||||||
|
t.Fatalf("FakeDNS without FakeEnable = %v, want ErrEmptyResponse", err)
|
||||||
|
}
|
||||||
|
if upstream.calls != 0 {
|
||||||
|
t.Fatalf("FakeDNS was queried without FakeEnable: %d calls", upstream.calls)
|
||||||
|
}
|
||||||
|
withFake := featureDNS.IPOption{IPv4Enable: true, FakeEnable: true}
|
||||||
|
ips, ttl, err := server.LookupIP("good.example", withFake)
|
||||||
|
if err != nil || ttl != 30 || len(ips) != 1 || !ips[0].Equal(net.ParseIP("198.18.0.1")) {
|
||||||
|
t.Fatalf("FakeDNS with FakeEnable = %v, TTL %d, %v", ips, ttl, err)
|
||||||
|
}
|
||||||
|
if upstream.calls != 1 {
|
||||||
|
t.Fatalf("FakeDNS query count = %d, want 1", upstream.calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||||
|
// versions:
|
||||||
|
// protoc-gen-go v1.36.11
|
||||||
|
// protoc v6.33.5
|
||||||
|
// source: app/geodata/config.proto
|
||||||
|
|
||||||
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||||
|
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||||
|
reflect "reflect"
|
||||||
|
sync "sync"
|
||||||
|
unsafe "unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Verify that this generated code is sufficiently up-to-date.
|
||||||
|
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||||
|
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||||
|
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||||
|
)
|
||||||
|
|
||||||
|
type Asset struct {
|
||||||
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
|
Url string `protobuf:"bytes,1,opt,name=url,proto3" json:"url,omitempty"`
|
||||||
|
File string `protobuf:"bytes,2,opt,name=file,proto3" json:"file,omitempty"`
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Asset) Reset() {
|
||||||
|
*x = Asset{}
|
||||||
|
mi := &file_app_geodata_config_proto_msgTypes[0]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Asset) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Asset) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *Asset) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_app_geodata_config_proto_msgTypes[0]
|
||||||
|
if x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use Asset.ProtoReflect.Descriptor instead.
|
||||||
|
func (*Asset) Descriptor() ([]byte, []int) {
|
||||||
|
return file_app_geodata_config_proto_rawDescGZIP(), []int{0}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Asset) GetUrl() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Url
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Asset) GetFile() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.File
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
|
Cron string `protobuf:"bytes,1,opt,name=cron,proto3" json:"cron,omitempty"`
|
||||||
|
Outbound string `protobuf:"bytes,2,opt,name=outbound,proto3" json:"outbound,omitempty"`
|
||||||
|
Assets []*Asset `protobuf:"bytes,3,rep,name=assets,proto3" json:"assets,omitempty"`
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Config) Reset() {
|
||||||
|
*x = Config{}
|
||||||
|
mi := &file_app_geodata_config_proto_msgTypes[1]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Config) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Config) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *Config) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_app_geodata_config_proto_msgTypes[1]
|
||||||
|
if x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use Config.ProtoReflect.Descriptor instead.
|
||||||
|
func (*Config) Descriptor() ([]byte, []int) {
|
||||||
|
return file_app_geodata_config_proto_rawDescGZIP(), []int{1}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Config) GetCron() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Cron
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Config) GetOutbound() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Outbound
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Config) GetAssets() []*Asset {
|
||||||
|
if x != nil {
|
||||||
|
return x.Assets
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var File_app_geodata_config_proto protoreflect.FileDescriptor
|
||||||
|
|
||||||
|
const file_app_geodata_config_proto_rawDesc = "" +
|
||||||
|
"\n" +
|
||||||
|
"\x18app/geodata/config.proto\x12\x10xray.app.geodata\"-\n" +
|
||||||
|
"\x05Asset\x12\x10\n" +
|
||||||
|
"\x03url\x18\x01 \x01(\tR\x03url\x12\x12\n" +
|
||||||
|
"\x04file\x18\x02 \x01(\tR\x04file\"i\n" +
|
||||||
|
"\x06Config\x12\x12\n" +
|
||||||
|
"\x04cron\x18\x01 \x01(\tR\x04cron\x12\x1a\n" +
|
||||||
|
"\boutbound\x18\x02 \x01(\tR\boutbound\x12/\n" +
|
||||||
|
"\x06assets\x18\x03 \x03(\v2\x17.xray.app.geodata.AssetR\x06assetsBR\n" +
|
||||||
|
"\x14com.xray.app.geodataP\x01Z%github.com/xtls/xray-core/app/geodata\xaa\x02\x10Xray.App.Geodatab\x06proto3"
|
||||||
|
|
||||||
|
var (
|
||||||
|
file_app_geodata_config_proto_rawDescOnce sync.Once
|
||||||
|
file_app_geodata_config_proto_rawDescData []byte
|
||||||
|
)
|
||||||
|
|
||||||
|
func file_app_geodata_config_proto_rawDescGZIP() []byte {
|
||||||
|
file_app_geodata_config_proto_rawDescOnce.Do(func() {
|
||||||
|
file_app_geodata_config_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_app_geodata_config_proto_rawDesc), len(file_app_geodata_config_proto_rawDesc)))
|
||||||
|
})
|
||||||
|
return file_app_geodata_config_proto_rawDescData
|
||||||
|
}
|
||||||
|
|
||||||
|
var file_app_geodata_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
|
||||||
|
var file_app_geodata_config_proto_goTypes = []any{
|
||||||
|
(*Asset)(nil), // 0: xray.app.geodata.Asset
|
||||||
|
(*Config)(nil), // 1: xray.app.geodata.Config
|
||||||
|
}
|
||||||
|
var file_app_geodata_config_proto_depIdxs = []int32{
|
||||||
|
0, // 0: xray.app.geodata.Config.assets:type_name -> xray.app.geodata.Asset
|
||||||
|
1, // [1:1] is the sub-list for method output_type
|
||||||
|
1, // [1:1] is the sub-list for method input_type
|
||||||
|
1, // [1:1] is the sub-list for extension type_name
|
||||||
|
1, // [1:1] is the sub-list for extension extendee
|
||||||
|
0, // [0:1] is the sub-list for field type_name
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() { file_app_geodata_config_proto_init() }
|
||||||
|
func file_app_geodata_config_proto_init() {
|
||||||
|
if File_app_geodata_config_proto != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
type x struct{}
|
||||||
|
out := protoimpl.TypeBuilder{
|
||||||
|
File: protoimpl.DescBuilder{
|
||||||
|
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||||
|
RawDescriptor: unsafe.Slice(unsafe.StringData(file_app_geodata_config_proto_rawDesc), len(file_app_geodata_config_proto_rawDesc)),
|
||||||
|
NumEnums: 0,
|
||||||
|
NumMessages: 2,
|
||||||
|
NumExtensions: 0,
|
||||||
|
NumServices: 0,
|
||||||
|
},
|
||||||
|
GoTypes: file_app_geodata_config_proto_goTypes,
|
||||||
|
DependencyIndexes: file_app_geodata_config_proto_depIdxs,
|
||||||
|
MessageInfos: file_app_geodata_config_proto_msgTypes,
|
||||||
|
}.Build()
|
||||||
|
File_app_geodata_config_proto = out.File
|
||||||
|
file_app_geodata_config_proto_goTypes = nil
|
||||||
|
file_app_geodata_config_proto_depIdxs = nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package xray.app.geodata;
|
||||||
|
option csharp_namespace = "Xray.App.Geodata";
|
||||||
|
option go_package = "github.com/xtls/xray-core/app/geodata";
|
||||||
|
option java_package = "com.xray.app.geodata";
|
||||||
|
option java_multiple_files = true;
|
||||||
|
|
||||||
|
message Asset {
|
||||||
|
string url = 1;
|
||||||
|
|
||||||
|
string file = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
message Config {
|
||||||
|
string cron = 1;
|
||||||
|
|
||||||
|
string outbound = 2;
|
||||||
|
|
||||||
|
repeated Asset assets = 3;
|
||||||
|
}
|
||||||
@@ -0,0 +1,346 @@
|
|||||||
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
go_errors "errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
utls "github.com/refraction-networking/utls"
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
"github.com/xtls/xray-core/common/platform/filesystem"
|
||||||
|
"github.com/xtls/xray-core/common/task"
|
||||||
|
"github.com/xtls/xray-core/common/utils"
|
||||||
|
"github.com/xtls/xray-core/features/routing"
|
||||||
|
"github.com/xtls/xray-core/transport/internet/tagged"
|
||||||
|
"golang.org/x/net/http2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const idleTimeout = 30 * time.Second
|
||||||
|
|
||||||
|
type stage struct {
|
||||||
|
target string
|
||||||
|
temp string
|
||||||
|
}
|
||||||
|
|
||||||
|
type downloader struct {
|
||||||
|
ctx context.Context
|
||||||
|
httpClient *http.Client
|
||||||
|
httpsClient *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
type idleConn struct {
|
||||||
|
net.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *idleConn) Read(b []byte) (int, error) {
|
||||||
|
t := time.AfterFunc(idleTimeout, func() {
|
||||||
|
_ = c.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
n, err := c.Conn.Read(b)
|
||||||
|
if !t.Stop() {
|
||||||
|
_ = c.Close()
|
||||||
|
return n, errors.New("connection idle timeout")
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *idleConn) Write(b []byte) (int, error) {
|
||||||
|
return c.Conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDownloader(ctx context.Context, dispatcher routing.Dispatcher, outbound string) *downloader {
|
||||||
|
return &downloader{
|
||||||
|
ctx: ctx,
|
||||||
|
httpClient: newClient(ctx, dispatcher, outbound, false),
|
||||||
|
httpsClient: newClient(ctx, dispatcher, outbound, true),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newClient(baseCtx context.Context, dispatcher routing.Dispatcher, outbound string, isHTTPS bool) *http.Client {
|
||||||
|
dial := func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
var conn net.Conn
|
||||||
|
err := task.Run(ctx, func() error {
|
||||||
|
if tagged.Dialer == nil {
|
||||||
|
return errors.New("tagged dialer is not initialized")
|
||||||
|
}
|
||||||
|
dest, err := net.ParseDestination(network + ":" + address)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("cannot understand address").Base(err)
|
||||||
|
}
|
||||||
|
c, err := tagged.Dialer(baseCtx, dispatcher, dest, outbound)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("cannot dial remote address ", dest).Base(err)
|
||||||
|
}
|
||||||
|
conn = c
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("cannot finish connection").Base(err)
|
||||||
|
}
|
||||||
|
return &idleConn{
|
||||||
|
Conn: conn,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
if isHTTPS {
|
||||||
|
return &http.Client{
|
||||||
|
Transport: &http2.Transport{
|
||||||
|
DialTLSContext: func(ctx context.Context, network string, address string, cfg *tls.Config) (net.Conn, error) {
|
||||||
|
conn, err := dial(ctx, network, address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
host, _, _ := net.SplitHostPort(address)
|
||||||
|
tlsConn := utls.UClient(conn, &utls.Config{ServerName: host}, utls.HelloChrome_Auto)
|
||||||
|
handshakeCtx, cancel := context.WithTimeout(ctx, idleTimeout)
|
||||||
|
defer cancel()
|
||||||
|
if err := tlsConn.HandshakeContext(handshakeCtx); err != nil {
|
||||||
|
conn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return tlsConn, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
|
if req.URL.Scheme != "https" {
|
||||||
|
return errors.New("redirected to non-https URL: ", req.URL.String())
|
||||||
|
}
|
||||||
|
if len(via) >= 10 {
|
||||||
|
return errors.New("stopped after 10 redirects")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return &http.Client{
|
||||||
|
Transport: &http.Transport{
|
||||||
|
Proxy: nil,
|
||||||
|
DisableKeepAlives: true,
|
||||||
|
DialContext: dial,
|
||||||
|
ResponseHeaderTimeout: idleTimeout,
|
||||||
|
},
|
||||||
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
|
if req.URL.Scheme != "https" {
|
||||||
|
return errors.New("redirected to non-https URL: ", req.URL.String())
|
||||||
|
}
|
||||||
|
if len(via) >= 10 {
|
||||||
|
return errors.New("stopped after 10 redirects")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *downloader) download(assets []*Asset) ([]stage, error) {
|
||||||
|
staged := make([]stage, 0, len(assets))
|
||||||
|
for _, asset := range assets {
|
||||||
|
stage, err := d.downloadOne(asset)
|
||||||
|
if err != nil {
|
||||||
|
clean(staged)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
staged = append(staged, stage)
|
||||||
|
}
|
||||||
|
return staged, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *downloader) downloadOne(asset *Asset) (stage, error) {
|
||||||
|
target, err := filesystem.ResolveAsset(asset.File)
|
||||||
|
if err != nil {
|
||||||
|
return stage{}, err
|
||||||
|
}
|
||||||
|
errors.LogInfo(d.ctx, "downloading geodata asset from ", asset.Url, " to ", target)
|
||||||
|
|
||||||
|
temp, err := tempFile(target, ".tmp")
|
||||||
|
if err != nil {
|
||||||
|
return stage{}, err
|
||||||
|
}
|
||||||
|
tempName := temp.Name()
|
||||||
|
keepTemp := false
|
||||||
|
defer func() {
|
||||||
|
if !keepTemp {
|
||||||
|
os.Remove(tempName)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := d.fetch(asset.Url, temp); err != nil {
|
||||||
|
temp.Close()
|
||||||
|
return stage{}, err
|
||||||
|
}
|
||||||
|
if err := temp.Chmod(0o644); err != nil {
|
||||||
|
temp.Close()
|
||||||
|
return stage{}, err
|
||||||
|
}
|
||||||
|
if err := temp.Close(); err != nil {
|
||||||
|
return stage{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
keepTemp = true
|
||||||
|
return stage{
|
||||||
|
target: target,
|
||||||
|
temp: tempName,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *downloader) fetch(rawURL string, writer io.Writer) error {
|
||||||
|
req, err := http.NewRequestWithContext(d.ctx, http.MethodGet, rawURL, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
utils.TryDefaultHeadersWith(req.Header, "nav")
|
||||||
|
|
||||||
|
var client *http.Client
|
||||||
|
if req.URL.Scheme == "https" {
|
||||||
|
client = d.httpsClient
|
||||||
|
} else {
|
||||||
|
client = d.httpClient
|
||||||
|
}
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||||
|
io.Copy(io.Discard, resp.Body)
|
||||||
|
return errors.New("unexpected status code: ", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := io.Copy(writer, resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return errors.New("empty response body")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func clean(assets []stage) {
|
||||||
|
for _, asset := range assets {
|
||||||
|
if asset.temp != "" {
|
||||||
|
os.Remove(asset.temp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type tx struct {
|
||||||
|
swaps []swap
|
||||||
|
}
|
||||||
|
|
||||||
|
type swap struct {
|
||||||
|
target string
|
||||||
|
backup string
|
||||||
|
hadOriginal bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func swapAll(assets []stage) (*tx, error) {
|
||||||
|
t := &tx{}
|
||||||
|
for _, asset := range assets {
|
||||||
|
s, err := swapOne(asset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Combine(err, t.rollback())
|
||||||
|
}
|
||||||
|
t.swaps = append(t.swaps, s)
|
||||||
|
}
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func swapOne(asset stage) (swap, error) {
|
||||||
|
backup, err := backupFile(asset.target)
|
||||||
|
if err != nil {
|
||||||
|
return swap{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s := swap{
|
||||||
|
target: asset.target,
|
||||||
|
backup: backup,
|
||||||
|
}
|
||||||
|
if err := os.Rename(asset.target, backup); err != nil {
|
||||||
|
if !go_errors.Is(err, os.ErrNotExist) {
|
||||||
|
return swap{}, err
|
||||||
|
}
|
||||||
|
if err := os.Remove(backup); err != nil && !go_errors.Is(err, os.ErrNotExist) {
|
||||||
|
return swap{}, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
s.hadOriginal = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.Rename(asset.temp, asset.target); err != nil {
|
||||||
|
if s.hadOriginal {
|
||||||
|
if restoreErr := os.Rename(backup, asset.target); restoreErr != nil {
|
||||||
|
return swap{}, errors.Combine(err, restoreErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return swap{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *tx) rollback() error {
|
||||||
|
var errs []error
|
||||||
|
for i := len(t.swaps) - 1; i >= 0; i-- {
|
||||||
|
if err := t.swaps[i].rollback(); err != nil {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.Combine(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s swap) rollback() error {
|
||||||
|
var errs []error
|
||||||
|
if err := os.Remove(s.target); err != nil && !go_errors.Is(err, os.ErrNotExist) {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
if s.hadOriginal {
|
||||||
|
if err := os.Rename(s.backup, s.target); err != nil {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
} else if err := os.Remove(s.backup); err != nil && !go_errors.Is(err, os.ErrNotExist) {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
return errors.Combine(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *tx) commit() error {
|
||||||
|
var errs []error
|
||||||
|
for _, swap := range t.swaps {
|
||||||
|
if err := os.Remove(swap.backup); err != nil && !go_errors.Is(err, os.ErrNotExist) {
|
||||||
|
errs = append(errs, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.Combine(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func tempFile(target string, suffix string) (*os.File, error) {
|
||||||
|
dir := filepath.Dir(target)
|
||||||
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return os.CreateTemp(dir, "."+filepath.Base(target)+".*"+suffix)
|
||||||
|
}
|
||||||
|
|
||||||
|
func backupFile(target string) (string, error) {
|
||||||
|
file, err := tempFile(target, ".bak")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
name := file.Name()
|
||||||
|
if err := file.Close(); err != nil {
|
||||||
|
os.Remove(name)
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := os.Remove(name); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/robfig/cron/v3"
|
||||||
|
"github.com/xtls/xray-core/common"
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
commongeodata "github.com/xtls/xray-core/common/geodata"
|
||||||
|
"github.com/xtls/xray-core/core"
|
||||||
|
"github.com/xtls/xray-core/features/routing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Instance struct {
|
||||||
|
assets []*Asset
|
||||||
|
downloader *downloader
|
||||||
|
tasker *cron.Cron
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
running bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(ctx context.Context, config *Config) (*Instance, error) {
|
||||||
|
if config.Cron == "" {
|
||||||
|
return &Instance{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
g := &Instance{
|
||||||
|
assets: config.Assets,
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(g.assets) > 0 {
|
||||||
|
var dispatcher routing.Dispatcher
|
||||||
|
if err := core.RequireFeatures(ctx, func(d routing.Dispatcher) {
|
||||||
|
dispatcher = d
|
||||||
|
}); err != nil {
|
||||||
|
return nil, errors.New("failed to get dispatcher for geodata downloader").Base(err)
|
||||||
|
}
|
||||||
|
g.downloader = newDownloader(ctx, dispatcher, config.Outbound)
|
||||||
|
}
|
||||||
|
|
||||||
|
g.tasker = cron.New(
|
||||||
|
cron.WithChain(cron.SkipIfStillRunning(cron.DiscardLogger)),
|
||||||
|
cron.WithLogger(cron.DiscardLogger),
|
||||||
|
)
|
||||||
|
if _, err := g.tasker.AddFunc(config.Cron, g.execute); err != nil {
|
||||||
|
return nil, errors.New("invalid geodata cron").Base(err)
|
||||||
|
}
|
||||||
|
errors.LogInfo(ctx, "scheduled geodata reload with cron: ", config.Cron)
|
||||||
|
|
||||||
|
return g, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Instance) execute() {
|
||||||
|
var err error
|
||||||
|
if g.downloader != nil {
|
||||||
|
err = g.reloadWithUpdate()
|
||||||
|
} else {
|
||||||
|
err = reload()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
errors.LogErrorInner(context.Background(), err, "scheduled geodata reload failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Instance) reloadWithUpdate() error {
|
||||||
|
staged, err := g.downloader.download(g.assets)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer clean(staged)
|
||||||
|
|
||||||
|
tx, err := swapAll(staged)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := reload(); err != nil {
|
||||||
|
errors.LogErrorInner(context.Background(), err, "failed to reload geodata after downloading assets, rolling back")
|
||||||
|
rollbackErr := tx.rollback()
|
||||||
|
return errors.Combine(err, rollbackErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.commit()
|
||||||
|
}
|
||||||
|
|
||||||
|
func reload() error {
|
||||||
|
return errors.Combine(commongeodata.IPReg.Reload(), commongeodata.DomainReg.Reload())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Instance) Type() interface{} {
|
||||||
|
return (*Instance)(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Instance) Start() error {
|
||||||
|
g.mu.Lock()
|
||||||
|
defer g.mu.Unlock()
|
||||||
|
|
||||||
|
if g.running {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.tasker != nil {
|
||||||
|
g.tasker.Start()
|
||||||
|
}
|
||||||
|
|
||||||
|
g.running = true
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *Instance) Close() error {
|
||||||
|
g.mu.Lock()
|
||||||
|
defer g.mu.Unlock()
|
||||||
|
|
||||||
|
if !g.running {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if g.tasker != nil {
|
||||||
|
<-g.tasker.Stop().Done()
|
||||||
|
}
|
||||||
|
|
||||||
|
g.running = false
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, cfg interface{}) (interface{}, error) {
|
||||||
|
return New(ctx, cfg.(*Config))
|
||||||
|
}))
|
||||||
|
}
|
||||||
+148
-57
@@ -2,15 +2,18 @@ package metrics
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
stderrors "errors"
|
||||||
"expvar"
|
"expvar"
|
||||||
|
stdnet "net"
|
||||||
"net/http"
|
"net/http"
|
||||||
_ "net/http/pprof"
|
"net/http/pprof"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/app/observatory"
|
"github.com/xtls/xray-core/app/observatory"
|
||||||
"github.com/xtls/xray-core/common"
|
"github.com/xtls/xray-core/common"
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/net"
|
xnet "github.com/xtls/xray-core/common/net"
|
||||||
"github.com/xtls/xray-core/common/signal/done"
|
"github.com/xtls/xray-core/common/signal/done"
|
||||||
"github.com/xtls/xray-core/core"
|
"github.com/xtls/xray-core/core"
|
||||||
"github.com/xtls/xray-core/features/extension"
|
"github.com/xtls/xray-core/features/extension"
|
||||||
@@ -21,15 +24,17 @@ import (
|
|||||||
type MetricsHandler struct {
|
type MetricsHandler struct {
|
||||||
ohm outbound.Manager
|
ohm outbound.Manager
|
||||||
statsManager feature_stats.Manager
|
statsManager feature_stats.Manager
|
||||||
observatory extension.Observatory
|
ctx context.Context
|
||||||
tag string
|
tag string
|
||||||
listen string
|
listen string
|
||||||
tcpListener net.Listener
|
tcpListener xnet.Listener
|
||||||
|
listener *OutboundListener
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewMetricsHandler creates a new MetricsHandler based on the given config.
|
// NewMetricsHandler creates a new MetricsHandler based on the given config.
|
||||||
func NewMetricsHandler(ctx context.Context, config *Config) (*MetricsHandler, error) {
|
func NewMetricsHandler(ctx context.Context, config *Config) (*MetricsHandler, error) {
|
||||||
c := &MetricsHandler{
|
c := &MetricsHandler{
|
||||||
|
ctx: ctx,
|
||||||
tag: config.Tag,
|
tag: config.Tag,
|
||||||
listen: config.Listen,
|
listen: config.Listen,
|
||||||
}
|
}
|
||||||
@@ -37,46 +42,6 @@ func NewMetricsHandler(ctx context.Context, config *Config) (*MetricsHandler, er
|
|||||||
c.statsManager = sm
|
c.statsManager = sm
|
||||||
c.ohm = om
|
c.ohm = om
|
||||||
}))
|
}))
|
||||||
expvar.Publish("stats", expvar.Func(func() interface{} {
|
|
||||||
resp := map[string]map[string]map[string]int64{
|
|
||||||
"inbound": {},
|
|
||||||
"outbound": {},
|
|
||||||
"user": {},
|
|
||||||
}
|
|
||||||
c.statsManager.VisitCounters(func(name string, counter feature_stats.Counter) bool {
|
|
||||||
nameSplit := strings.Split(name, ">>>")
|
|
||||||
typeName, tagOrUser, direction := nameSplit[0], nameSplit[1], nameSplit[3]
|
|
||||||
if item, found := resp[typeName][tagOrUser]; found {
|
|
||||||
item[direction] = counter.Value()
|
|
||||||
} else {
|
|
||||||
resp[typeName][tagOrUser] = map[string]int64{
|
|
||||||
direction: counter.Value(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
return resp
|
|
||||||
}))
|
|
||||||
expvar.Publish("observatory", expvar.Func(func() interface{} {
|
|
||||||
if c.observatory == nil {
|
|
||||||
common.Must(core.RequireFeatures(ctx, func(observatory extension.Observatory) error {
|
|
||||||
c.observatory = observatory
|
|
||||||
return nil
|
|
||||||
}))
|
|
||||||
if c.observatory == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resp := map[string]*observatory.OutboundStatus{}
|
|
||||||
if o, err := c.observatory.GetObservation(context.Background()); err != nil {
|
|
||||||
return err
|
|
||||||
} else {
|
|
||||||
for _, x := range o.(*observatory.ObservationResult).GetStatus() {
|
|
||||||
resp[x.OutboundTag] = x
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return resp
|
|
||||||
}))
|
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,46 +50,172 @@ func (p *MetricsHandler) Type() interface{} {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (p *MetricsHandler) Start() error {
|
func (p *MetricsHandler) Start() error {
|
||||||
|
handler := p.httpHandler()
|
||||||
|
|
||||||
// direct listen a port if listen is set
|
// direct listen a port if listen is set
|
||||||
if p.listen != "" {
|
if p.listen != "" {
|
||||||
TCPlistener, err := net.Listen("tcp", p.listen)
|
TCPlistener, err := xnet.Listen("tcp", p.listen)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
p.tcpListener = TCPlistener
|
p.tcpListener = TCPlistener
|
||||||
errors.LogInfo(context.Background(), "Metrics server listening on ", p.listen)
|
errors.LogInfo(context.Background(), "Metrics server listening on ", p.listen)
|
||||||
|
|
||||||
go func() {
|
go p.serve(TCPlistener, handler)
|
||||||
if err := http.Serve(TCPlistener, http.DefaultServeMux); err != nil {
|
|
||||||
errors.LogErrorInner(context.Background(), err, "failed to start metrics server")
|
|
||||||
}
|
}
|
||||||
}()
|
|
||||||
|
if p.tag == "" {
|
||||||
|
if p.tcpListener == nil {
|
||||||
|
return errors.New("metrics must have a tag or listen address")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
listener := &OutboundListener{
|
listener := &OutboundListener{
|
||||||
buffer: make(chan net.Conn, 4),
|
buffer: make(chan xnet.Conn, 4),
|
||||||
done: done.New(),
|
done: done.New(),
|
||||||
}
|
}
|
||||||
|
p.listener = listener
|
||||||
|
|
||||||
go func() {
|
go p.serve(listener, handler)
|
||||||
if err := http.Serve(listener, http.DefaultServeMux); err != nil {
|
|
||||||
errors.LogErrorInner(context.Background(), err, "failed to start metrics server")
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil {
|
if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil {
|
||||||
errors.LogInfo(context.Background(), "failed to remove existing handler")
|
errors.LogInfo(context.Background(), "failed to remove existing handler")
|
||||||
}
|
}
|
||||||
|
|
||||||
return p.ohm.AddHandler(context.Background(), &Outbound{
|
if err := p.ohm.AddHandler(context.Background(), &Outbound{
|
||||||
tag: p.tag,
|
tag: p.tag,
|
||||||
listener: listener,
|
listener: listener,
|
||||||
})
|
}); err != nil {
|
||||||
|
if closeErr := p.Close(); closeErr != nil {
|
||||||
|
errors.LogErrorInner(context.Background(), closeErr, "failed to close metrics server after start failure")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *MetricsHandler) Close() error {
|
func (p *MetricsHandler) Close() error {
|
||||||
|
var errs []error
|
||||||
|
if p.tcpListener != nil {
|
||||||
|
errs = append(errs, p.tcpListener.Close())
|
||||||
|
p.tcpListener = nil
|
||||||
|
}
|
||||||
|
if p.listener != nil {
|
||||||
|
errs = append(errs, p.listener.Close())
|
||||||
|
p.listener = nil
|
||||||
|
}
|
||||||
|
if p.ohm != nil && p.tag != "" {
|
||||||
|
if err := p.ohm.RemoveHandler(context.Background(), p.tag); err != nil {
|
||||||
|
errors.LogInfo(context.Background(), "failed to remove metrics handler")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.Combine(errs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *MetricsHandler) serve(listener xnet.Listener, handler http.Handler) {
|
||||||
|
if err := http.Serve(listener, handler); err != nil && !isClosedListenerError(err) {
|
||||||
|
errors.LogErrorInner(context.Background(), err, "failed to start metrics server")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isClosedListenerError(err error) bool {
|
||||||
|
if err == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if stderrors.Is(err, stdnet.ErrClosed) || stderrors.Is(err, http.ErrServerClosed) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
errText := err.Error()
|
||||||
|
return strings.Contains(errText, "listen closed") ||
|
||||||
|
strings.Contains(errText, "use of closed network connection")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *MetricsHandler) httpHandler() http.Handler {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/debug/vars", p.handleDebugVars)
|
||||||
|
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
||||||
|
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
||||||
|
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
||||||
|
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
|
||||||
|
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
|
||||||
|
return mux
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *MetricsHandler) handleDebugVars(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
vars := map[string]json.RawMessage{}
|
||||||
|
expvar.Do(func(kv expvar.KeyValue) {
|
||||||
|
value := json.RawMessage(kv.Value.String())
|
||||||
|
if !json.Valid(value) {
|
||||||
|
value = json.RawMessage("null")
|
||||||
|
}
|
||||||
|
vars[kv.Key] = value
|
||||||
|
})
|
||||||
|
vars["stats"] = marshalJSON(p.stats())
|
||||||
|
vars["observatory"] = marshalJSON(p.observatoryStatus())
|
||||||
|
|
||||||
|
payload, err := json.Marshal(vars)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Write(payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
func marshalJSON(value interface{}) json.RawMessage {
|
||||||
|
data, err := json.Marshal(value)
|
||||||
|
if err != nil {
|
||||||
|
return json.RawMessage("null")
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *MetricsHandler) stats() map[string]map[string]map[string]int64 {
|
||||||
|
resp := map[string]map[string]map[string]int64{
|
||||||
|
"inbound": {},
|
||||||
|
"outbound": {},
|
||||||
|
"user": {},
|
||||||
|
}
|
||||||
|
p.statsManager.VisitCounters(func(name string, counter feature_stats.Counter) bool {
|
||||||
|
nameSplit := strings.Split(name, ">>>")
|
||||||
|
if len(nameSplit) < 4 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
typeName, tagOrUser, direction := nameSplit[0], nameSplit[1], nameSplit[3]
|
||||||
|
items, found := resp[typeName]
|
||||||
|
if !found {
|
||||||
|
items = map[string]map[string]int64{}
|
||||||
|
resp[typeName] = items
|
||||||
|
}
|
||||||
|
if item, found := items[tagOrUser]; found {
|
||||||
|
item[direction] = counter.Value()
|
||||||
|
} else {
|
||||||
|
items[tagOrUser] = map[string]int64{
|
||||||
|
direction: counter.Value(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *MetricsHandler) observatoryStatus() interface{} {
|
||||||
|
feature := core.MustFromContext(p.ctx).GetFeature(extension.ObservatoryType())
|
||||||
|
if feature == nil {
|
||||||
return nil
|
return nil
|
||||||
|
}
|
||||||
|
observatoryFeature := feature.(extension.Observatory)
|
||||||
|
resp := map[string]*observatory.OutboundStatus{}
|
||||||
|
if o, err := observatoryFeature.GetObservation(context.Background()); err != nil {
|
||||||
|
return err
|
||||||
|
} else {
|
||||||
|
for _, x := range o.(*observatory.ObservationResult).GetStatus() {
|
||||||
|
resp[x.OutboundTag] = x
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return resp
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
@@ -0,0 +1,161 @@
|
|||||||
|
package metrics
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
stdnet "net"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/app/dispatcher"
|
||||||
|
"github.com/xtls/xray-core/app/proxyman"
|
||||||
|
_ "github.com/xtls/xray-core/app/proxyman/inbound"
|
||||||
|
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||||
|
appstats "github.com/xtls/xray-core/app/stats"
|
||||||
|
"github.com/xtls/xray-core/common/serial"
|
||||||
|
"github.com/xtls/xray-core/core"
|
||||||
|
feature_outbound "github.com/xtls/xray-core/features/outbound"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMetricsCanRestartInSameProcess(t *testing.T) {
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
server := startMetricsTestServer(t)
|
||||||
|
readMetricsVars(t, server)
|
||||||
|
readMetricsPprof(t, server)
|
||||||
|
if err := server.Close(); err != nil {
|
||||||
|
t.Fatalf("failed to close metrics server: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMetricsCanRunMultipleInstancesInSameProcess(t *testing.T) {
|
||||||
|
server1 := startMetricsTestServer(t)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = server1.Close()
|
||||||
|
})
|
||||||
|
server2 := startMetricsTestServer(t)
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = server2.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
readMetricsVars(t, server1)
|
||||||
|
readMetricsVars(t, server2)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMetricsListenOnlyWithoutTagDoesNotRegisterOutbound(t *testing.T) {
|
||||||
|
listen := pickMetricsListenAddress(t)
|
||||||
|
server := startMetricsTestServerWithMetricsConfig(t, &Config{
|
||||||
|
Listen: listen,
|
||||||
|
})
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = server.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
response, err := http.Get("http://" + listen + "/debug/vars")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to read listen-only metrics: %v", err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("unexpected listen-only metrics status: %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
outboundManager := server.GetFeature(feature_outbound.ManagerType()).(feature_outbound.Manager)
|
||||||
|
if handlers := outboundManager.ListHandlers(context.Background()); len(handlers) != 0 {
|
||||||
|
t.Fatalf("listen-only metrics registered outbound handlers: got %d, want 0", len(handlers))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func startMetricsTestServer(t *testing.T) *core.Instance {
|
||||||
|
return startMetricsTestServerWithMetricsConfig(t, &Config{
|
||||||
|
Tag: "metrics_out",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func startMetricsTestServerWithMetricsConfig(t *testing.T, metricsConfig *Config) *core.Instance {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
server, err := core.New(metricsTestConfig(metricsConfig))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to create metrics server: %v", err)
|
||||||
|
}
|
||||||
|
if err := server.Start(); err != nil {
|
||||||
|
_ = server.Close()
|
||||||
|
t.Fatalf("failed to start metrics server: %v", err)
|
||||||
|
}
|
||||||
|
return server
|
||||||
|
}
|
||||||
|
|
||||||
|
func metricsTestConfig(metricsConfig *Config) *core.Config {
|
||||||
|
return &core.Config{
|
||||||
|
App: []*serial.TypedMessage{
|
||||||
|
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||||
|
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||||
|
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||||
|
serial.ToTypedMessage(&appstats.Config{}),
|
||||||
|
serial.ToTypedMessage(metricsConfig),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func pickMetricsListenAddress(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
listener, err := stdnet.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("failed to pick metrics listen address: %v", err)
|
||||||
|
}
|
||||||
|
defer listener.Close()
|
||||||
|
return listener.Addr().String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func readMetricsVars(t *testing.T, server *core.Instance) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
metricsHandler(t, server).httpHandler().ServeHTTP(
|
||||||
|
recorder,
|
||||||
|
httptest.NewRequest(http.MethodGet, "/debug/vars", nil),
|
||||||
|
)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("unexpected metrics vars status: %d", recorder.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
var payload map[string]interface{}
|
||||||
|
if err := json.NewDecoder(recorder.Body).Decode(&payload); err != nil {
|
||||||
|
t.Fatalf("failed to decode metrics vars: %v", err)
|
||||||
|
}
|
||||||
|
if _, found := payload["stats"]; !found {
|
||||||
|
t.Fatal("metrics vars missing stats")
|
||||||
|
}
|
||||||
|
if _, found := payload["observatory"]; !found {
|
||||||
|
t.Fatal("metrics vars missing observatory")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readMetricsPprof(t *testing.T, server *core.Instance) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
metricsHandler(t, server).httpHandler().ServeHTTP(
|
||||||
|
recorder,
|
||||||
|
httptest.NewRequest(http.MethodGet, "/debug/pprof/goroutine?debug=1", nil),
|
||||||
|
)
|
||||||
|
|
||||||
|
if recorder.Code != http.StatusOK {
|
||||||
|
t.Fatalf("unexpected metrics pprof status: %d", recorder.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func metricsHandler(t *testing.T, server *core.Instance) *MetricsHandler {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
feature := server.GetFeature((*MetricsHandler)(nil))
|
||||||
|
handler, ok := feature.(*MetricsHandler)
|
||||||
|
if !ok || handler == nil {
|
||||||
|
t.Fatal("metrics handler not registered")
|
||||||
|
}
|
||||||
|
return handler
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@ package burst
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/app/observatory"
|
"github.com/xtls/xray-core/app/observatory"
|
||||||
@@ -72,7 +71,6 @@ func (o *Observer) Start() error {
|
|||||||
o.hp.StartScheduler(func() ([]string, error) {
|
o.hp.StartScheduler(func() ([]string, error) {
|
||||||
hs, ok := o.ohm.(outbound.HandlerSelector)
|
hs, ok := o.ohm.(outbound.HandlerSelector)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|
||||||
return nil, errors.New("outbound.Manager is not a HandlerSelector")
|
return nil, errors.New("outbound.Manager is not a HandlerSelector")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/dice"
|
"github.com/xtls/xray-core/common/dice"
|
||||||
@@ -25,10 +26,11 @@ type HealthPingSettings struct {
|
|||||||
// HealthPing is the health checker for balancers
|
// HealthPing is the health checker for balancers
|
||||||
type HealthPing struct {
|
type HealthPing struct {
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
|
cancelCtx context.CancelFunc
|
||||||
|
cancelPending atomic.Pointer[context.CancelFunc]
|
||||||
dispatcher routing.Dispatcher
|
dispatcher routing.Dispatcher
|
||||||
access sync.Mutex
|
access sync.Mutex
|
||||||
ticker *time.Ticker
|
ticker *time.Ticker
|
||||||
tickerClose chan struct{}
|
|
||||||
|
|
||||||
Settings *HealthPingSettings
|
Settings *HealthPingSettings
|
||||||
Results map[string]*HealthPingRTTS
|
Results map[string]*HealthPingRTTS
|
||||||
@@ -62,10 +64,10 @@ func NewHealthPing(ctx context.Context, dispatcher routing.Dispatcher, config *H
|
|||||||
settings.Destination = "https://connectivitycheck.gstatic.com/generate_204"
|
settings.Destination = "https://connectivitycheck.gstatic.com/generate_204"
|
||||||
}
|
}
|
||||||
if settings.Interval == 0 {
|
if settings.Interval == 0 {
|
||||||
settings.Interval = time.Duration(1) * time.Minute
|
settings.Interval = 1 * time.Minute
|
||||||
} else if settings.Interval < 10 {
|
} else if settings.Interval < 10*time.Second {
|
||||||
errors.LogWarning(ctx, "health check interval is too small, 10s is applied")
|
errors.LogWarning(ctx, "health check interval is too small, 10s is applied")
|
||||||
settings.Interval = time.Duration(10) * time.Second
|
settings.Interval = 10 * time.Second
|
||||||
}
|
}
|
||||||
if settings.SamplingCount <= 0 {
|
if settings.SamplingCount <= 0 {
|
||||||
settings.SamplingCount = 10
|
settings.SamplingCount = 10
|
||||||
@@ -73,10 +75,12 @@ func NewHealthPing(ctx context.Context, dispatcher routing.Dispatcher, config *H
|
|||||||
if settings.Timeout <= 0 {
|
if settings.Timeout <= 0 {
|
||||||
// results are saved after all health pings finish,
|
// results are saved after all health pings finish,
|
||||||
// a larger timeout could possibly makes checks run longer
|
// a larger timeout could possibly makes checks run longer
|
||||||
settings.Timeout = time.Duration(5) * time.Second
|
settings.Timeout = 5 * time.Second
|
||||||
}
|
}
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
return &HealthPing{
|
return &HealthPing{
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
|
cancelCtx: cancel,
|
||||||
dispatcher: dispatcher,
|
dispatcher: dispatcher,
|
||||||
Settings: settings,
|
Settings: settings,
|
||||||
Results: nil,
|
Results: nil,
|
||||||
@@ -90,9 +94,9 @@ func (h *HealthPing) StartScheduler(selector func() ([]string, error)) {
|
|||||||
}
|
}
|
||||||
interval := h.Settings.Interval * time.Duration(h.Settings.SamplingCount)
|
interval := h.Settings.Interval * time.Duration(h.Settings.SamplingCount)
|
||||||
ticker := time.NewTicker(interval)
|
ticker := time.NewTicker(interval)
|
||||||
tickerClose := make(chan struct{})
|
|
||||||
h.ticker = ticker
|
h.ticker = ticker
|
||||||
h.tickerClose = tickerClose
|
|
||||||
|
// init run to get a fast check result
|
||||||
go func() {
|
go func() {
|
||||||
tags, err := selector()
|
tags, err := selector()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -110,13 +114,20 @@ func (h *HealthPing) StartScheduler(selector func() ([]string, error)) {
|
|||||||
errors.LogWarning(h.ctx, "error select outbounds for scheduled health check: ", err)
|
errors.LogWarning(h.ctx, "error select outbounds for scheduled health check: ", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
h.doCheck(tags, interval, h.Settings.SamplingCount)
|
subCtx, cancel := context.WithCancel(h.ctx)
|
||||||
|
old := h.cancelPending.Swap(&cancel)
|
||||||
|
if old != nil {
|
||||||
|
errors.LogDebug(h.ctx, "scheduled health check not finished before next round, canceling previous one")
|
||||||
|
(*old)()
|
||||||
|
}
|
||||||
|
h.doCheck(subCtx, tags, interval, h.Settings.SamplingCount)
|
||||||
|
h.cancelPending.CompareAndSwap(&cancel, nil)
|
||||||
h.Cleanup(tags)
|
h.Cleanup(tags)
|
||||||
}()
|
}()
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
continue
|
continue
|
||||||
case <-tickerClose:
|
case <-h.ctx.Done():
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -130,8 +141,7 @@ func (h *HealthPing) StopScheduler() {
|
|||||||
}
|
}
|
||||||
h.ticker.Stop()
|
h.ticker.Stop()
|
||||||
h.ticker = nil
|
h.ticker = nil
|
||||||
close(h.tickerClose)
|
h.cancelCtx()
|
||||||
h.tickerClose = nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check implements the HealthChecker
|
// Check implements the HealthChecker
|
||||||
@@ -140,7 +150,7 @@ func (h *HealthPing) Check(tags []string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
errors.LogInfo(h.ctx, "perform one-time health check for tags ", tags)
|
errors.LogInfo(h.ctx, "perform one-time health check for tags ", tags)
|
||||||
h.doCheck(tags, 0, 1)
|
h.doCheck(h.ctx, tags, 0, 1)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,13 +161,14 @@ type rtt struct {
|
|||||||
|
|
||||||
// doCheck performs the 'rounds' amount checks in given 'duration'. You should make
|
// doCheck performs the 'rounds' amount checks in given 'duration'. You should make
|
||||||
// sure all tags are valid for current balancer
|
// sure all tags are valid for current balancer
|
||||||
func (h *HealthPing) doCheck(tags []string, duration time.Duration, rounds int) {
|
// cancel ctx will stop all pending checks
|
||||||
|
func (h *HealthPing) doCheck(ctx context.Context, tags []string, duration time.Duration, rounds int) {
|
||||||
count := len(tags) * rounds
|
count := len(tags) * rounds
|
||||||
if count == 0 {
|
if count == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ch := make(chan *rtt, count)
|
ch := make(chan *rtt, count)
|
||||||
|
timers := make([]*time.Timer, 0, count)
|
||||||
for _, tag := range tags {
|
for _, tag := range tags {
|
||||||
handler := tag
|
handler := tag
|
||||||
client := newPingClient(
|
client := newPingClient(
|
||||||
@@ -172,7 +183,7 @@ func (h *HealthPing) doCheck(tags []string, duration time.Duration, rounds int)
|
|||||||
if duration > 0 {
|
if duration > 0 {
|
||||||
delay = time.Duration(dice.RollInt63n(int64(duration)))
|
delay = time.Duration(dice.RollInt63n(int64(duration)))
|
||||||
}
|
}
|
||||||
time.AfterFunc(delay, func() {
|
timers = append(timers, time.AfterFunc(delay, func() {
|
||||||
errors.LogDebug(h.ctx, "checking ", handler)
|
errors.LogDebug(h.ctx, "checking ", handler)
|
||||||
delay, err := client.MeasureDelay(h.Settings.HttpMethod)
|
delay, err := client.MeasureDelay(h.Settings.HttpMethod)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -200,15 +211,22 @@ func (h *HealthPing) doCheck(tags []string, duration time.Duration, rounds int)
|
|||||||
handler: handler,
|
handler: handler,
|
||||||
value: rttFailed,
|
value: rttFailed,
|
||||||
}
|
}
|
||||||
})
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for i := 0; i < count; i++ {
|
for i := 0; i < count; i++ {
|
||||||
rtt := <-ch
|
select {
|
||||||
|
case rtt := <-ch:
|
||||||
if rtt.value > 0 {
|
if rtt.value > 0 {
|
||||||
// should not put results when network is down
|
// should not put results when network is down
|
||||||
h.PutResult(rtt.handler, rtt.value)
|
h.PutResult(rtt.handler, rtt.value)
|
||||||
}
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
for _, timer := range timers {
|
||||||
|
timer.Stop()
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ func (h *HealthPingRTTS) Put(d time.Duration) {
|
|||||||
if h.rtts == nil {
|
if h.rtts == nil {
|
||||||
h.rtts = make([]*pingRTT, h.cap)
|
h.rtts = make([]*pingRTT, h.cap)
|
||||||
for i := 0; i < h.cap; i++ {
|
for i := 0; i < h.cap; i++ {
|
||||||
h.rtts[i] = &pingRTT{}
|
h.rtts[i] = &pingRTT{value: rttUntested}
|
||||||
}
|
}
|
||||||
h.idx = -1
|
h.idx = -1
|
||||||
}
|
}
|
||||||
@@ -88,7 +88,7 @@ func (h *HealthPingRTTS) getStatistics() *HealthPingStats {
|
|||||||
validRTTs := make([]time.Duration, 0)
|
validRTTs := make([]time.Duration, 0)
|
||||||
for _, rtt := range h.rtts {
|
for _, rtt := range h.rtts {
|
||||||
switch {
|
switch {
|
||||||
case rtt.value == 0 || time.Since(rtt.time) > h.validity:
|
case rtt.value == rttUntested || time.Since(rtt.time) > h.validity:
|
||||||
continue
|
continue
|
||||||
case rtt.value == rttFailed:
|
case rtt.value == rttFailed:
|
||||||
stats.Fail++
|
stats.Fail++
|
||||||
|
|||||||
@@ -78,6 +78,12 @@ func (o *Observer) background() {
|
|||||||
sleepTime = time.Duration(o.config.ProbeInterval)
|
sleepTime = time.Duration(o.config.ProbeInterval)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(outbounds) == 0 {
|
||||||
|
errors.LogWarning(o.ctx, "no outbound matches subjectSelector ", o.config.SubjectSelector)
|
||||||
|
time.Sleep(sleepTime)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if !o.config.EnableConcurrency {
|
if !o.config.EnableConcurrency {
|
||||||
sort.Strings(outbounds)
|
sort.Strings(outbounds)
|
||||||
for _, v := range outbounds {
|
for _, v := range outbounds {
|
||||||
@@ -186,7 +192,7 @@ func (o *Observer) probe(outbound string) ProbeResult {
|
|||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var errorMessage = "the outbound " + outbound + " is dead: GET request failed:" + err.Error() + "with outbound handler report underlying connection failed"
|
errorMessage := "the outbound " + outbound + " is dead: GET request failed:" + err.Error() + "with outbound handler report underlying connection failed"
|
||||||
errors.LogInfoInner(o.ctx, errorCollectorForRequest.UnderlyingError(), errorMessage)
|
errors.LogInfoInner(o.ctx, errorCollectorForRequest.UnderlyingError(), errorMessage)
|
||||||
return ProbeResult{Alive: false, LastErrorReason: errorMessage}
|
return ProbeResult{Alive: false, LastErrorReason: errorMessage}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -138,7 +138,7 @@ func (s *handlerServer) GetInboundUsers(ctx context.Context, request *GetInbound
|
|||||||
if len(request.Email) > 0 {
|
if len(request.Email) > 0 {
|
||||||
return &GetInboundUserResponse{Users: []*protocol.User{protocol.ToProtoUser(um.GetUser(ctx, request.Email))}}, nil
|
return &GetInboundUserResponse{Users: []*protocol.User{protocol.ToProtoUser(um.GetUser(ctx, request.Email))}}, nil
|
||||||
}
|
}
|
||||||
var result = make([]*protocol.User, 0, 100)
|
result := make([]*protocol.User, 0, 100)
|
||||||
users := um.GetUsers(ctx)
|
users := um.GetUsers(ctx)
|
||||||
for _, u := range users {
|
for _, u := range users {
|
||||||
result = append(result, protocol.ToProtoUser(u))
|
result = append(result, protocol.ToProtoUser(u))
|
||||||
|
|||||||
+11
-22
@@ -330,7 +330,6 @@ type SenderConfig struct {
|
|||||||
// Send traffic through the given IP. Only IP is allowed.
|
// Send traffic through the given IP. Only IP is allowed.
|
||||||
Via *net.IPOrDomain `protobuf:"bytes,1,opt,name=via,proto3" json:"via,omitempty"`
|
Via *net.IPOrDomain `protobuf:"bytes,1,opt,name=via,proto3" json:"via,omitempty"`
|
||||||
StreamSettings *internet.StreamConfig `protobuf:"bytes,2,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"`
|
StreamSettings *internet.StreamConfig `protobuf:"bytes,2,opt,name=stream_settings,json=streamSettings,proto3" json:"stream_settings,omitempty"`
|
||||||
ProxySettings *internet.ProxyConfig `protobuf:"bytes,3,opt,name=proxy_settings,json=proxySettings,proto3" json:"proxy_settings,omitempty"`
|
|
||||||
MultiplexSettings *MultiplexingConfig `protobuf:"bytes,4,opt,name=multiplex_settings,json=multiplexSettings,proto3" json:"multiplex_settings,omitempty"`
|
MultiplexSettings *MultiplexingConfig `protobuf:"bytes,4,opt,name=multiplex_settings,json=multiplexSettings,proto3" json:"multiplex_settings,omitempty"`
|
||||||
ViaCidr string `protobuf:"bytes,5,opt,name=via_cidr,json=viaCidr,proto3" json:"via_cidr,omitempty"`
|
ViaCidr string `protobuf:"bytes,5,opt,name=via_cidr,json=viaCidr,proto3" json:"via_cidr,omitempty"`
|
||||||
TargetStrategy internet.DomainStrategy `protobuf:"varint,6,opt,name=target_strategy,json=targetStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"target_strategy,omitempty"`
|
TargetStrategy internet.DomainStrategy `protobuf:"varint,6,opt,name=target_strategy,json=targetStrategy,proto3,enum=xray.transport.internet.DomainStrategy" json:"target_strategy,omitempty"`
|
||||||
@@ -382,13 +381,6 @@ func (x *SenderConfig) GetStreamSettings() *internet.StreamConfig {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (x *SenderConfig) GetProxySettings() *internet.ProxyConfig {
|
|
||||||
if x != nil {
|
|
||||||
return x.ProxySettings
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (x *SenderConfig) GetMultiplexSettings() *MultiplexingConfig {
|
func (x *SenderConfig) GetMultiplexSettings() *MultiplexingConfig {
|
||||||
if x != nil {
|
if x != nil {
|
||||||
return x.MultiplexSettings
|
return x.MultiplexSettings
|
||||||
@@ -506,14 +498,13 @@ const file_app_proxyman_config_proto_rawDesc = "" +
|
|||||||
"\x03tag\x18\x01 \x01(\tR\x03tag\x12M\n" +
|
"\x03tag\x18\x01 \x01(\tR\x03tag\x12M\n" +
|
||||||
"\x11receiver_settings\x18\x02 \x01(\v2 .xray.common.serial.TypedMessageR\x10receiverSettings\x12G\n" +
|
"\x11receiver_settings\x18\x02 \x01(\v2 .xray.common.serial.TypedMessageR\x10receiverSettings\x12G\n" +
|
||||||
"\x0eproxy_settings\x18\x03 \x01(\v2 .xray.common.serial.TypedMessageR\rproxySettings\"\x10\n" +
|
"\x0eproxy_settings\x18\x03 \x01(\v2 .xray.common.serial.TypedMessageR\rproxySettings\"\x10\n" +
|
||||||
"\x0eOutboundConfig\"\x9d\x03\n" +
|
"\x0eOutboundConfig\"\xd6\x02\n" +
|
||||||
"\fSenderConfig\x12-\n" +
|
"\fSenderConfig\x12-\n" +
|
||||||
"\x03via\x18\x01 \x01(\v2\x1b.xray.common.net.IPOrDomainR\x03via\x12N\n" +
|
"\x03via\x18\x01 \x01(\v2\x1b.xray.common.net.IPOrDomainR\x03via\x12N\n" +
|
||||||
"\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12K\n" +
|
"\x0fstream_settings\x18\x02 \x01(\v2%.xray.transport.internet.StreamConfigR\x0estreamSettings\x12T\n" +
|
||||||
"\x0eproxy_settings\x18\x03 \x01(\v2$.xray.transport.internet.ProxyConfigR\rproxySettings\x12T\n" +
|
|
||||||
"\x12multiplex_settings\x18\x04 \x01(\v2%.xray.app.proxyman.MultiplexingConfigR\x11multiplexSettings\x12\x19\n" +
|
"\x12multiplex_settings\x18\x04 \x01(\v2%.xray.app.proxyman.MultiplexingConfigR\x11multiplexSettings\x12\x19\n" +
|
||||||
"\bvia_cidr\x18\x05 \x01(\tR\aviaCidr\x12P\n" +
|
"\bvia_cidr\x18\x05 \x01(\tR\aviaCidr\x12P\n" +
|
||||||
"\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategy\"\xa4\x01\n" +
|
"\x0ftarget_strategy\x18\x06 \x01(\x0e2'.xray.transport.internet.DomainStrategyR\x0etargetStrategyJ\x04\b\x03\x10\x04\"\xa4\x01\n" +
|
||||||
"\x12MultiplexingConfig\x12\x18\n" +
|
"\x12MultiplexingConfig\x12\x18\n" +
|
||||||
"\aenabled\x18\x01 \x01(\bR\aenabled\x12 \n" +
|
"\aenabled\x18\x01 \x01(\bR\aenabled\x12 \n" +
|
||||||
"\vconcurrency\x18\x02 \x01(\x05R\vconcurrency\x12(\n" +
|
"\vconcurrency\x18\x02 \x01(\x05R\vconcurrency\x12(\n" +
|
||||||
@@ -548,8 +539,7 @@ var file_app_proxyman_config_proto_goTypes = []any{
|
|||||||
(*net.IPOrDomain)(nil), // 10: xray.common.net.IPOrDomain
|
(*net.IPOrDomain)(nil), // 10: xray.common.net.IPOrDomain
|
||||||
(*internet.StreamConfig)(nil), // 11: xray.transport.internet.StreamConfig
|
(*internet.StreamConfig)(nil), // 11: xray.transport.internet.StreamConfig
|
||||||
(*serial.TypedMessage)(nil), // 12: xray.common.serial.TypedMessage
|
(*serial.TypedMessage)(nil), // 12: xray.common.serial.TypedMessage
|
||||||
(*internet.ProxyConfig)(nil), // 13: xray.transport.internet.ProxyConfig
|
(internet.DomainStrategy)(0), // 13: xray.transport.internet.DomainStrategy
|
||||||
(internet.DomainStrategy)(0), // 14: xray.transport.internet.DomainStrategy
|
|
||||||
}
|
}
|
||||||
var file_app_proxyman_config_proto_depIdxs = []int32{
|
var file_app_proxyman_config_proto_depIdxs = []int32{
|
||||||
7, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule
|
7, // 0: xray.app.proxyman.SniffingConfig.domains_excluded:type_name -> xray.common.geodata.DomainRule
|
||||||
@@ -562,14 +552,13 @@ var file_app_proxyman_config_proto_depIdxs = []int32{
|
|||||||
12, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage
|
12, // 7: xray.app.proxyman.InboundHandlerConfig.proxy_settings:type_name -> xray.common.serial.TypedMessage
|
||||||
10, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain
|
10, // 8: xray.app.proxyman.SenderConfig.via:type_name -> xray.common.net.IPOrDomain
|
||||||
11, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
11, // 9: xray.app.proxyman.SenderConfig.stream_settings:type_name -> xray.transport.internet.StreamConfig
|
||||||
13, // 10: xray.app.proxyman.SenderConfig.proxy_settings:type_name -> xray.transport.internet.ProxyConfig
|
6, // 10: xray.app.proxyman.SenderConfig.multiplex_settings:type_name -> xray.app.proxyman.MultiplexingConfig
|
||||||
6, // 11: xray.app.proxyman.SenderConfig.multiplex_settings:type_name -> xray.app.proxyman.MultiplexingConfig
|
13, // 11: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
|
||||||
14, // 12: xray.app.proxyman.SenderConfig.target_strategy:type_name -> xray.transport.internet.DomainStrategy
|
12, // [12:12] is the sub-list for method output_type
|
||||||
13, // [13:13] is the sub-list for method output_type
|
12, // [12:12] is the sub-list for method input_type
|
||||||
13, // [13:13] is the sub-list for method input_type
|
12, // [12:12] is the sub-list for extension type_name
|
||||||
13, // [13:13] is the sub-list for extension type_name
|
12, // [12:12] is the sub-list for extension extendee
|
||||||
13, // [13:13] is the sub-list for extension extendee
|
0, // [0:12] is the sub-list for field type_name
|
||||||
0, // [0:13] is the sub-list for field type_name
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() { file_app_proxyman_config_proto_init() }
|
func init() { file_app_proxyman_config_proto_init() }
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ message SenderConfig {
|
|||||||
// Send traffic through the given IP. Only IP is allowed.
|
// Send traffic through the given IP. Only IP is allowed.
|
||||||
xray.common.net.IPOrDomain via = 1;
|
xray.common.net.IPOrDomain via = 1;
|
||||||
xray.transport.internet.StreamConfig stream_settings = 2;
|
xray.transport.internet.StreamConfig stream_settings = 2;
|
||||||
xray.transport.internet.ProxyConfig proxy_settings = 3;
|
reserved 3;
|
||||||
MultiplexingConfig multiplex_settings = 4;
|
MultiplexingConfig multiplex_settings = 4;
|
||||||
string via_cidr = 5;
|
string via_cidr = 5;
|
||||||
xray.transport.internet.DomainStrategy target_strategy = 6;
|
xray.transport.internet.DomainStrategy target_strategy = 6;
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter)
|
|||||||
if len(tag) > 0 && policy.ForSystem().Stats.InboundUplink {
|
if len(tag) > 0 && policy.ForSystem().Stats.InboundUplink {
|
||||||
statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
|
statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
|
||||||
name := "inbound>>>" + tag + ">>>traffic>>>uplink"
|
name := "inbound>>>" + tag + ">>>traffic>>>uplink"
|
||||||
c, _ := stats.GetOrRegisterCounter(statsManager, name)
|
c, _ := statsManager.GetOrRegisterCounter(name)
|
||||||
if c != nil {
|
if c != nil {
|
||||||
uplinkCounter = c
|
uplinkCounter = c
|
||||||
}
|
}
|
||||||
@@ -34,7 +34,7 @@ func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter)
|
|||||||
if len(tag) > 0 && policy.ForSystem().Stats.InboundDownlink {
|
if len(tag) > 0 && policy.ForSystem().Stats.InboundDownlink {
|
||||||
statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
|
statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
|
||||||
name := "inbound>>>" + tag + ">>>traffic>>>downlink"
|
name := "inbound>>>" + tag + ">>>traffic>>>downlink"
|
||||||
c, _ := stats.GetOrRegisterCounter(statsManager, name)
|
c, _ := statsManager.GetOrRegisterCounter(name)
|
||||||
if c != nil {
|
if c != nil {
|
||||||
downlinkCounter = c
|
downlinkCounter = c
|
||||||
}
|
}
|
||||||
@@ -57,16 +57,23 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
src := net.TCPDestination(net.AnyIP, 0)
|
||||||
// Set tag and sniffing config in context before creating proxy
|
if receiverConfig.Listen != nil {
|
||||||
// This allows proxies like TUN to access these settings
|
src.Address = receiverConfig.Listen.AsAddress()
|
||||||
ctx = session.ContextWithInbound(ctx, &session.Inbound{Tag: tag})
|
|
||||||
if receiverConfig.SniffingSettings != nil {
|
|
||||||
ctx = session.ContextWithContent(ctx, &session.Content{
|
|
||||||
SniffingRequest: sniffingRequest,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
rawProxy, err := common.CreateObject(ctx, proxyConfig)
|
if receiverConfig.PortList != nil && len(receiverConfig.PortList.Range) > 0 {
|
||||||
|
src.Port = net.Port(receiverConfig.PortList.Range[0].From)
|
||||||
|
}
|
||||||
|
mss, err := internet.ToMemoryStreamConfig(receiverConfig.StreamSettings)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("failed to parse stream config").Base(err).AtWarning()
|
||||||
|
}
|
||||||
|
|
||||||
|
newCtx := session.ContextWithInbound(ctx, &session.Inbound{Tag: tag, Source: src})
|
||||||
|
newCtx = session.ContextWithContent(newCtx, &session.Content{SniffingRequest: sniffingRequest})
|
||||||
|
newCtx = session.ContextWithStreamSettings(newCtx, mss)
|
||||||
|
|
||||||
|
rawProxy, err := common.CreateObject(newCtx, proxyConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -92,11 +99,6 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
|||||||
address = net.AnyIP
|
address = net.AnyIP
|
||||||
}
|
}
|
||||||
|
|
||||||
mss, err := internet.ToMemoryStreamConfig(receiverConfig.StreamSettings)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("failed to parse stream config").Base(err).AtWarning()
|
|
||||||
}
|
|
||||||
|
|
||||||
if receiverConfig.ReceiveOriginalDestination {
|
if receiverConfig.ReceiveOriginalDestination {
|
||||||
if mss.SocketSettings == nil {
|
if mss.SocketSettings == nil {
|
||||||
mss.SocketSettings = &internet.SocketConfig{}
|
mss.SocketSettings = &internet.SocketConfig{}
|
||||||
@@ -170,6 +172,12 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
|
|||||||
|
|
||||||
// Start implements common.Runnable.
|
// Start implements common.Runnable.
|
||||||
func (h *AlwaysOnInboundHandler) Start() error {
|
func (h *AlwaysOnInboundHandler) Start() error {
|
||||||
|
// for inbound without worker (TUN)
|
||||||
|
if run, ok := h.proxy.(common.Runnable); ok {
|
||||||
|
if err := run.Start(); err != nil {
|
||||||
|
return errors.New("failed to start proxy").Base(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
for _, worker := range h.workers {
|
for _, worker := range h.workers {
|
||||||
if err := worker.Start(); err != nil {
|
if err := worker.Start(); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ import (
|
|||||||
"github.com/xtls/xray-core/features/routing"
|
"github.com/xtls/xray-core/features/routing"
|
||||||
"github.com/xtls/xray-core/features/stats"
|
"github.com/xtls/xray-core/features/stats"
|
||||||
"github.com/xtls/xray-core/proxy"
|
"github.com/xtls/xray-core/proxy"
|
||||||
"github.com/xtls/xray-core/proxy/hysteria/account"
|
hysteria_proxy "github.com/xtls/xray-core/proxy/hysteria"
|
||||||
hyCtx "github.com/xtls/xray-core/proxy/hysteria/ctx"
|
|
||||||
"github.com/xtls/xray-core/transport/internet"
|
"github.com/xtls/xray-core/transport/internet"
|
||||||
|
"github.com/xtls/xray-core/transport/internet/hysteria"
|
||||||
"github.com/xtls/xray-core/transport/internet/stat"
|
"github.com/xtls/xray-core/transport/internet/stat"
|
||||||
"github.com/xtls/xray-core/transport/internet/tcp"
|
"github.com/xtls/xray-core/transport/internet/tcp"
|
||||||
"github.com/xtls/xray-core/transport/internet/udp"
|
"github.com/xtls/xray-core/transport/internet/udp"
|
||||||
@@ -134,10 +134,8 @@ func (w *tcpWorker) Proxy() proxy.Inbound {
|
|||||||
func (w *tcpWorker) Start() error {
|
func (w *tcpWorker) Start() error {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
type HysteriaInboundValidator interface{ HysteriaInboundValidator() *account.Validator }
|
if v, ok := w.proxy.(*hysteria_proxy.Server); ok {
|
||||||
if v, ok := w.proxy.(HysteriaInboundValidator); ok {
|
ctx = hysteria.ContextWithValidator(ctx, v.HysteriaInboundValidator())
|
||||||
ctx = hyCtx.ContextWithRequireDatagram(ctx, true)
|
|
||||||
ctx = hyCtx.ContextWithValidator(ctx, v.HysteriaInboundValidator())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
hub, err := internet.ListenTCP(ctx, w.address, w.port, w.stream, func(conn stat.Connection) {
|
hub, err := internet.ListenTCP(ctx, w.address, w.port, w.stream, func(conn stat.Connection) {
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import (
|
|||||||
goerrors "errors"
|
goerrors "errors"
|
||||||
"io"
|
"io"
|
||||||
"math/big"
|
"math/big"
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/dice"
|
"github.com/xtls/xray-core/common/dice"
|
||||||
|
|
||||||
@@ -16,7 +15,6 @@ import (
|
|||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/mux"
|
"github.com/xtls/xray-core/common/mux"
|
||||||
"github.com/xtls/xray-core/common/net"
|
"github.com/xtls/xray-core/common/net"
|
||||||
"github.com/xtls/xray-core/common/net/cnc"
|
|
||||||
"github.com/xtls/xray-core/common/serial"
|
"github.com/xtls/xray-core/common/serial"
|
||||||
"github.com/xtls/xray-core/common/session"
|
"github.com/xtls/xray-core/common/session"
|
||||||
"github.com/xtls/xray-core/core"
|
"github.com/xtls/xray-core/core"
|
||||||
@@ -27,8 +25,6 @@ import (
|
|||||||
"github.com/xtls/xray-core/transport"
|
"github.com/xtls/xray-core/transport"
|
||||||
"github.com/xtls/xray-core/transport/internet"
|
"github.com/xtls/xray-core/transport/internet"
|
||||||
"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/pipe"
|
|
||||||
"google.golang.org/protobuf/proto"
|
"google.golang.org/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -40,7 +36,7 @@ func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter)
|
|||||||
if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink {
|
if len(tag) > 0 && policy.ForSystem().Stats.OutboundUplink {
|
||||||
statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
|
statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
|
||||||
name := "outbound>>>" + tag + ">>>traffic>>>uplink"
|
name := "outbound>>>" + tag + ">>>traffic>>>uplink"
|
||||||
c, _ := stats.GetOrRegisterCounter(statsManager, name)
|
c, _ := statsManager.GetOrRegisterCounter(name)
|
||||||
if c != nil {
|
if c != nil {
|
||||||
uplinkCounter = c
|
uplinkCounter = c
|
||||||
}
|
}
|
||||||
@@ -48,7 +44,7 @@ func getStatCounter(v *core.Instance, tag string) (stats.Counter, stats.Counter)
|
|||||||
if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink {
|
if len(tag) > 0 && policy.ForSystem().Stats.OutboundDownlink {
|
||||||
statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
|
statsManager := v.GetFeature(stats.ManagerType()).(stats.Manager)
|
||||||
name := "outbound>>>" + tag + ">>>traffic>>>downlink"
|
name := "outbound>>>" + tag + ">>>traffic>>>downlink"
|
||||||
c, _ := stats.GetOrRegisterCounter(statsManager, name)
|
c, _ := statsManager.GetOrRegisterCounter(name)
|
||||||
if c != nil {
|
if c != nil {
|
||||||
downlinkCounter = c
|
downlinkCounter = c
|
||||||
}
|
}
|
||||||
@@ -64,7 +60,6 @@ type Handler struct {
|
|||||||
streamSettings *internet.MemoryStreamConfig
|
streamSettings *internet.MemoryStreamConfig
|
||||||
proxyConfig proto.Message
|
proxyConfig proto.Message
|
||||||
proxy proxy.Outbound
|
proxy proxy.Outbound
|
||||||
outboundManager outbound.Manager
|
|
||||||
mux *mux.ClientManager
|
mux *mux.ClientManager
|
||||||
xudp *mux.ClientManager
|
xudp *mux.ClientManager
|
||||||
udp443 string
|
udp443 string
|
||||||
@@ -78,7 +73,6 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
|
|||||||
uplinkCounter, downlinkCounter := getStatCounter(v, config.Tag)
|
uplinkCounter, downlinkCounter := getStatCounter(v, config.Tag)
|
||||||
h := &Handler{
|
h := &Handler{
|
||||||
tag: config.Tag,
|
tag: config.Tag,
|
||||||
outboundManager: v.GetFeature(outbound.ManagerType()).(outbound.Manager),
|
|
||||||
uplinkCounter: uplinkCounter,
|
uplinkCounter: uplinkCounter,
|
||||||
downlinkCounter: downlinkCounter,
|
downlinkCounter: downlinkCounter,
|
||||||
}
|
}
|
||||||
@@ -109,6 +103,10 @@ func NewHandler(ctx context.Context, config *core.OutboundHandlerConfig) (outbou
|
|||||||
|
|
||||||
ctx = session.ContextWithFullHandler(ctx, h)
|
ctx = session.ContextWithFullHandler(ctx, h)
|
||||||
|
|
||||||
|
if h.streamSettings != nil {
|
||||||
|
ctx = session.ContextWithStreamSettings(ctx, h.streamSettings)
|
||||||
|
}
|
||||||
|
|
||||||
rawProxyHandler, err := common.CreateObject(ctx, proxyConfig)
|
rawProxyHandler, err := common.CreateObject(ctx, proxyConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -196,7 +194,6 @@ func (h *Handler) Dispatch(ctx context.Context, link *transport.Link) {
|
|||||||
common.Interrupt(link.Reader)
|
common.Interrupt(link.Reader)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
unchangedDomain := ob.Target.Address.Domain()
|
unchangedDomain := ob.Target.Address.Domain()
|
||||||
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
|
ob.Target.Address = net.IPAddress(ips[dice.Roll(len(ips))])
|
||||||
@@ -269,71 +266,26 @@ func (h *Handler) DestIpAddress() net.IP {
|
|||||||
|
|
||||||
// Dial implements internet.Dialer.
|
// Dial implements internet.Dialer.
|
||||||
func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
|
func (h *Handler) Dial(ctx context.Context, dest net.Destination) (stat.Connection, error) {
|
||||||
if h.senderSettings != nil {
|
if h.senderSettings != nil && h.senderSettings.Via != nil {
|
||||||
|
|
||||||
if h.senderSettings.ProxySettings.HasTag() {
|
|
||||||
|
|
||||||
tag := h.senderSettings.ProxySettings.Tag
|
|
||||||
handler := h.outboundManager.GetHandler(tag)
|
|
||||||
if handler != nil {
|
|
||||||
errors.LogDebug(ctx, "proxying to ", tag, " for dest ", dest)
|
|
||||||
outbounds := session.OutboundsFromContext(ctx)
|
|
||||||
ctx = session.ContextWithOutbounds(ctx, append(outbounds, &session.Outbound{
|
|
||||||
Target: dest,
|
|
||||||
Tag: tag,
|
|
||||||
})) // add another outbound in session ctx
|
|
||||||
opts := pipe.OptionsFromContext(ctx)
|
|
||||||
uplinkReader, uplinkWriter := pipe.New(opts...)
|
|
||||||
downlinkReader, downlinkWriter := pipe.New(opts...)
|
|
||||||
|
|
||||||
go handler.Dispatch(ctx, &transport.Link{Reader: uplinkReader, Writer: downlinkWriter})
|
|
||||||
conn := cnc.NewConnection(cnc.ConnectionInputMulti(uplinkWriter), cnc.ConnectionOutputMulti(downlinkReader))
|
|
||||||
|
|
||||||
if config := tls.ConfigFromStreamSettings(h.streamSettings); config != nil {
|
|
||||||
tlsConfig := config.GetTLSConfig(tls.WithDestination(dest))
|
|
||||||
conn = tls.Client(conn, tlsConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
return h.getStatCouterConnection(conn), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
errors.LogError(ctx, "failed to get outbound handler with tag: ", tag)
|
|
||||||
return nil, errors.New("failed to get outbound handler with tag: " + tag)
|
|
||||||
}
|
|
||||||
|
|
||||||
if h.senderSettings.Via != nil {
|
|
||||||
outbounds := session.OutboundsFromContext(ctx)
|
outbounds := session.OutboundsFromContext(ctx)
|
||||||
ob := outbounds[len(outbounds)-1]
|
ob := outbounds[len(outbounds)-1]
|
||||||
h.SetOutboundGateway(ctx, ob)
|
h.SetOutboundGateway(ctx, ob)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
if conn, err := h.getUoTConnection(ctx, dest); err != os.ErrInvalid {
|
|
||||||
return conn, err
|
|
||||||
}
|
|
||||||
|
|
||||||
conn, err := internet.Dial(ctx, dest, h.streamSettings)
|
conn, err := internet.Dial(ctx, dest, h.streamSettings)
|
||||||
conn = h.getStatCouterConnection(conn)
|
conn = h.getStatCouterConnection(conn)
|
||||||
outbounds := session.OutboundsFromContext(ctx)
|
|
||||||
if outbounds != nil {
|
|
||||||
ob := outbounds[len(outbounds)-1]
|
|
||||||
ob.Conn = conn
|
|
||||||
} else {
|
|
||||||
// for Vision's pre-connect
|
|
||||||
}
|
|
||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) SetOutboundGateway(ctx context.Context, ob *session.Outbound) {
|
func (h *Handler) SetOutboundGateway(ctx context.Context, ob *session.Outbound) {
|
||||||
if ob.Gateway == nil && h.senderSettings != nil && h.senderSettings.Via != nil && !h.senderSettings.ProxySettings.HasTag() && (h.streamSettings.SocketSettings == nil || len(h.streamSettings.SocketSettings.DialerProxy) == 0) {
|
if ob.Gateway == nil && h.senderSettings != nil && h.senderSettings.Via != nil &&
|
||||||
|
(h.streamSettings.SocketSettings == nil || len(h.streamSettings.SocketSettings.DialerProxy) == 0) {
|
||||||
var domain string
|
var domain string
|
||||||
addr := h.senderSettings.Via.AsAddress()
|
addr := h.senderSettings.Via.AsAddress()
|
||||||
domain = h.senderSettings.Via.GetDomain()
|
domain = h.senderSettings.Via.GetDomain()
|
||||||
switch {
|
switch {
|
||||||
case h.senderSettings.ViaCidr != "":
|
case h.senderSettings.ViaCidr != "":
|
||||||
ob.Gateway = ParseRandomIP(addr, h.senderSettings.ViaCidr)
|
ob.Gateway = ParseRandomIP(addr, h.senderSettings.ViaCidr)
|
||||||
|
|
||||||
case domain == "origin":
|
case domain == "origin":
|
||||||
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
if inbound := session.InboundFromContext(ctx); inbound != nil {
|
||||||
if inbound.Local.IsValid() && inbound.Local.Address.Family().IsIP() {
|
if inbound.Local.IsValid() && inbound.Local.Address.Family().IsIP() {
|
||||||
@@ -348,12 +300,9 @@ func (h *Handler) SetOutboundGateway(ctx context.Context, ob *session.Outbound)
|
|||||||
errors.LogDebug(ctx, "use inbound source ip as sendthrough: ", inbound.Source.Address.String())
|
errors.LogDebug(ctx, "use inbound source ip as sendthrough: ", inbound.Source.Address.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//case addr.Family().IsDomain():
|
default: // case addr.Family().IsDomain():
|
||||||
default:
|
|
||||||
ob.Gateway = addr
|
ob.Gateway = addr
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -396,7 +345,6 @@ func (h *Handler) ProxySettings() *serial.TypedMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ParseRandomIP(addr net.Address, prefix string) net.Address {
|
func ParseRandomIP(addr net.Address, prefix string) net.Address {
|
||||||
|
|
||||||
_, ipnet, _ := net.ParseCIDR(addr.IP().String() + "/" + prefix)
|
_, ipnet, _ := net.ParseCIDR(addr.IP().String() + "/" + prefix)
|
||||||
|
|
||||||
ones, bits := ipnet.Mask.Size()
|
ones, bits := ipnet.Mask.Size()
|
||||||
|
|||||||
@@ -22,8 +22,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestInterfaces(t *testing.T) {
|
func TestInterfaces(t *testing.T) {
|
||||||
_ = (outbound.Handler)(new(Handler))
|
_ = outbound.Handler(new(Handler))
|
||||||
_ = (outbound.Manager)(new(Manager))
|
_ = outbound.Manager(new(Manager))
|
||||||
}
|
}
|
||||||
|
|
||||||
const xrayKey core.XrayKey = 1
|
const xrayKey core.XrayKey = 1
|
||||||
@@ -43,12 +43,12 @@ func TestOutboundWithoutStatCounter(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
v, _ := core.New(config)
|
v, _ := core.New(config)
|
||||||
v.AddFeature((outbound.Manager)(new(Manager)))
|
v.AddFeature(outbound.Manager(new(Manager)))
|
||||||
ctx := context.WithValue(context.Background(), xrayKey, v)
|
ctx := context.WithValue(context.Background(), xrayKey, v)
|
||||||
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}})
|
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}})
|
||||||
h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{
|
h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{
|
||||||
Tag: "tag",
|
Tag: "tag",
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||||
})
|
})
|
||||||
conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146))
|
conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146))
|
||||||
_, ok := conn.(*stat.CounterConnection)
|
_, ok := conn.(*stat.CounterConnection)
|
||||||
@@ -73,12 +73,12 @@ func TestOutboundWithStatCounter(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
v, _ := core.New(config)
|
v, _ := core.New(config)
|
||||||
v.AddFeature((outbound.Manager)(new(Manager)))
|
v.AddFeature(outbound.Manager(new(Manager)))
|
||||||
ctx := context.WithValue(context.Background(), xrayKey, v)
|
ctx := context.WithValue(context.Background(), xrayKey, v)
|
||||||
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}})
|
ctx = session.ContextWithOutbounds(ctx, []*session.Outbound{{}})
|
||||||
h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{
|
h, _ := NewHandler(ctx, &core.OutboundHandlerConfig{
|
||||||
Tag: "tag",
|
Tag: "tag",
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||||
})
|
})
|
||||||
conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146))
|
conn, _ := h.(*Handler).Dial(ctx, net.TCPDestination(net.DomainAddress("localhost"), 13146))
|
||||||
_, ok := conn.(*stat.CounterConnection)
|
_, ok := conn.(*stat.CounterConnection)
|
||||||
@@ -88,7 +88,6 @@ func TestOutboundWithStatCounter(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestTagsCache(t *testing.T) {
|
func TestTagsCache(t *testing.T) {
|
||||||
|
|
||||||
test_duration := 10 * time.Second
|
test_duration := 10 * time.Second
|
||||||
threads_num := 50
|
threads_num := 50
|
||||||
delay := 10 * time.Millisecond
|
delay := 10 * time.Millisecond
|
||||||
@@ -118,7 +117,7 @@ func TestTagsCache(t *testing.T) {
|
|||||||
tag := fmt.Sprintf("%s%d", tags_prefix, idx)
|
tag := fmt.Sprintf("%s%d", tags_prefix, idx)
|
||||||
cfg := &core.OutboundHandlerConfig{
|
cfg := &core.OutboundHandlerConfig{
|
||||||
Tag: tag,
|
Tag: tag,
|
||||||
ProxySettings: serial.ToTypedMessage(&freedom.Config{}),
|
ProxySettings: serial.ToTypedMessage(&freedom.Config{FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}}}),
|
||||||
}
|
}
|
||||||
if h, err := NewHandler(ctx, cfg); err == nil {
|
if h, err := NewHandler(ctx, cfg); err == nil {
|
||||||
if err := ohm.AddHandler(ctx, h); err == nil {
|
if err := ohm.AddHandler(ctx, h); err == nil {
|
||||||
|
|||||||
@@ -162,7 +162,6 @@ func (m *Manager) ListHandlers(ctx context.Context) []outbound.Handler {
|
|||||||
|
|
||||||
// Select implements outbound.HandlerSelector.
|
// Select implements outbound.HandlerSelector.
|
||||||
func (m *Manager) Select(selectors []string) []string {
|
func (m *Manager) Select(selectors []string) []string {
|
||||||
|
|
||||||
key := strings.Join(selectors, ",")
|
key := strings.Join(selectors, ",")
|
||||||
if cache, ok := m.tagsCache.Load(key); ok {
|
if cache, ok := m.tagsCache.Load(key); ok {
|
||||||
return cache.([]string)
|
return cache.([]string)
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/uot"
|
|
||||||
"github.com/xtls/xray-core/common/errors"
|
|
||||||
"github.com/xtls/xray-core/common/net"
|
|
||||||
"github.com/xtls/xray-core/transport/internet"
|
|
||||||
"github.com/xtls/xray-core/transport/internet/stat"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (h *Handler) getUoTConnection(ctx context.Context, dest net.Destination) (stat.Connection, error) {
|
|
||||||
if dest.Address == nil {
|
|
||||||
return nil, errors.New("nil destination address")
|
|
||||||
}
|
|
||||||
if !dest.Address.Family().IsDomain() {
|
|
||||||
return nil, os.ErrInvalid
|
|
||||||
}
|
|
||||||
var uotVersion int
|
|
||||||
if dest.Address.Domain() == uot.MagicAddress {
|
|
||||||
uotVersion = uot.Version
|
|
||||||
} else if dest.Address.Domain() == uot.LegacyMagicAddress {
|
|
||||||
uotVersion = uot.LegacyVersion
|
|
||||||
} else {
|
|
||||||
return nil, os.ErrInvalid
|
|
||||||
}
|
|
||||||
packetConn, err := internet.ListenSystemPacket(ctx, &net.UDPAddr{IP: net.AnyIP.IP(), Port: 0}, h.streamSettings.SocketSettings)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("unable to listen socket").Base(err)
|
|
||||||
}
|
|
||||||
conn := uot.NewServerConn(packetConn, uotVersion)
|
|
||||||
return h.getStatCouterConnection(conn), nil
|
|
||||||
}
|
|
||||||
@@ -136,7 +136,7 @@ func (b *Balancer) SelectOutbounds() ([]string, error) {
|
|||||||
|
|
||||||
// GetPrincipleTarget implements routing.BalancerPrincipleTarget
|
// GetPrincipleTarget implements routing.BalancerPrincipleTarget
|
||||||
func (r *Router) GetPrincipleTarget(tag string) ([]string, error) {
|
func (r *Router) GetPrincipleTarget(tag string) ([]string, error) {
|
||||||
if b, ok := r.balancers[tag]; ok {
|
if b, ok := (*r.balancers.Load())[tag]; ok {
|
||||||
if s, ok := b.strategy.(BalancingPrincipleTarget); ok {
|
if s, ok := b.strategy.(BalancingPrincipleTarget); ok {
|
||||||
candidates, err := b.SelectOutbounds()
|
candidates, err := b.SelectOutbounds()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -151,7 +151,7 @@ func (r *Router) GetPrincipleTarget(tag string) ([]string, error) {
|
|||||||
|
|
||||||
// SetOverrideTarget implements routing.BalancerOverrider
|
// SetOverrideTarget implements routing.BalancerOverrider
|
||||||
func (r *Router) SetOverrideTarget(tag, target string) error {
|
func (r *Router) SetOverrideTarget(tag, target string) error {
|
||||||
if b, ok := r.balancers[tag]; ok {
|
if b, ok := (*r.balancers.Load())[tag]; ok {
|
||||||
b.override.Put(target)
|
b.override.Put(target)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -160,7 +160,7 @@ func (r *Router) SetOverrideTarget(tag, target string) error {
|
|||||||
|
|
||||||
// GetOverrideTarget implements routing.BalancerOverrider
|
// GetOverrideTarget implements routing.BalancerOverrider
|
||||||
func (r *Router) GetOverrideTarget(tag string) (string, error) {
|
func (r *Router) GetOverrideTarget(tag string) (string, error) {
|
||||||
if b, ok := r.balancers[tag]; ok {
|
if b, ok := (*r.balancers.Load())[tag]; ok {
|
||||||
return b.override.Get(), nil
|
return b.override.Get(), nil
|
||||||
}
|
}
|
||||||
return "", errors.New("cannot find tag")
|
return "", errors.New("cannot find tag")
|
||||||
|
|||||||
@@ -2,25 +2,8 @@ package router
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
sync "sync"
|
sync "sync"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/errors"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func (r *Router) OverrideBalancer(balancer string, target string) error {
|
|
||||||
var b *Balancer
|
|
||||||
for tag, bl := range r.balancers {
|
|
||||||
if tag == balancer {
|
|
||||||
b = bl
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if b == nil {
|
|
||||||
return errors.New("balancer '", balancer, "' not found")
|
|
||||||
}
|
|
||||||
b.override.Put(target)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type overrideSettings struct {
|
type overrideSettings struct {
|
||||||
target string
|
target string
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,7 +58,6 @@ func (s *routingServer) AddRule(ctx context.Context, request *AddRuleRequest) (*
|
|||||||
return &AddRuleResponse{}, bo.AddRule(request.Config, request.ShouldAppend)
|
return &AddRuleResponse{}, bo.AddRule(request.Config, request.ShouldAppend)
|
||||||
}
|
}
|
||||||
return nil, errors.New("unsupported router implementation")
|
return nil, errors.New("unsupported router implementation")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *routingServer) RemoveRule(ctx context.Context, request *RemoveRuleRequest) (*RemoveRuleResponse, error) {
|
func (s *routingServer) RemoveRule(ctx context.Context, request *RemoveRuleRequest) (*RemoveRuleResponse, error) {
|
||||||
|
|||||||
@@ -308,7 +308,7 @@ func TestServiceTestRoute(t *testing.T) {
|
|||||||
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
SourceIp: []*geodata.IPRule{{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDR{Ip: []byte{127, 0, 0, 0}, Prefix: 8}}}},
|
SourceIp: []*geodata.IPRule{{Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{Cidr: &geodata.CIDR{Ip: []byte{127, 0, 0, 0}, Prefix: 8}}}}},
|
||||||
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
TargetTag: &router.RoutingRule_Tag{Tag: "out"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
+28
-1
@@ -5,6 +5,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"runtime"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -12,6 +13,7 @@ import (
|
|||||||
"github.com/xtls/xray-core/common/geodata"
|
"github.com/xtls/xray-core/common/geodata"
|
||||||
"github.com/xtls/xray-core/common/net"
|
"github.com/xtls/xray-core/common/net"
|
||||||
"github.com/xtls/xray-core/features/routing"
|
"github.com/xtls/xray-core/features/routing"
|
||||||
|
"github.com/xtls/xray-core/features/routing/dns"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Condition interface {
|
type Condition interface {
|
||||||
@@ -356,7 +358,13 @@ func (m *ProcessNameMatcher) Apply(ctx routing.Context) bool {
|
|||||||
|
|
||||||
var dstIP string
|
var dstIP string
|
||||||
var dstPort uint16 = 0
|
var dstPort uint16 = 0
|
||||||
if len(ctx.GetTargetIPs()) > 0 {
|
|
||||||
|
// do not use resolved IP because Android process lookup needs original dst ip
|
||||||
|
resolvableContext, ok := ctx.(*dns.ResolvableContext)
|
||||||
|
if ok && len(resolvableContext.Context.GetTargetIPs()) > 0 {
|
||||||
|
dstIP = resolvableContext.Context.GetTargetIPs()[0].String()
|
||||||
|
dstPort = uint16(resolvableContext.Context.GetTargetPort())
|
||||||
|
} else if len(ctx.GetTargetIPs()) > 0 {
|
||||||
dstIP = ctx.GetTargetIPs()[0].String()
|
dstIP = ctx.GetTargetIPs()[0].String()
|
||||||
dstPort = uint16(ctx.GetTargetPort())
|
dstPort = uint16(ctx.GetTargetPort())
|
||||||
}
|
}
|
||||||
@@ -386,3 +394,22 @@ func (m *ProcessNameMatcher) Apply(ctx routing.Context) bool {
|
|||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LocalOSMatcher matches the operating system Xray itself is running on. That never
|
||||||
|
// changes while Xray is running, so the result is resolved when the rule is built.
|
||||||
|
type LocalOSMatcher struct {
|
||||||
|
matched bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLocalOSMatcher(names []string) *LocalOSMatcher {
|
||||||
|
return &LocalOSMatcher{
|
||||||
|
matched: slices.ContainsFunc(names, func(name string) bool {
|
||||||
|
return strings.EqualFold(name, runtime.GOOS)
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply implements Condition.
|
||||||
|
func (m *LocalOSMatcher) Apply(_ routing.Context) bool {
|
||||||
|
return m.matched
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ package router_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
. "github.com/xtls/xray-core/app/router"
|
. "github.com/xtls/xray-core/app/router"
|
||||||
@@ -92,25 +94,22 @@ func TestRoutingRule(t *testing.T) {
|
|||||||
Ip: []*geodata.IPRule{
|
Ip: []*geodata.IPRule{
|
||||||
{
|
{
|
||||||
Value: &geodata.IPRule_Custom{
|
Value: &geodata.IPRule_Custom{
|
||||||
Custom: &geodata.CIDR{
|
Custom: &geodata.CIDRRule{
|
||||||
Ip: []byte{8, 8, 8, 8},
|
Cidr: &geodata.CIDR{Ip: []byte{8, 8, 8, 8}, Prefix: 32},
|
||||||
Prefix: 32,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Value: &geodata.IPRule_Custom{
|
Value: &geodata.IPRule_Custom{
|
||||||
Custom: &geodata.CIDR{
|
Custom: &geodata.CIDRRule{
|
||||||
Ip: []byte{8, 8, 8, 8},
|
Cidr: &geodata.CIDR{Ip: []byte{8, 8, 8, 8}, Prefix: 32},
|
||||||
Prefix: 32,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
Value: &geodata.IPRule_Custom{
|
Value: &geodata.IPRule_Custom{
|
||||||
Custom: &geodata.CIDR{
|
Custom: &geodata.CIDRRule{
|
||||||
Ip: net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334").IP(),
|
Cidr: &geodata.CIDR{Ip: net.ParseAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334").IP(), Prefix: 128},
|
||||||
Prefix: 128,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -140,9 +139,8 @@ func TestRoutingRule(t *testing.T) {
|
|||||||
SourceIp: []*geodata.IPRule{
|
SourceIp: []*geodata.IPRule{
|
||||||
{
|
{
|
||||||
Value: &geodata.IPRule_Custom{
|
Value: &geodata.IPRule_Custom{
|
||||||
Custom: &geodata.CIDR{
|
Custom: &geodata.CIDRRule{
|
||||||
Ip: []byte{192, 168, 0, 0},
|
Cidr: &geodata.CIDR{Ip: []byte{192, 168, 0, 0}, Prefix: 16},
|
||||||
Prefix: 16,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -347,6 +345,31 @@ func TestChinaSites(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLocalOSRule(t *testing.T) {
|
||||||
|
otherOS := "plan9"
|
||||||
|
if runtime.GOOS == otherOS {
|
||||||
|
otherOS = "linux"
|
||||||
|
}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
localOS []string
|
||||||
|
output bool
|
||||||
|
}{
|
||||||
|
{localOS: []string{runtime.GOOS}, output: true},
|
||||||
|
{localOS: []string{otherOS}, output: false},
|
||||||
|
{localOS: []string{otherOS, runtime.GOOS}, output: true},
|
||||||
|
{localOS: []string{strings.ToUpper(runtime.GOOS)}, output: true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range cases {
|
||||||
|
cond, err := (&RoutingRule{LocalOs: test.localOS}).BuildCondition()
|
||||||
|
common.Must(err)
|
||||||
|
if got := cond.Apply(withBackground()); got != test.output {
|
||||||
|
t.Errorf("for localOS %v on %s: expected %v, got %v", test.localOS, runtime.GOOS, test.output, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func BenchmarkMphDomainMatcher(b *testing.B) {
|
func BenchmarkMphDomainMatcher(b *testing.B) {
|
||||||
b.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
b.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||||
rules, err := geodata.ParseDomainRules([]string{"geosite:cn"}, geodata.Domain_Substr)
|
rules, err := geodata.ParseDomainRules([]string{"geosite:cn"}, geodata.Domain_Substr)
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ func (r *Rule) Apply(ctx routing.Context) bool {
|
|||||||
func (rr *RoutingRule) BuildCondition() (Condition, error) {
|
func (rr *RoutingRule) BuildCondition() (Condition, error) {
|
||||||
conds := NewConditionChan()
|
conds := NewConditionChan()
|
||||||
|
|
||||||
|
if len(rr.LocalOs) > 0 {
|
||||||
|
conds.Add(NewLocalOSMatcher(rr.LocalOs))
|
||||||
|
}
|
||||||
|
|
||||||
if len(rr.InboundTag) > 0 {
|
if len(rr.InboundTag) > 0 {
|
||||||
conds.Add(NewInboundTagMatcher(rr.InboundTag))
|
conds.Add(NewInboundTagMatcher(rr.InboundTag))
|
||||||
}
|
}
|
||||||
|
|||||||
+24
-4
@@ -107,6 +107,8 @@ type RoutingRule struct {
|
|||||||
VlessRouteList *net.PortList `protobuf:"bytes,20,opt,name=vless_route_list,json=vlessRouteList,proto3" json:"vless_route_list,omitempty"`
|
VlessRouteList *net.PortList `protobuf:"bytes,20,opt,name=vless_route_list,json=vlessRouteList,proto3" json:"vless_route_list,omitempty"`
|
||||||
Process []string `protobuf:"bytes,21,rep,name=process,proto3" json:"process,omitempty"`
|
Process []string `protobuf:"bytes,21,rep,name=process,proto3" json:"process,omitempty"`
|
||||||
Webhook *WebhookConfig `protobuf:"bytes,22,opt,name=webhook,proto3" json:"webhook,omitempty"`
|
Webhook *WebhookConfig `protobuf:"bytes,22,opt,name=webhook,proto3" json:"webhook,omitempty"`
|
||||||
|
// List of operating systems for matching the one Xray itself is running on.
|
||||||
|
LocalOs []string `protobuf:"bytes,23,rep,name=local_os,json=localOs,proto3" json:"local_os,omitempty"`
|
||||||
unknownFields protoimpl.UnknownFields
|
unknownFields protoimpl.UnknownFields
|
||||||
sizeCache protoimpl.SizeCache
|
sizeCache protoimpl.SizeCache
|
||||||
}
|
}
|
||||||
@@ -278,6 +280,13 @@ func (x *RoutingRule) GetWebhook() *WebhookConfig {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (x *RoutingRule) GetLocalOs() []string {
|
||||||
|
if x != nil {
|
||||||
|
return x.LocalOs
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
type isRoutingRule_TargetTag interface {
|
type isRoutingRule_TargetTag interface {
|
||||||
isRoutingRule_TargetTag()
|
isRoutingRule_TargetTag()
|
||||||
}
|
}
|
||||||
@@ -578,6 +587,8 @@ type Config struct {
|
|||||||
DomainStrategy Config_DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=xray.app.router.Config_DomainStrategy" json:"domain_strategy,omitempty"`
|
DomainStrategy Config_DomainStrategy `protobuf:"varint,1,opt,name=domain_strategy,json=domainStrategy,proto3,enum=xray.app.router.Config_DomainStrategy" json:"domain_strategy,omitempty"`
|
||||||
Rule []*RoutingRule `protobuf:"bytes,2,rep,name=rule,proto3" json:"rule,omitempty"`
|
Rule []*RoutingRule `protobuf:"bytes,2,rep,name=rule,proto3" json:"rule,omitempty"`
|
||||||
BalancingRule []*BalancingRule `protobuf:"bytes,3,rep,name=balancing_rule,json=balancingRule,proto3" json:"balancing_rule,omitempty"`
|
BalancingRule []*BalancingRule `protobuf:"bytes,3,rep,name=balancing_rule,json=balancingRule,proto3" json:"balancing_rule,omitempty"`
|
||||||
|
// Absolute path to the Lua routing script.
|
||||||
|
Script string `protobuf:"bytes,4,opt,name=script,proto3" json:"script,omitempty"`
|
||||||
unknownFields protoimpl.UnknownFields
|
unknownFields protoimpl.UnknownFields
|
||||||
sizeCache protoimpl.SizeCache
|
sizeCache protoimpl.SizeCache
|
||||||
}
|
}
|
||||||
@@ -633,11 +644,18 @@ func (x *Config) GetBalancingRule() []*BalancingRule {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (x *Config) GetScript() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Script
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
var File_app_router_config_proto protoreflect.FileDescriptor
|
var File_app_router_config_proto protoreflect.FileDescriptor
|
||||||
|
|
||||||
const file_app_router_config_proto_rawDesc = "" +
|
const file_app_router_config_proto_rawDesc = "" +
|
||||||
"\n" +
|
"\n" +
|
||||||
"\x17app/router/config.proto\x12\x0fxray.app.router\x1a!common/serial/typed_message.proto\x1a\x15common/net/port.proto\x1a\x18common/net/network.proto\x1a\x1bcommon/geodata/geodat.proto\"\xc1\a\n" +
|
"\x17app/router/config.proto\x12\x0fxray.app.router\x1a!common/serial/typed_message.proto\x1a\x15common/net/port.proto\x1a\x18common/net/network.proto\x1a\x1bcommon/geodata/geodat.proto\"\xdc\a\n" +
|
||||||
"\vRoutingRule\x12\x12\n" +
|
"\vRoutingRule\x12\x12\n" +
|
||||||
"\x03tag\x18\x01 \x01(\tH\x00R\x03tag\x12%\n" +
|
"\x03tag\x18\x01 \x01(\tH\x00R\x03tag\x12%\n" +
|
||||||
"\rbalancing_tag\x18\f \x01(\tH\x00R\fbalancingTag\x12\x19\n" +
|
"\rbalancing_tag\x18\f \x01(\tH\x00R\fbalancingTag\x12\x19\n" +
|
||||||
@@ -661,7 +679,8 @@ const file_app_router_config_proto_rawDesc = "" +
|
|||||||
"\x0flocal_port_list\x18\x12 \x01(\v2\x19.xray.common.net.PortListR\rlocalPortList\x12C\n" +
|
"\x0flocal_port_list\x18\x12 \x01(\v2\x19.xray.common.net.PortListR\rlocalPortList\x12C\n" +
|
||||||
"\x10vless_route_list\x18\x14 \x01(\v2\x19.xray.common.net.PortListR\x0evlessRouteList\x12\x18\n" +
|
"\x10vless_route_list\x18\x14 \x01(\v2\x19.xray.common.net.PortListR\x0evlessRouteList\x12\x18\n" +
|
||||||
"\aprocess\x18\x15 \x03(\tR\aprocess\x128\n" +
|
"\aprocess\x18\x15 \x03(\tR\aprocess\x128\n" +
|
||||||
"\awebhook\x18\x16 \x01(\v2\x1e.xray.app.router.WebhookConfigR\awebhook\x1a=\n" +
|
"\awebhook\x18\x16 \x01(\v2\x1e.xray.app.router.WebhookConfigR\awebhook\x12\x19\n" +
|
||||||
|
"\blocal_os\x18\x17 \x03(\tR\alocalOs\x1a=\n" +
|
||||||
"\x0fAttributesEntry\x12\x10\n" +
|
"\x0fAttributesEntry\x12\x10\n" +
|
||||||
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
|
||||||
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\f\n" +
|
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\f\n" +
|
||||||
@@ -689,11 +708,12 @@ const file_app_router_config_proto_rawDesc = "" +
|
|||||||
"\tbaselines\x18\x03 \x03(\x03R\tbaselines\x12\x1a\n" +
|
"\tbaselines\x18\x03 \x03(\x03R\tbaselines\x12\x1a\n" +
|
||||||
"\bexpected\x18\x04 \x01(\x05R\bexpected\x12\x16\n" +
|
"\bexpected\x18\x04 \x01(\x05R\bexpected\x12\x16\n" +
|
||||||
"\x06maxRTT\x18\x05 \x01(\x03R\x06maxRTT\x12\x1c\n" +
|
"\x06maxRTT\x18\x05 \x01(\x03R\x06maxRTT\x12\x1c\n" +
|
||||||
"\ttolerance\x18\x06 \x01(\x02R\ttolerance\"\x96\x02\n" +
|
"\ttolerance\x18\x06 \x01(\x02R\ttolerance\"\xae\x02\n" +
|
||||||
"\x06Config\x12O\n" +
|
"\x06Config\x12O\n" +
|
||||||
"\x0fdomain_strategy\x18\x01 \x01(\x0e2&.xray.app.router.Config.DomainStrategyR\x0edomainStrategy\x120\n" +
|
"\x0fdomain_strategy\x18\x01 \x01(\x0e2&.xray.app.router.Config.DomainStrategyR\x0edomainStrategy\x120\n" +
|
||||||
"\x04rule\x18\x02 \x03(\v2\x1c.xray.app.router.RoutingRuleR\x04rule\x12E\n" +
|
"\x04rule\x18\x02 \x03(\v2\x1c.xray.app.router.RoutingRuleR\x04rule\x12E\n" +
|
||||||
"\x0ebalancing_rule\x18\x03 \x03(\v2\x1e.xray.app.router.BalancingRuleR\rbalancingRule\"B\n" +
|
"\x0ebalancing_rule\x18\x03 \x03(\v2\x1e.xray.app.router.BalancingRuleR\rbalancingRule\x12\x16\n" +
|
||||||
|
"\x06script\x18\x04 \x01(\tR\x06script\"B\n" +
|
||||||
"\x0eDomainStrategy\x12\b\n" +
|
"\x0eDomainStrategy\x12\b\n" +
|
||||||
"\x04AsIs\x10\x00\x12\x10\n" +
|
"\x04AsIs\x10\x00\x12\x10\n" +
|
||||||
"\fIpIfNonMatch\x10\x02\x12\x0e\n" +
|
"\fIpIfNonMatch\x10\x02\x12\x0e\n" +
|
||||||
|
|||||||
@@ -56,6 +56,9 @@ message RoutingRule {
|
|||||||
|
|
||||||
repeated string process = 21;
|
repeated string process = 21;
|
||||||
WebhookConfig webhook = 22;
|
WebhookConfig webhook = 22;
|
||||||
|
|
||||||
|
// List of operating systems for matching the one Xray itself is running on.
|
||||||
|
repeated string local_os = 23;
|
||||||
}
|
}
|
||||||
|
|
||||||
message WebhookConfig {
|
message WebhookConfig {
|
||||||
@@ -107,4 +110,6 @@ message Config {
|
|||||||
DomainStrategy domain_strategy = 1;
|
DomainStrategy domain_strategy = 1;
|
||||||
repeated RoutingRule rule = 2;
|
repeated RoutingRule rule = 2;
|
||||||
repeated BalancingRule balancing_rule = 3;
|
repeated BalancingRule balancing_rule = 3;
|
||||||
|
// Absolute path to the Lua routing script.
|
||||||
|
string script = 4;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,206 @@
|
|||||||
|
package router
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
"github.com/xtls/xray-core/features/routing"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
luaContextType = "xray.router.Context"
|
||||||
|
luaAttributesType = "xray.router.Attributes"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RegisterLua makes xray.router available to routing scripts.
|
||||||
|
func (r *Router) RegisterLua(L *lua.LState) {
|
||||||
|
registerLuaContext(L)
|
||||||
|
|
||||||
|
L.PreloadModule("xray.router", func(L *lua.LState) int {
|
||||||
|
module := L.NewTable()
|
||||||
|
|
||||||
|
module.RawSetString("NetworkUnknown", lua.LNumber(net.Network_Unknown))
|
||||||
|
module.RawSetString("NetworkTCP", lua.LNumber(net.Network_TCP))
|
||||||
|
module.RawSetString("NetworkUDP", lua.LNumber(net.Network_UDP))
|
||||||
|
module.RawSetString("NetworkUNIX", lua.LNumber(net.Network_UNIX))
|
||||||
|
module.RawSetString("LocalOS", lua.LString(runtime.GOOS))
|
||||||
|
|
||||||
|
module.RawSetString("PickOutbound", L.NewFunction(func(L *lua.LState) int {
|
||||||
|
tag, ok := L.Get(2).(lua.LString)
|
||||||
|
if !ok {
|
||||||
|
L.ArgError(2, "balancer tag must be a string")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
balancer, found := (*r.balancers.Load())[string(tag)]
|
||||||
|
if !found {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
pushLuaError(L, errors.New("balancer ", tag, " not found"))
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
outboundTag, err := balancer.PickOutbound()
|
||||||
|
L.Push(lua.LString(outboundTag))
|
||||||
|
pushLuaError(L, err)
|
||||||
|
return 2
|
||||||
|
}))
|
||||||
|
|
||||||
|
module.RawSetString("FindProcess", L.NewFunction(func(L *lua.LState) int {
|
||||||
|
pid, name, path, err := findProcess(checkLuaContext(L), net.FindProcess)
|
||||||
|
L.Push(lua.LNumber(pid))
|
||||||
|
L.Push(lua.LString(name))
|
||||||
|
L.Push(lua.LString(path))
|
||||||
|
pushLuaError(L, err)
|
||||||
|
return 4
|
||||||
|
}))
|
||||||
|
|
||||||
|
L.Push(module)
|
||||||
|
return 1
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func registerLuaContext(L *lua.LState) {
|
||||||
|
attributes := L.NewTypeMetatable(luaAttributesType)
|
||||||
|
L.SetField(attributes, "__index", L.NewFunction(func(L *lua.LState) int {
|
||||||
|
values := L.CheckUserData(1).Value.(map[string]string)
|
||||||
|
key := L.CheckString(2)
|
||||||
|
if value, found := values[key]; found {
|
||||||
|
L.Push(lua.LString(value))
|
||||||
|
} else {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
}
|
||||||
|
return 1
|
||||||
|
}))
|
||||||
|
methods := L.NewTable()
|
||||||
|
L.SetFuncs(methods, map[string]lua.LGFunction{
|
||||||
|
"GetSourceIPs": func(L *lua.LState) int {
|
||||||
|
return pushLuaIPs(L, checkLuaContext(L).GetSourceIPs())
|
||||||
|
},
|
||||||
|
"GetTargetIPs": func(L *lua.LState) int {
|
||||||
|
return pushLuaIPs(L, checkLuaContext(L).GetTargetIPs())
|
||||||
|
},
|
||||||
|
"GetLocalIPs": func(L *lua.LState) int {
|
||||||
|
return pushLuaIPs(L, checkLuaContext(L).GetLocalIPs())
|
||||||
|
},
|
||||||
|
"GetAttributes": func(L *lua.LState) int {
|
||||||
|
values := L.NewUserData()
|
||||||
|
values.Value = checkLuaContext(L).GetAttributes()
|
||||||
|
L.SetMetatable(values, attributes)
|
||||||
|
L.Push(values)
|
||||||
|
return 1
|
||||||
|
},
|
||||||
|
})
|
||||||
|
L.SetField(L.NewTypeMetatable(luaContextType), "__index", methods)
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkLuaContext(L *lua.LState) routing.Context {
|
||||||
|
ctx, ok := L.CheckUserData(1).Value.(routing.Context)
|
||||||
|
if !ok {
|
||||||
|
L.ArgError(1, "routing context expected")
|
||||||
|
}
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func pushLuaIPs(L *lua.LState, ips []net.IP) int {
|
||||||
|
addresses := L.NewUserData()
|
||||||
|
addresses.Value = ips
|
||||||
|
L.Push(addresses)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func pushLuaError(L *lua.LState, err error) {
|
||||||
|
if err == nil {
|
||||||
|
L.Push(lua.LNil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
value := L.NewUserData()
|
||||||
|
value.Value = err
|
||||||
|
L.Push(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CallLuaHook invokes HandleRoute in the supplied state.
|
||||||
|
func (r *Router) CallLuaHook(L *lua.LState, ctx context.Context, routeCtx routing.Context) (string, string, error) {
|
||||||
|
previous, top := L.Context(), L.GetTop()
|
||||||
|
L.SetContext(ctx)
|
||||||
|
defer func() {
|
||||||
|
L.SetTop(top)
|
||||||
|
if previous == nil {
|
||||||
|
L.RemoveContext()
|
||||||
|
} else {
|
||||||
|
L.SetContext(previous)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
fn := L.GetGlobal("HandleRoute")
|
||||||
|
if fn.Type() != lua.LTFunction {
|
||||||
|
return "", "", errors.New("routing script must define HandleRoute(...)")
|
||||||
|
}
|
||||||
|
value := L.NewUserData()
|
||||||
|
value.Value = routeCtx
|
||||||
|
L.SetMetatable(value, L.GetTypeMetatable(luaContextType))
|
||||||
|
if err := L.CallByParam(lua.P{Fn: fn, NRet: 3, Protect: true},
|
||||||
|
value, lua.LString(routeCtx.GetInboundTag()), lua.LNumber(routeCtx.GetSourcePort()),
|
||||||
|
lua.LNumber(routeCtx.GetTargetPort()), lua.LNumber(routeCtx.GetLocalPort()),
|
||||||
|
lua.LString(routeCtx.GetTargetDomain()), lua.LNumber(routeCtx.GetNetwork()),
|
||||||
|
lua.LString(routeCtx.GetProtocol()), lua.LString(routeCtx.GetUser()),
|
||||||
|
lua.LNumber(routeCtx.GetVlessRoute()), lua.LBool(routeCtx.GetSkipDNSResolve())); err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
return readLuaRouteResult(L.Get(-3), L.Get(-2), L.Get(-1))
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLuaRouteResult(tagValue, ruleValue, errorValue lua.LValue) (string, string, error) {
|
||||||
|
if errorValue != lua.LNil {
|
||||||
|
if value, ok := errorValue.(*lua.LUserData); ok {
|
||||||
|
if err, ok := value.Value.(error); ok {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if value, ok := errorValue.(lua.LString); ok {
|
||||||
|
return "", "", errors.New(string(value))
|
||||||
|
}
|
||||||
|
return "", "", errors.New("routing script error must be an error or string")
|
||||||
|
}
|
||||||
|
if tagValue == lua.LNil {
|
||||||
|
return "", "", nil
|
||||||
|
}
|
||||||
|
tag, ok := tagValue.(lua.LString)
|
||||||
|
if !ok {
|
||||||
|
return "", "", errors.New("routing script outboundTag must be a string or nil")
|
||||||
|
}
|
||||||
|
if tag == "" {
|
||||||
|
return "", "", nil
|
||||||
|
}
|
||||||
|
var ruleTag string
|
||||||
|
if ruleValue != lua.LNil {
|
||||||
|
value, ok := ruleValue.(lua.LString)
|
||||||
|
if !ok {
|
||||||
|
return "", "", errors.New("routing script ruleTag must be a string")
|
||||||
|
}
|
||||||
|
ruleTag = string(value)
|
||||||
|
}
|
||||||
|
return string(tag), ruleTag, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type processFinder func(string, string, uint16, string, uint16) (int, string, string, error)
|
||||||
|
|
||||||
|
func findProcess(ctx routing.Context, finder processFinder) (int, string, string, error) {
|
||||||
|
sources := ctx.GetSourceIPs()
|
||||||
|
if len(sources) == 0 {
|
||||||
|
return 0, "", "", errors.New("process lookup requires a source IP")
|
||||||
|
}
|
||||||
|
var network string
|
||||||
|
switch ctx.GetNetwork() {
|
||||||
|
case net.Network_TCP:
|
||||||
|
network = "tcp"
|
||||||
|
case net.Network_UDP:
|
||||||
|
network = "udp"
|
||||||
|
default:
|
||||||
|
return 0, "", "", errors.New("process lookup requires TCP or UDP")
|
||||||
|
}
|
||||||
|
targetIP, targetPort := "", uint16(0)
|
||||||
|
if targets := ctx.GetTargetIPs(); len(targets) > 0 {
|
||||||
|
targetIP, targetPort = targets[0].String(), uint16(ctx.GetTargetPort())
|
||||||
|
}
|
||||||
|
return finder(network, sources[0].String(), uint16(ctx.GetSourcePort()), targetIP, targetPort)
|
||||||
|
}
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
package router
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
go_errors "errors"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/geodata"
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
"github.com/xtls/xray-core/common/protocol"
|
||||||
|
"github.com/xtls/xray-core/common/session"
|
||||||
|
"github.com/xtls/xray-core/features/routing"
|
||||||
|
routing_session "github.com/xtls/xray-core/features/routing/session"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
)
|
||||||
|
|
||||||
|
type luaRouteTestContext struct {
|
||||||
|
*routing_session.Context
|
||||||
|
sourceIPs, targetIPs, localIPs []net.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *luaRouteTestContext) GetSourceIPs() []net.IP { return c.sourceIPs }
|
||||||
|
func (c *luaRouteTestContext) GetTargetIPs() []net.IP { return c.targetIPs }
|
||||||
|
func (c *luaRouteTestContext) GetLocalIPs() []net.IP { return c.localIPs }
|
||||||
|
|
||||||
|
func newLuaRouteTestContext() *luaRouteTestContext {
|
||||||
|
return &luaRouteTestContext{
|
||||||
|
Context: &routing_session.Context{
|
||||||
|
Inbound: &session.Inbound{
|
||||||
|
Tag: "in", VlessRoute: 4321,
|
||||||
|
Source: net.TCPDestination(net.LocalHostIP, 1234),
|
||||||
|
Local: net.TCPDestination(net.LocalHostIP, 5678),
|
||||||
|
User: &protocol.MemoryUser{Email: "user@example.com"},
|
||||||
|
},
|
||||||
|
Outbound: &session.Outbound{
|
||||||
|
Target: net.TCPDestination(net.LocalHostIP, 443),
|
||||||
|
RouteTarget: net.TCPDestination(net.DomainAddress("MiXeD.Example."), 443),
|
||||||
|
},
|
||||||
|
Content: &session.Content{
|
||||||
|
Protocol: "tls", Attributes: map[string]string{"key": "value"}, SkipDNSResolve: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
sourceIPs: []net.IP{{127, 0, 0, 2}},
|
||||||
|
targetIPs: []net.IP{{127, 0, 0, 3}},
|
||||||
|
localIPs: []net.IP{{127, 0, 0, 1}},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newLuaRouterState(t *testing.T, script string) (*Router, *lua.LState) {
|
||||||
|
t.Helper()
|
||||||
|
r := new(Router)
|
||||||
|
if err := r.Init(context.Background(), &Config{}, nil, nil, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
L := lua.NewState()
|
||||||
|
t.Cleanup(L.Close)
|
||||||
|
r.RegisterLua(L)
|
||||||
|
geodata.RegisterLua(L)
|
||||||
|
if err := L.DoString(script); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return r, L
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLuaRouteBinding(t *testing.T) {
|
||||||
|
r, L := newLuaRouterState(t, `
|
||||||
|
local router = require("xray.router")
|
||||||
|
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.0/8")
|
||||||
|
assert(router.NetworkUnknown == 0 and router.NetworkTCP == 2)
|
||||||
|
assert(router.NetworkUDP == 3 and router.NetworkUNIX == 4)
|
||||||
|
assert(router.BuildIPMatcher == nil and router.BuildDomainMatcher == nil)
|
||||||
|
function HandleRoute(ctx, inboundTag, sourcePort, targetPort, localPort,
|
||||||
|
targetDomain, network, protocol, user, vlessRoute, skipDNSResolve, ...)
|
||||||
|
assert(select("#", ...) == 0)
|
||||||
|
assert(inboundTag == "in" and sourcePort == 1234 and targetPort == 443 and localPort == 5678)
|
||||||
|
assert(targetDomain == "MiXeD.Example." and network == router.NetworkTCP)
|
||||||
|
assert(protocol == "tls" and user == "user@example.com" and vlessRoute == 4321 and skipDNSResolve)
|
||||||
|
assert(ctx.GetNetwork == nil and ctx.Context == nil)
|
||||||
|
savedContext = ctx
|
||||||
|
sourceIPs, targetIPs, localIPs = ctx:GetSourceIPs(), ctx:GetTargetIPs(), ctx:GetLocalIPs()
|
||||||
|
attributes = ctx:GetAttributes()
|
||||||
|
assert(matcher:AnyMatch(sourceIPs) and matcher:AnyMatch(targetIPs) and matcher:AnyMatch(localIPs))
|
||||||
|
assert(attributes.key == "value" and attributes.missing == nil)
|
||||||
|
assert(not pcall(function() attributes.key = "changed" end))
|
||||||
|
return "out", "rule"
|
||||||
|
end`)
|
||||||
|
|
||||||
|
ctx := newLuaRouteTestContext()
|
||||||
|
tag, rule, err := r.CallLuaHook(L, context.Background(), ctx)
|
||||||
|
if err != nil || tag != "out" || rule != "rule" {
|
||||||
|
t.Fatalf("hook = %q, %q, %v", tag, rule, err)
|
||||||
|
}
|
||||||
|
if L.GetGlobal("savedContext").(*lua.LUserData).Value != ctx {
|
||||||
|
t.Fatal("routing context was copied")
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
want []net.IP
|
||||||
|
}{
|
||||||
|
{"sourceIPs", ctx.sourceIPs},
|
||||||
|
{"targetIPs", ctx.targetIPs},
|
||||||
|
{"localIPs", ctx.localIPs},
|
||||||
|
} {
|
||||||
|
got := L.GetGlobal(tc.name).(*lua.LUserData).Value.([]net.IP)
|
||||||
|
if &got[0] != &tc.want[0] {
|
||||||
|
t.Fatalf("%s storage was copied", tc.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.Content.Attributes["key"] = "updated"
|
||||||
|
L.SetGlobal("expectedOS", lua.LString(runtime.GOOS))
|
||||||
|
if err := L.DoString(`
|
||||||
|
assert(attributes.key == "updated")
|
||||||
|
assert(require("xray.router").LocalOS == expectedOS)`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLuaRouteResult(t *testing.T) {
|
||||||
|
nativeErr := go_errors.New("native failure")
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, body, tag, rule, wantErr string
|
||||||
|
native bool
|
||||||
|
}{
|
||||||
|
{name: "route", body: `return "out", "rule"`, tag: "out", rule: "rule"},
|
||||||
|
{name: "no match", body: `return nil`},
|
||||||
|
{name: "empty tag", body: `return ""`},
|
||||||
|
{name: "invalid tag", body: `return 1`, wantErr: "outboundTag"},
|
||||||
|
{name: "invalid rule", body: `return "out", false`, wantErr: "ruleTag"},
|
||||||
|
{name: "string error", body: `return nil, nil, "script failure"`, wantErr: "script failure"},
|
||||||
|
{name: "native error", body: `return nil, nil, nativeError`, native: true},
|
||||||
|
{name: "runtime error", body: `error("runtime failure")`, wantErr: "runtime failure"},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
r, L := newLuaRouterState(t, "function HandleRoute() "+tc.body+" end")
|
||||||
|
value := L.NewUserData()
|
||||||
|
value.Value = nativeErr
|
||||||
|
L.SetGlobal("nativeError", value)
|
||||||
|
previous := context.WithValue(context.Background(), struct{}{}, true)
|
||||||
|
L.SetContext(previous)
|
||||||
|
L.Push(lua.LTrue)
|
||||||
|
|
||||||
|
tag, rule, err := r.CallLuaHook(L, context.Background(), &routing_session.Context{})
|
||||||
|
if tag != tc.tag || rule != tc.rule {
|
||||||
|
t.Fatalf("result = %q, %q, %v", tag, rule, err)
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case tc.native:
|
||||||
|
if err != nativeErr {
|
||||||
|
t.Fatalf("error = %v, want original error", err)
|
||||||
|
}
|
||||||
|
case tc.wantErr != "":
|
||||||
|
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
|
||||||
|
t.Fatalf("error = %v, want %q", err, tc.wantErr)
|
||||||
|
}
|
||||||
|
case err != nil:
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if L.Context() != previous || L.GetTop() != 1 || L.Get(1) != lua.LTrue {
|
||||||
|
t.Fatal("hook did not restore the previous context and stack")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLuaRouteCancellation(t *testing.T) {
|
||||||
|
r, L := newLuaRouterState(t, `function HandleRoute() while true do end end`)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if _, _, err := r.CallLuaHook(L, ctx, &routing_session.Context{}); err == nil {
|
||||||
|
t.Fatal("CallLuaHook did not stop after context cancellation")
|
||||||
|
}
|
||||||
|
if L.Context() != nil || L.GetTop() != 0 {
|
||||||
|
t.Fatal("CallLuaHook did not restore the Lua state")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFindProcess(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, network, target string
|
||||||
|
targetPort uint16
|
||||||
|
modify func(*luaRouteTestContext)
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{name: "TCP", network: "tcp", target: "127.0.0.3", targetPort: 443},
|
||||||
|
{name: "UDP", network: "udp", target: "127.0.0.3", targetPort: 443, modify: func(c *luaRouteTestContext) {
|
||||||
|
c.Outbound.Target.Network = net.Network_UDP
|
||||||
|
}},
|
||||||
|
{name: "domain target", network: "tcp", modify: func(c *luaRouteTestContext) { c.targetIPs = nil }},
|
||||||
|
{name: "missing source", modify: func(c *luaRouteTestContext) { c.sourceIPs = nil }, wantErr: true},
|
||||||
|
{name: "unsupported network", modify: func(c *luaRouteTestContext) {
|
||||||
|
c.Outbound.Target.Network = net.Network_UNIX
|
||||||
|
}, wantErr: true},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
ctx := newLuaRouteTestContext()
|
||||||
|
if tc.modify != nil {
|
||||||
|
tc.modify(ctx)
|
||||||
|
}
|
||||||
|
called := false
|
||||||
|
pid, name, path, err := findProcess(ctx, func(network, source string, sourcePort uint16, target string, targetPort uint16) (int, string, string, error) {
|
||||||
|
called = true
|
||||||
|
if network != tc.network || source != "127.0.0.2" || sourcePort != 1234 || target != tc.target || targetPort != tc.targetPort {
|
||||||
|
t.Fatalf("endpoints = %s %s:%d -> %s:%d", network, source, sourcePort, target, targetPort)
|
||||||
|
}
|
||||||
|
return 42, "process", "/path/process", nil
|
||||||
|
})
|
||||||
|
if tc.wantErr {
|
||||||
|
if err == nil || called {
|
||||||
|
t.Fatalf("findProcess = %d, %q, %q, %v", pid, name, path, err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil || !called || pid != 42 || name != "process" || path != "/path/process" {
|
||||||
|
t.Fatalf("findProcess = %d, %q, %q, %v", pid, name, path, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BenchmarkLuaRouteHookCall isolates a preloaded Lua hook and its routing context bridge.
|
||||||
|
// The direct case runs an equivalent native routing rule.
|
||||||
|
func BenchmarkLuaRouteHookCall(b *testing.B) {
|
||||||
|
r := new(Router)
|
||||||
|
if err := r.Init(context.Background(), &Config{Rule: []*RoutingRule{{
|
||||||
|
TargetTag: &RoutingRule_Tag{Tag: "out"},
|
||||||
|
RuleTag: "rule",
|
||||||
|
InboundTag: []string{"in"},
|
||||||
|
Networks: []net.Network{net.Network_TCP},
|
||||||
|
Ip: []*geodata.IPRule{{
|
||||||
|
Value: &geodata.IPRule_Custom{Custom: &geodata.CIDRRule{
|
||||||
|
Cidr: &geodata.CIDR{Ip: []byte{127, 0, 0, 0}, Prefix: 8},
|
||||||
|
}},
|
||||||
|
}},
|
||||||
|
}}}, nil, nil, nil); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
r.RegisterLua(L)
|
||||||
|
geodata.RegisterLua(L)
|
||||||
|
if err := L.DoString(`
|
||||||
|
local router = require("xray.router")
|
||||||
|
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.0/8")
|
||||||
|
function HandleRoute(ctx, inboundTag, sourcePort, targetPort, localPort,
|
||||||
|
targetDomain, network, protocol, user, vlessRoute, skipDNSResolve)
|
||||||
|
if inboundTag == "in" and network == router.NetworkTCP and matcher:AnyMatch(ctx:GetTargetIPs()) then
|
||||||
|
return "out", "rule"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
`); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
routeCtx := newLuaRouteTestContext()
|
||||||
|
for _, benchmark := range []struct {
|
||||||
|
name string
|
||||||
|
route func() (string, string, error)
|
||||||
|
}{
|
||||||
|
{"direct", func() (string, string, error) {
|
||||||
|
route, err := r.PickRoute(routeCtx)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
return route.GetOutboundTag(), route.GetRuleTag(), nil
|
||||||
|
}},
|
||||||
|
{"lua_hook", func() (string, string, error) {
|
||||||
|
return r.CallLuaHook(L, ctx, routeCtx)
|
||||||
|
}},
|
||||||
|
} {
|
||||||
|
b.Run(benchmark.name, func(b *testing.B) {
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.ResetTimer()
|
||||||
|
var tag, rule string
|
||||||
|
var err error
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
tag, rule, err = benchmark.route()
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.StopTimer()
|
||||||
|
if tag != "out" || rule != "rule" {
|
||||||
|
b.Fatalf("route() = %q, %q; want out, rule", tag, rule)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ routing.Context = (*luaRouteTestContext)(nil)
|
||||||
+73
-113
@@ -2,7 +2,9 @@ package router
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"maps"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common"
|
"github.com/xtls/xray-core/common"
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
@@ -17,8 +19,10 @@ import (
|
|||||||
// Router is an implementation of routing.Router.
|
// Router is an implementation of routing.Router.
|
||||||
type Router struct {
|
type Router struct {
|
||||||
domainStrategy Config_DomainStrategy
|
domainStrategy Config_DomainStrategy
|
||||||
rules []*Rule
|
rules atomic.Pointer[[]*Rule]
|
||||||
balancers map[string]*Balancer
|
scriptPath string
|
||||||
|
script *scriptEngine
|
||||||
|
balancers atomic.Pointer[map[string]*Balancer]
|
||||||
dns dns.Client
|
dns dns.Client
|
||||||
|
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
@@ -38,61 +42,23 @@ type Route struct {
|
|||||||
// Init initializes the Router.
|
// Init initializes the Router.
|
||||||
func (r *Router) Init(ctx context.Context, config *Config, d dns.Client, ohm outbound.Manager, dispatcher routing.Dispatcher) error {
|
func (r *Router) Init(ctx context.Context, config *Config, d dns.Client, ohm outbound.Manager, dispatcher routing.Dispatcher) error {
|
||||||
r.domainStrategy = config.DomainStrategy
|
r.domainStrategy = config.DomainStrategy
|
||||||
|
r.scriptPath = config.Script
|
||||||
r.dns = d
|
r.dns = d
|
||||||
r.ctx = ctx
|
r.ctx = ctx
|
||||||
r.ohm = ohm
|
r.ohm = ohm
|
||||||
r.dispatcher = dispatcher
|
r.dispatcher = dispatcher
|
||||||
|
|
||||||
r.balancers = make(map[string]*Balancer, len(config.BalancingRule))
|
r.rules.Store(new([]*Rule))
|
||||||
for _, rule := range config.BalancingRule {
|
r.balancers.Store(&map[string]*Balancer{})
|
||||||
balancer, err := rule.Build(ohm, dispatcher)
|
return r.ReloadRules(config, false)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
balancer.InjectContext(ctx)
|
|
||||||
r.balancers[rule.Tag] = balancer
|
|
||||||
}
|
|
||||||
|
|
||||||
r.rules = make([]*Rule, 0, len(config.Rule))
|
|
||||||
for _, rule := range config.Rule {
|
|
||||||
cond, err := rule.BuildCondition()
|
|
||||||
if err != nil {
|
|
||||||
r.closeWebhooks()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
rr := &Rule{
|
|
||||||
Condition: cond,
|
|
||||||
Tag: rule.GetTag(),
|
|
||||||
RuleTag: rule.GetRuleTag(),
|
|
||||||
}
|
|
||||||
if wh := rule.GetWebhook(); wh != nil {
|
|
||||||
notifier, err := NewWebhookNotifier(wh)
|
|
||||||
if err != nil {
|
|
||||||
r.closeWebhooks()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
rr.Webhook = notifier
|
|
||||||
}
|
|
||||||
btag := rule.GetBalancingTag()
|
|
||||||
if len(btag) > 0 {
|
|
||||||
brule, found := r.balancers[btag]
|
|
||||||
if !found {
|
|
||||||
if rr.Webhook != nil {
|
|
||||||
rr.Webhook.Close()
|
|
||||||
}
|
|
||||||
r.closeWebhooks()
|
|
||||||
return errors.New("balancer ", btag, " not found")
|
|
||||||
}
|
|
||||||
rr.Balancer = brule
|
|
||||||
}
|
|
||||||
r.rules = append(r.rules, rr)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// PickRoute implements routing.Router.
|
// PickRoute implements routing.Router.
|
||||||
func (r *Router) PickRoute(ctx routing.Context) (routing.Route, error) {
|
func (r *Router) PickRoute(ctx routing.Context) (routing.Route, error) {
|
||||||
|
if r.script != nil {
|
||||||
|
return r.script.pickRoute(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
originalCtx := ctx
|
originalCtx := ctx
|
||||||
rule, ctx, err := r.pickRouteInternal(ctx)
|
rule, ctx, err := r.pickRouteInternal(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -110,7 +76,6 @@ func (r *Router) PickRoute(ctx routing.Context) (routing.Route, error) {
|
|||||||
|
|
||||||
// AddRule implements routing.Router.
|
// AddRule implements routing.Router.
|
||||||
func (r *Router) AddRule(config *serial.TypedMessage, shouldAppend bool) error {
|
func (r *Router) AddRule(config *serial.TypedMessage, shouldAppend bool) error {
|
||||||
|
|
||||||
inst, err := config.GetInstance()
|
inst, err := config.GetInstance()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -125,18 +90,22 @@ func (r *Router) ReloadRules(config *Config, shouldAppend bool) error {
|
|||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
defer r.mu.Unlock()
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
if !shouldAppend {
|
oldRules := *r.rules.Load()
|
||||||
for _, rule := range r.rules {
|
oldBalancers := *r.balancers.Load()
|
||||||
if rule.Webhook != nil {
|
|
||||||
rule.Webhook.Close()
|
var newRules []*Rule
|
||||||
|
newBalancers := make(map[string]*Balancer)
|
||||||
|
existTags := make(map[string]bool, len(oldRules)+len(config.Rule))
|
||||||
|
if shouldAppend {
|
||||||
|
newRules = append(newRules, oldRules...)
|
||||||
|
maps.Copy(newBalancers, oldBalancers)
|
||||||
|
for _, rule := range oldRules {
|
||||||
|
existTags[rule.RuleTag] = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
r.balancers = make(map[string]*Balancer, len(config.BalancingRule))
|
|
||||||
r.rules = make([]*Rule, 0, len(config.Rule))
|
|
||||||
}
|
|
||||||
for _, rule := range config.BalancingRule {
|
for _, rule := range config.BalancingRule {
|
||||||
_, found := r.balancers[rule.Tag]
|
if _, found := newBalancers[rule.Tag]; found {
|
||||||
if found {
|
|
||||||
return errors.New("duplicate balancer tag")
|
return errors.New("duplicate balancer tag")
|
||||||
}
|
}
|
||||||
balancer, err := rule.Build(r.ohm, r.dispatcher)
|
balancer, err := rule.Build(r.ohm, r.dispatcher)
|
||||||
@@ -144,27 +113,12 @@ func (r *Router) ReloadRules(config *Config, shouldAppend bool) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
balancer.InjectContext(r.ctx)
|
balancer.InjectContext(r.ctx)
|
||||||
r.balancers[rule.Tag] = balancer
|
newBalancers[rule.Tag] = balancer
|
||||||
}
|
|
||||||
|
|
||||||
startIdx := len(r.rules)
|
|
||||||
closeNewWebhooks := func() {
|
|
||||||
for i := startIdx; i < len(r.rules); i++ {
|
|
||||||
if r.rules[i].Webhook != nil {
|
|
||||||
r.rules[i].Webhook.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
r.rules = r.rules[:startIdx]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, rule := range config.Rule {
|
for _, rule := range config.Rule {
|
||||||
if r.RuleExists(rule.GetRuleTag()) {
|
|
||||||
closeNewWebhooks()
|
|
||||||
return errors.New("duplicate ruleTag ", rule.GetRuleTag())
|
|
||||||
}
|
|
||||||
cond, err := rule.BuildCondition()
|
cond, err := rule.BuildCondition()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
closeNewWebhooks()
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
rr := &Rule{
|
rr := &Rule{
|
||||||
@@ -172,70 +126,64 @@ func (r *Router) ReloadRules(config *Config, shouldAppend bool) error {
|
|||||||
Tag: rule.GetTag(),
|
Tag: rule.GetTag(),
|
||||||
RuleTag: rule.GetRuleTag(),
|
RuleTag: rule.GetRuleTag(),
|
||||||
}
|
}
|
||||||
|
if rr.RuleTag != "" && existTags[rr.RuleTag] {
|
||||||
|
return errors.New("duplicate ruleTag ", rr.RuleTag)
|
||||||
|
}
|
||||||
|
existTags[rr.RuleTag] = true
|
||||||
if wh := rule.GetWebhook(); wh != nil {
|
if wh := rule.GetWebhook(); wh != nil {
|
||||||
notifier, err := NewWebhookNotifier(wh)
|
notifier, err := NewWebhookNotifier(wh)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
closeNewWebhooks()
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
rr.Webhook = notifier
|
rr.Webhook = notifier
|
||||||
}
|
}
|
||||||
btag := rule.GetBalancingTag()
|
if btag := rule.GetBalancingTag(); len(btag) > 0 {
|
||||||
if len(btag) > 0 {
|
brule, found := newBalancers[btag]
|
||||||
brule, found := r.balancers[btag]
|
|
||||||
if !found {
|
if !found {
|
||||||
if rr.Webhook != nil {
|
|
||||||
rr.Webhook.Close()
|
|
||||||
}
|
|
||||||
closeNewWebhooks()
|
|
||||||
return errors.New("balancer ", btag, " not found")
|
return errors.New("balancer ", btag, " not found")
|
||||||
}
|
}
|
||||||
rr.Balancer = brule
|
rr.Balancer = brule
|
||||||
}
|
}
|
||||||
r.rules = append(r.rules, rr)
|
newRules = append(newRules, rr)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
r.balancers.Store(&newBalancers)
|
||||||
|
r.rules.Store(&newRules)
|
||||||
|
if !shouldAppend {
|
||||||
|
closeWebhooks(oldRules)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Router) RuleExists(tag string) bool {
|
|
||||||
if tag != "" {
|
|
||||||
for _, rule := range r.rules {
|
|
||||||
if rule.RuleTag == tag {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// RemoveRule implements routing.Router.
|
// RemoveRule implements routing.Router.
|
||||||
func (r *Router) RemoveRule(tag string) error {
|
func (r *Router) RemoveRule(tag string) error {
|
||||||
|
if tag == "" {
|
||||||
|
return errors.New("empty tag name!")
|
||||||
|
}
|
||||||
|
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
defer r.mu.Unlock()
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
newRules := []*Rule{}
|
oldRules := *r.rules.Load()
|
||||||
if tag != "" {
|
newRules := make([]*Rule, 0, len(oldRules))
|
||||||
for _, rule := range r.rules {
|
var removed []*Rule
|
||||||
|
for _, rule := range oldRules {
|
||||||
if rule.RuleTag != tag {
|
if rule.RuleTag != tag {
|
||||||
newRules = append(newRules, rule)
|
newRules = append(newRules, rule)
|
||||||
} else if rule.Webhook != nil {
|
} else {
|
||||||
rule.Webhook.Close()
|
removed = append(removed, rule)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
r.rules = newRules
|
r.rules.Store(&newRules)
|
||||||
|
closeWebhooks(removed)
|
||||||
return nil
|
return nil
|
||||||
}
|
|
||||||
return errors.New("empty tag name!")
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListRule implements routing.Router
|
// ListRule implements routing.Router
|
||||||
func (r *Router) ListRule() []routing.Route {
|
func (r *Router) ListRule() []routing.Route {
|
||||||
r.mu.Lock()
|
rules := *r.rules.Load()
|
||||||
defer r.mu.Unlock()
|
ruleList := make([]routing.Route, 0, len(rules))
|
||||||
ruleList := make([]routing.Route, 0)
|
for _, rule := range rules {
|
||||||
for _, rule := range r.rules {
|
|
||||||
ruleList = append(ruleList, &Route{
|
ruleList = append(ruleList, &Route{
|
||||||
outboundTag: rule.Tag,
|
outboundTag: rule.Tag,
|
||||||
ruleTag: rule.RuleTag,
|
ruleTag: rule.RuleTag,
|
||||||
@@ -254,7 +202,9 @@ func (r *Router) pickRouteInternal(ctx routing.Context) (*Rule, routing.Context,
|
|||||||
ctx = routing_dns.ContextWithDNSClient(ctx, r.dns)
|
ctx = routing_dns.ContextWithDNSClient(ctx, r.dns)
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, rule := range r.rules {
|
rules := *r.rules.Load()
|
||||||
|
|
||||||
|
for _, rule := range rules {
|
||||||
if rule.Apply(ctx) {
|
if rule.Apply(ctx) {
|
||||||
return rule, ctx, nil
|
return rule, ctx, nil
|
||||||
}
|
}
|
||||||
@@ -267,7 +217,7 @@ func (r *Router) pickRouteInternal(ctx routing.Context) (*Rule, routing.Context,
|
|||||||
ctx = routing_dns.ContextWithDNSClient(ctx, r.dns)
|
ctx = routing_dns.ContextWithDNSClient(ctx, r.dns)
|
||||||
|
|
||||||
// Try applying rules again if we have IPs.
|
// Try applying rules again if we have IPs.
|
||||||
for _, rule := range r.rules {
|
for _, rule := range rules {
|
||||||
if rule.Apply(ctx) {
|
if rule.Apply(ctx) {
|
||||||
return rule, ctx, nil
|
return rule, ctx, nil
|
||||||
}
|
}
|
||||||
@@ -278,12 +228,19 @@ func (r *Router) pickRouteInternal(ctx routing.Context) (*Rule, routing.Context,
|
|||||||
|
|
||||||
// Start implements common.Runnable.
|
// Start implements common.Runnable.
|
||||||
func (r *Router) Start() error {
|
func (r *Router) Start() error {
|
||||||
|
if r.scriptPath != "" {
|
||||||
|
engine, err := newScriptEngine(r.scriptPath, r)
|
||||||
|
if err != nil {
|
||||||
|
return errors.New("failed to initialize routing script").Base(err)
|
||||||
|
}
|
||||||
|
r.script = engine
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// closeWebhooks closes all webhook notifiers in the current rule set.
|
// closeWebhooks closes all webhook notifiers in the given rule set.
|
||||||
func (r *Router) closeWebhooks() {
|
func closeWebhooks(rules []*Rule) {
|
||||||
for _, rule := range r.rules {
|
for _, rule := range rules {
|
||||||
if rule.Webhook != nil {
|
if rule.Webhook != nil {
|
||||||
rule.Webhook.Close()
|
rule.Webhook.Close()
|
||||||
}
|
}
|
||||||
@@ -292,9 +249,12 @@ func (r *Router) closeWebhooks() {
|
|||||||
|
|
||||||
// Close implements common.Closable.
|
// Close implements common.Closable.
|
||||||
func (r *Router) Close() error {
|
func (r *Router) Close() error {
|
||||||
|
if r.script != nil {
|
||||||
|
r.script.close()
|
||||||
|
}
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
defer r.mu.Unlock()
|
defer r.mu.Unlock()
|
||||||
r.closeWebhooks()
|
closeWebhooks(*r.rules.Load())
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -159,9 +159,8 @@ func TestIPOnDemand(t *testing.T) {
|
|||||||
Ip: []*geodata.IPRule{
|
Ip: []*geodata.IPRule{
|
||||||
{
|
{
|
||||||
Value: &geodata.IPRule_Custom{
|
Value: &geodata.IPRule_Custom{
|
||||||
Custom: &geodata.CIDR{
|
Custom: &geodata.CIDRRule{
|
||||||
Ip: []byte{192, 168, 0, 0},
|
Cidr: &geodata.CIDR{Ip: []byte{192, 168, 0, 0}, Prefix: 16},
|
||||||
Prefix: 16,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -204,9 +203,8 @@ func TestIPIfNonMatchDomain(t *testing.T) {
|
|||||||
Ip: []*geodata.IPRule{
|
Ip: []*geodata.IPRule{
|
||||||
{
|
{
|
||||||
Value: &geodata.IPRule_Custom{
|
Value: &geodata.IPRule_Custom{
|
||||||
Custom: &geodata.CIDR{
|
Custom: &geodata.CIDRRule{
|
||||||
Ip: []byte{192, 168, 0, 0},
|
Cidr: &geodata.CIDR{Ip: []byte{192, 168, 0, 0}, Prefix: 16},
|
||||||
Prefix: 16,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -249,9 +247,8 @@ func TestIPIfNonMatchIP(t *testing.T) {
|
|||||||
Ip: []*geodata.IPRule{
|
Ip: []*geodata.IPRule{
|
||||||
{
|
{
|
||||||
Value: &geodata.IPRule_Custom{
|
Value: &geodata.IPRule_Custom{
|
||||||
Custom: &geodata.CIDR{
|
Custom: &geodata.CIDRRule{
|
||||||
Ip: []byte{127, 0, 0, 0},
|
Cidr: &geodata.CIDR{Ip: []byte{127, 0, 0, 0}, Prefix: 8},
|
||||||
Prefix: 8,
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package router
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/app/dns"
|
||||||
|
"github.com/xtls/xray-core/common"
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
"github.com/xtls/xray-core/common/geodata"
|
||||||
|
"github.com/xtls/xray-core/common/log"
|
||||||
|
luamgr "github.com/xtls/xray-core/common/lua"
|
||||||
|
"github.com/xtls/xray-core/features/routing"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
)
|
||||||
|
|
||||||
|
const scriptExecutionTimeout = 10 * time.Second
|
||||||
|
|
||||||
|
type scriptEngine struct {
|
||||||
|
router *Router
|
||||||
|
pool *luamgr.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newScriptEngine(path string, router *Router) (*scriptEngine, error) {
|
||||||
|
program, err := luamgr.CompileFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
e := &scriptEngine{router: router}
|
||||||
|
e.pool, err = luamgr.NewPool(router.ctx, func(poolCtx context.Context) (*lua.LState, error) {
|
||||||
|
initCtx, cancel := context.WithTimeout(poolCtx, scriptExecutionTimeout)
|
||||||
|
defer cancel()
|
||||||
|
L, err := program.NewState(initCtx, func(L *lua.LState) {
|
||||||
|
geodata.RegisterLua(L)
|
||||||
|
log.RegisterLua(L)
|
||||||
|
router.RegisterLua(L)
|
||||||
|
dns.RegisterLua(L, router.dns)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if L.GetGlobal("HandleRoute").Type() != lua.LTFunction {
|
||||||
|
L.Close()
|
||||||
|
return nil, errors.New("routing script must define HandleRoute(...)")
|
||||||
|
}
|
||||||
|
return L, nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
errors.LogInfo(router.ctx, "routing script initialized from ", path)
|
||||||
|
return e, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *scriptEngine) close() {
|
||||||
|
e.pool.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *scriptEngine) pickRoute(ctx routing.Context) (routing.Route, error) {
|
||||||
|
L, err := e.pool.Acquire()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reusable := false
|
||||||
|
defer func() {
|
||||||
|
e.pool.Release(L, reusable)
|
||||||
|
}()
|
||||||
|
callCtx, cancel := context.WithTimeout(e.pool.Context(), scriptExecutionTimeout)
|
||||||
|
defer cancel()
|
||||||
|
tag, ruleTag, err := e.router.CallLuaHook(L, callCtx, ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
reusable = true
|
||||||
|
if tag == "" {
|
||||||
|
return nil, common.ErrNoClue
|
||||||
|
}
|
||||||
|
return &Route{Context: ctx, outboundTag: tag, ruleTag: ruleTag}, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
package router
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
stdnet "net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
wireDNS "github.com/miekg/dns"
|
||||||
|
"github.com/xtls/xray-core/app/dispatcher"
|
||||||
|
appdns "github.com/xtls/xray-core/app/dns"
|
||||||
|
"github.com/xtls/xray-core/app/proxyman"
|
||||||
|
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||||
|
"github.com/xtls/xray-core/common"
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
"github.com/xtls/xray-core/common/serial"
|
||||||
|
"github.com/xtls/xray-core/core"
|
||||||
|
featureDNS "github.com/xtls/xray-core/features/dns"
|
||||||
|
"github.com/xtls/xray-core/features/outbound"
|
||||||
|
"github.com/xtls/xray-core/features/routing"
|
||||||
|
routing_session "github.com/xtls/xray-core/features/routing/session"
|
||||||
|
"github.com/xtls/xray-core/proxy/blackhole"
|
||||||
|
"github.com/xtls/xray-core/proxy/freedom"
|
||||||
|
)
|
||||||
|
|
||||||
|
type luaRouteDNSClient struct {
|
||||||
|
featureDNS.Client
|
||||||
|
lookup func(string, featureDNS.IPOption) ([]net.IP, uint32, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *luaRouteDNSClient) LookupIP(domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
return d.lookup(domain, option)
|
||||||
|
}
|
||||||
|
|
||||||
|
type luaRouteOutboundManager struct{ outbound.Manager }
|
||||||
|
|
||||||
|
func (*luaRouteOutboundManager) Select(selectors []string) []string { return selectors }
|
||||||
|
|
||||||
|
func writeRouteScript(t *testing.T, script string) string {
|
||||||
|
t.Helper()
|
||||||
|
path := filepath.Join(t.TempDir(), "route.lua")
|
||||||
|
if err := os.WriteFile(path, []byte(script), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
|
||||||
|
func startLuaRouter(t *testing.T, script string, d featureDNS.Client, config *Config) *Router {
|
||||||
|
t.Helper()
|
||||||
|
if config == nil {
|
||||||
|
config = &Config{}
|
||||||
|
}
|
||||||
|
config.Script = writeRouteScript(t, script)
|
||||||
|
r := new(Router)
|
||||||
|
if err := r.Init(context.Background(), config, d, &luaRouteOutboundManager{}, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.Start(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
if err := r.Close(); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterScriptStartup(t *testing.T) {
|
||||||
|
for _, tc := range []struct{ name, script string }{
|
||||||
|
{"syntax error", "function HandleRoute("},
|
||||||
|
{"missing hook", "value = 1"},
|
||||||
|
{"initialization error", `error("setup failed")`},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
r := new(Router)
|
||||||
|
if err := r.Init(context.Background(), &Config{Script: writeRouteScript(t, tc.script)}, nil, nil, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer r.Close()
|
||||||
|
if err := r.Start(); err == nil {
|
||||||
|
t.Fatal("Start accepted an invalid routing script")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterScriptRouting(t *testing.T) {
|
||||||
|
var dnsCalls atomic.Int32
|
||||||
|
d := &luaRouteDNSClient{lookup: func(string, featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
dnsCalls.Add(1)
|
||||||
|
return []net.IP{{1, 2, 3, 4}}, 60, nil
|
||||||
|
}}
|
||||||
|
r := startLuaRouter(t, `
|
||||||
|
function HandleRoute(ctx, inbound)
|
||||||
|
if inbound == "miss" then return nil end
|
||||||
|
return "lua-out", "lua-rule"
|
||||||
|
end`, d, &Config{
|
||||||
|
DomainStrategy: Config_IpOnDemand,
|
||||||
|
Rule: []*RoutingRule{{
|
||||||
|
TargetTag: &RoutingRule_Tag{Tag: "json-out"},
|
||||||
|
Networks: []net.Network{net.Network_TCP},
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
ctx := newLuaRouteTestContext()
|
||||||
|
ctx.Content.SkipDNSResolve = false
|
||||||
|
route, err := r.PickRoute(ctx)
|
||||||
|
if err != nil || route.GetOutboundTag() != "lua-out" || route.GetRuleTag() != "lua-rule" || route.(*Route).Context != ctx {
|
||||||
|
t.Fatalf("route = %v, %v", route, err)
|
||||||
|
}
|
||||||
|
ctx.Inbound.Tag = "miss"
|
||||||
|
if route, err := r.PickRoute(ctx); route != nil || err != common.ErrNoClue {
|
||||||
|
t.Fatalf("miss = %v, %v", route, err)
|
||||||
|
}
|
||||||
|
if dnsCalls.Load() != 0 {
|
||||||
|
t.Fatal("script routing implicitly resolved DNS")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterScriptModules(t *testing.T) {
|
||||||
|
ips := []net.IP{{127, 0, 0, 7}}
|
||||||
|
calls := 0
|
||||||
|
d := &luaRouteDNSClient{lookup: func(domain string, option featureDNS.IPOption) ([]net.IP, uint32, error) {
|
||||||
|
calls++
|
||||||
|
if domain != "MiXeD.Example." || !option.IPv4Enable || option.IPv6Enable || !option.FakeEnable {
|
||||||
|
t.Fatalf("dns.Query arguments = %q, %+v", domain, option)
|
||||||
|
}
|
||||||
|
return ips, 17, nil
|
||||||
|
}}
|
||||||
|
r := startLuaRouter(t, `
|
||||||
|
local dns = require("xray.dns")
|
||||||
|
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.0/8")
|
||||||
|
assert(dns.Servers == nil and type(dns.Query) == "function")
|
||||||
|
assert(type(require("xray.log").Info) == "function")
|
||||||
|
function HandleRoute(ctx, inbound, sourcePort, targetPort, localPort, domain)
|
||||||
|
local ips, ttl, err = dns.Query(domain, true, false, true)
|
||||||
|
assert(not err and ttl == 17)
|
||||||
|
assert(matcher:AnyMatch(ips) and matcher:AnyMatch(ctx:GetTargetIPs()))
|
||||||
|
return "out"
|
||||||
|
end`, d, nil)
|
||||||
|
if _, err := r.PickRoute(newLuaRouteTestContext()); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if calls != 1 {
|
||||||
|
t.Fatalf("DNS calls = %d, want 1", calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterScriptBalancerReload(t *testing.T) {
|
||||||
|
config := func(tag string) *Config {
|
||||||
|
return &Config{BalancingRule: []*BalancingRule{{
|
||||||
|
Tag: "balance", Strategy: "roundrobin", OutboundSelector: []string{tag},
|
||||||
|
}}}
|
||||||
|
}
|
||||||
|
r := startLuaRouter(t, `
|
||||||
|
local router = require("xray.router")
|
||||||
|
function HandleRoute()
|
||||||
|
local tag, err = router:PickOutbound("balance")
|
||||||
|
return tag, "balanced", err
|
||||||
|
end`, nil, config("old"))
|
||||||
|
pick := func(want string) {
|
||||||
|
t.Helper()
|
||||||
|
route, err := r.PickRoute(&routing_session.Context{})
|
||||||
|
if err != nil || route.GetOutboundTag() != want || route.GetRuleTag() != "balanced" {
|
||||||
|
t.Fatalf("route = %v, %v, want %q", route, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pick("old")
|
||||||
|
if err := r.SetOverrideTarget("balance", "override"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
pick("override")
|
||||||
|
if err := r.SetOverrideTarget("balance", ""); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := r.ReloadRules(config("new"), false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
pick("new")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterScriptConcurrentBalancerReload(t *testing.T) {
|
||||||
|
config := func(tag string) *Config {
|
||||||
|
return &Config{BalancingRule: []*BalancingRule{{
|
||||||
|
Tag: "balance", Strategy: "roundrobin", OutboundSelector: []string{tag},
|
||||||
|
}}}
|
||||||
|
}
|
||||||
|
r := startLuaRouter(t, `
|
||||||
|
local router = require("xray.router")
|
||||||
|
function HandleRoute()
|
||||||
|
local tag, err = router:PickOutbound("balance")
|
||||||
|
return tag, nil, err
|
||||||
|
end`, nil, config("a"))
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for range 4 {
|
||||||
|
wg.Go(func() {
|
||||||
|
for range 20 {
|
||||||
|
route, err := r.PickRoute(&routing_session.Context{})
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("PickRoute: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tag := route.GetOutboundTag(); tag != "a" && tag != "b" {
|
||||||
|
t.Errorf("unexpected tag %q", tag)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
wg.Go(func() {
|
||||||
|
for range 20 {
|
||||||
|
for _, tag := range []string{"a", "b"} {
|
||||||
|
if err := r.ReloadRules(config(tag), false); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterScriptStateReuse(t *testing.T) {
|
||||||
|
r := startLuaRouter(t, `
|
||||||
|
local calls = 0
|
||||||
|
function HandleRoute(ctx, inbound)
|
||||||
|
calls = calls + 1
|
||||||
|
if inbound == "miss" then return nil end
|
||||||
|
if inbound == "fail" then error("failed") end
|
||||||
|
return tostring(calls)
|
||||||
|
end`, nil, nil)
|
||||||
|
ctx := newLuaRouteTestContext()
|
||||||
|
pick := func(want string) {
|
||||||
|
t.Helper()
|
||||||
|
route, err := r.PickRoute(ctx)
|
||||||
|
if err != nil || route.GetOutboundTag() != want {
|
||||||
|
t.Fatalf("route = %v, %v, want %q", route, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pick("1")
|
||||||
|
ctx.Inbound.Tag = "miss"
|
||||||
|
if _, err := r.PickRoute(ctx); err != common.ErrNoClue {
|
||||||
|
t.Fatalf("miss = %v", err)
|
||||||
|
}
|
||||||
|
ctx.Inbound.Tag = "in"
|
||||||
|
pick("3")
|
||||||
|
ctx.Inbound.Tag = "fail"
|
||||||
|
if _, err := r.PickRoute(ctx); err == nil {
|
||||||
|
t.Fatal("script error was ignored")
|
||||||
|
}
|
||||||
|
ctx.Inbound.Tag = "in"
|
||||||
|
pick("1")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRouterScriptDNSDispatcherReentry(t *testing.T) {
|
||||||
|
conn, err := stdnet.ListenPacket("udp4", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
port := conn.LocalAddr().(*stdnet.UDPAddr).Port
|
||||||
|
ready, stopped := make(chan struct{}), make(chan error, 1)
|
||||||
|
var queries atomic.Int32
|
||||||
|
server := &wireDNS.Server{
|
||||||
|
PacketConn: conn,
|
||||||
|
NotifyStartedFunc: func() {
|
||||||
|
close(ready)
|
||||||
|
},
|
||||||
|
Handler: wireDNS.HandlerFunc(func(w wireDNS.ResponseWriter, query *wireDNS.Msg) {
|
||||||
|
queries.Add(1)
|
||||||
|
response := new(wireDNS.Msg).SetReply(query)
|
||||||
|
for _, question := range query.Question {
|
||||||
|
if question.Name == "nested.example." && question.Qtype == wireDNS.TypeA {
|
||||||
|
response.Answer = append(response.Answer, &wireDNS.A{
|
||||||
|
Hdr: wireDNS.RR_Header{Name: question.Name, Rrtype: wireDNS.TypeA, Class: wireDNS.ClassINET, Ttl: 60},
|
||||||
|
A: stdnet.IP{127, 0, 0, 7},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := w.WriteMsg(response); err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
go func() { stopped <- server.ActivateAndServe() }()
|
||||||
|
defer func() {
|
||||||
|
server.Shutdown()
|
||||||
|
select {
|
||||||
|
case err := <-stopped:
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Error("DNS server did not stop")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case <-ready:
|
||||||
|
case err := <-stopped:
|
||||||
|
t.Fatalf("DNS server startup: %v", err)
|
||||||
|
case <-time.After(3 * time.Second):
|
||||||
|
t.Fatal("DNS server did not start")
|
||||||
|
}
|
||||||
|
|
||||||
|
dnsScript := writeRouteScript(t, `
|
||||||
|
local server = require("xray.dns").Servers[1]
|
||||||
|
function HandleDNSQuery(domain, ipv4, ipv6, fake)
|
||||||
|
return server:Query(domain, ipv4, ipv6, fake)
|
||||||
|
end`)
|
||||||
|
routerScript := writeRouteScript(t, `
|
||||||
|
local router = require("xray.router")
|
||||||
|
local dns = require("xray.dns")
|
||||||
|
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.7")
|
||||||
|
local active = false
|
||||||
|
function HandleRoute(ctx, inbound, sourcePort, targetPort, localPort, domain, network,
|
||||||
|
protocol, user, vlessRoute, skipDNSResolve)
|
||||||
|
assert(not active, "borrowed Router VM reentered")
|
||||||
|
if inbound == "dns" then
|
||||||
|
assert(network == router.NetworkUDP and skipDNSResolve == false)
|
||||||
|
return "direct", "dns-route"
|
||||||
|
end
|
||||||
|
active = true
|
||||||
|
local ips, ttl, err = dns.Query("nested.example", true, false, false)
|
||||||
|
assert(not err and matcher:AnyMatch(ips) and active)
|
||||||
|
active = false
|
||||||
|
return "direct", "outer-route"
|
||||||
|
end`)
|
||||||
|
instance, err := core.New(&core.Config{
|
||||||
|
App: []*serial.TypedMessage{
|
||||||
|
serial.ToTypedMessage(&appdns.Config{
|
||||||
|
Tag: "dns", Script: dnsScript, DisableCache: true,
|
||||||
|
NameServer: []*appdns.NameServer{{
|
||||||
|
Id: "upstream", TimeoutMs: 1000,
|
||||||
|
Address: &net.Endpoint{
|
||||||
|
Network: net.Network_UDP,
|
||||||
|
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: []byte{127, 0, 0, 1}}},
|
||||||
|
Port: uint32(port),
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
}),
|
||||||
|
serial.ToTypedMessage(&Config{Script: routerScript}),
|
||||||
|
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||||
|
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||||
|
},
|
||||||
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
|
{Tag: "default", ProxySettings: serial.ToTypedMessage(&blackhole.Config{})},
|
||||||
|
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{
|
||||||
|
FinalRules: []*freedom.FinalRuleConfig{{Action: freedom.RuleAction_Allow}},
|
||||||
|
})},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer instance.Close()
|
||||||
|
if err := instance.Start(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r := instance.GetFeature(routing.RouterType()).(*Router)
|
||||||
|
route, err := r.PickRoute(newLuaRouteTestContext())
|
||||||
|
if err != nil || route.GetOutboundTag() != "direct" || route.GetRuleTag() != "outer-route" {
|
||||||
|
t.Fatalf("nested DNS routing = %v, %v", route, err)
|
||||||
|
}
|
||||||
|
if queries.Load() == 0 {
|
||||||
|
t.Fatal("DNS query did not pass through the dispatcher")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package router
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"math"
|
"math"
|
||||||
|
"slices"
|
||||||
"sort"
|
"sort"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -77,7 +78,7 @@ func (s *LeastLoadStrategy) PickOutbound(candidates []string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *LeastLoadStrategy) pickOutbounds(candidates []string) []*node {
|
func (s *LeastLoadStrategy) pickOutbounds(candidates []string) []*node {
|
||||||
qualified := s.getNodes(candidates, time.Duration(s.settings.MaxRTT))
|
qualified := s.getNodes(candidates)
|
||||||
selects := s.selectLeastLoad(qualified)
|
selects := s.selectLeastLoad(qualified)
|
||||||
return selects
|
return selects
|
||||||
}
|
}
|
||||||
@@ -138,7 +139,7 @@ func (s *LeastLoadStrategy) selectLeastLoad(nodes []*node) []*node {
|
|||||||
return nodes[:count]
|
return nodes[:count]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *LeastLoadStrategy) getNodes(candidates []string, maxRTT time.Duration) []*node {
|
func (s *LeastLoadStrategy) getNodes(candidates []string) []*node {
|
||||||
if s.observer == nil {
|
if s.observer == nil {
|
||||||
errors.LogError(s.ctx, "observer is nil")
|
errors.LogError(s.ctx, "observer is nil")
|
||||||
return make([]*node, 0)
|
return make([]*node, 0)
|
||||||
@@ -151,12 +152,10 @@ func (s *LeastLoadStrategy) getNodes(candidates []string, maxRTT time.Duration)
|
|||||||
|
|
||||||
results := observeResult.(*observatory.ObservationResult)
|
results := observeResult.(*observatory.ObservationResult)
|
||||||
|
|
||||||
outboundlist := outboundList(candidates)
|
|
||||||
|
|
||||||
var ret []*node
|
var ret []*node
|
||||||
|
|
||||||
for _, v := range results.Status {
|
for _, v := range results.Status {
|
||||||
if v.Alive && (v.Delay < maxRTT.Milliseconds() || maxRTT == 0) && outboundlist.contains(v.OutboundTag) {
|
if s.shouldSelectNode(v, candidates) {
|
||||||
record := &node{
|
record := &node{
|
||||||
Tag: v.OutboundTag,
|
Tag: v.OutboundTag,
|
||||||
CountAll: 1,
|
CountAll: 1,
|
||||||
@@ -172,8 +171,8 @@ func (s *LeastLoadStrategy) getNodes(candidates []string, maxRTT time.Duration)
|
|||||||
record.RTTDeviationCost = time.Duration(s.costs.Apply(v.OutboundTag, float64(v.HealthPing.Deviation)))
|
record.RTTDeviationCost = time.Duration(s.costs.Apply(v.OutboundTag, float64(v.HealthPing.Deviation)))
|
||||||
record.CountAll = int(v.HealthPing.All)
|
record.CountAll = int(v.HealthPing.All)
|
||||||
record.CountFail = int(v.HealthPing.Fail)
|
record.CountFail = int(v.HealthPing.Fail)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ret = append(ret, record)
|
ret = append(ret, record)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,6 +181,23 @@ func (s *LeastLoadStrategy) getNodes(candidates []string, maxRTT time.Duration)
|
|||||||
return ret
|
return ret
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *LeastLoadStrategy) shouldSelectNode(v *observatory.OutboundStatus, candidates []string) bool {
|
||||||
|
maxRTT := time.Duration(s.settings.MaxRTT)
|
||||||
|
if !v.Alive {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if maxRTT != 0 && v.Delay >= maxRTT.Milliseconds() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !slices.Contains(candidates, v.OutboundTag) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if v.HealthPing != nil && v.HealthPing.All > 0 && s.settings.Tolerance > 0 && float64(v.HealthPing.Fail)/float64(v.HealthPing.All) > float64(s.settings.Tolerance) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func leastloadSort(nodes []*node) {
|
func leastloadSort(nodes []*node) {
|
||||||
sort.Slice(nodes, func(i, j int) bool {
|
sort.Slice(nodes, func(i, j int) bool {
|
||||||
left := nodes[i]
|
left := nodes[i]
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ func TestSelectLeastExpected(t *testing.T) {
|
|||||||
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSelectLeastExpected2(t *testing.T) {
|
func TestSelectLeastExpected2(t *testing.T) {
|
||||||
strategy := &LeastLoadStrategy{
|
strategy := &LeastLoadStrategy{
|
||||||
settings: &StrategyLeastLoadConfig{
|
settings: &StrategyLeastLoadConfig{
|
||||||
@@ -102,6 +103,7 @@ func TestSelectLeastExpected2(t *testing.T) {
|
|||||||
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSelectLeastExpectedAndBaselines(t *testing.T) {
|
func TestSelectLeastExpectedAndBaselines(t *testing.T) {
|
||||||
strategy := &LeastLoadStrategy{
|
strategy := &LeastLoadStrategy{
|
||||||
settings: &StrategyLeastLoadConfig{
|
settings: &StrategyLeastLoadConfig{
|
||||||
@@ -122,6 +124,7 @@ func TestSelectLeastExpectedAndBaselines(t *testing.T) {
|
|||||||
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSelectLeastExpectedAndBaselines2(t *testing.T) {
|
func TestSelectLeastExpectedAndBaselines2(t *testing.T) {
|
||||||
strategy := &LeastLoadStrategy{
|
strategy := &LeastLoadStrategy{
|
||||||
settings: &StrategyLeastLoadConfig{
|
settings: &StrategyLeastLoadConfig{
|
||||||
@@ -142,6 +145,7 @@ func TestSelectLeastExpectedAndBaselines2(t *testing.T) {
|
|||||||
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSelectLeastLoadBaselines(t *testing.T) {
|
func TestSelectLeastLoadBaselines(t *testing.T) {
|
||||||
strategy := &LeastLoadStrategy{
|
strategy := &LeastLoadStrategy{
|
||||||
settings: &StrategyLeastLoadConfig{
|
settings: &StrategyLeastLoadConfig{
|
||||||
@@ -160,6 +164,7 @@ func TestSelectLeastLoadBaselines(t *testing.T) {
|
|||||||
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
t.Errorf("expected: %v, actual: %v", expected, len(ns))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSelectLeastLoadBaselinesNoQualified(t *testing.T) {
|
func TestSelectLeastLoadBaselinesNoQualified(t *testing.T) {
|
||||||
strategy := &LeastLoadStrategy{
|
strategy := &LeastLoadStrategy{
|
||||||
settings: &StrategyLeastLoadConfig{
|
settings: &StrategyLeastLoadConfig{
|
||||||
|
|||||||
+14
-66
@@ -7,61 +7,16 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
"sync"
|
||||||
"syscall"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
"github.com/xtls/xray-core/common/utils"
|
||||||
"github.com/xtls/xray-core/features/routing"
|
"github.com/xtls/xray-core/features/routing"
|
||||||
routing_session "github.com/xtls/xray-core/features/routing/session"
|
routing_session "github.com/xtls/xray-core/features/routing/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
// parseURL splits a webhook URL into an HTTP URL and an optional Unix socket
|
|
||||||
// path. For regular http/https URLs the input is returned unchanged with an
|
|
||||||
// empty socketPath. For Unix sockets the format is:
|
|
||||||
//
|
|
||||||
// /path/to/socket.sock:/http/path
|
|
||||||
// @abstract:/http/path
|
|
||||||
// @@padded:/http/path
|
|
||||||
//
|
|
||||||
// The :/ separator after the socket path delimits the HTTP request path.
|
|
||||||
// If omitted, "/" is used.
|
|
||||||
func parseURL(raw string) (httpURL, socketPath string) {
|
|
||||||
if len(raw) == 0 || (!filepath.IsAbs(raw) && raw[0] != '@') {
|
|
||||||
return raw, ""
|
|
||||||
}
|
|
||||||
if idx := strings.Index(raw, ":/"); idx >= 0 {
|
|
||||||
return "http://localhost" + raw[idx+1:], raw[:idx]
|
|
||||||
}
|
|
||||||
return "http://localhost/", raw
|
|
||||||
}
|
|
||||||
|
|
||||||
// resolveSocketPath applies platform-specific transformations to a Unix
|
|
||||||
// socket path, matching the behaviour of the listen side in
|
|
||||||
// transport/internet/system_listener.go.
|
|
||||||
//
|
|
||||||
// For abstract sockets (prefix @) on Linux/Android:
|
|
||||||
// - single @ — used as-is (lock-free abstract socket)
|
|
||||||
// - double @@ — stripped to single @ and padded to
|
|
||||||
// syscall.RawSockaddrUnix{}.Path length (HAProxy compat)
|
|
||||||
func resolveSocketPath(path string) string {
|
|
||||||
if len(path) == 0 || path[0] != '@' {
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
if runtime.GOOS != "linux" && runtime.GOOS != "android" {
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
if len(path) > 1 && path[1] == '@' {
|
|
||||||
fullAddr := make([]byte, len(syscall.RawSockaddrUnix{}.Path))
|
|
||||||
copy(fullAddr, path[1:])
|
|
||||||
return string(fullAddr)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
func ptr[T any](v T) *T { return &v }
|
func ptr[T any](v T) *T { return &v }
|
||||||
|
|
||||||
type event struct {
|
type event struct {
|
||||||
@@ -86,6 +41,7 @@ type WebhookNotifier struct {
|
|||||||
deduplication uint32
|
deduplication uint32
|
||||||
client *http.Client
|
client *http.Client
|
||||||
seen sync.Map
|
seen sync.Map
|
||||||
|
lastSweep atomic.Int64
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
wg sync.WaitGroup
|
wg sync.WaitGroup
|
||||||
closeOnce sync.Once
|
closeOnce sync.Once
|
||||||
@@ -96,7 +52,7 @@ func NewWebhookNotifier(cfg *WebhookConfig) (*WebhookNotifier, error) {
|
|||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
httpURL, socketPath := parseURL(cfg.Url)
|
httpURL, socketPath := utils.SplitHTTPUnixURL(cfg.Url)
|
||||||
h := &WebhookNotifier{
|
h := &WebhookNotifier{
|
||||||
url: httpURL,
|
url: httpURL,
|
||||||
deduplication: cfg.Deduplication,
|
deduplication: cfg.Deduplication,
|
||||||
@@ -107,7 +63,7 @@ func NewWebhookNotifier(cfg *WebhookConfig) (*WebhookNotifier, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if socketPath != "" {
|
if socketPath != "" {
|
||||||
dialAddr := resolveSocketPath(socketPath)
|
dialAddr := utils.ResolveSocketPath(socketPath)
|
||||||
h.client.Transport = &http.Transport{
|
h.client.Transport = &http.Transport{
|
||||||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||||
var d net.Dialer
|
var d net.Dialer
|
||||||
@@ -123,11 +79,6 @@ func NewWebhookNotifier(cfg *WebhookConfig) (*WebhookNotifier, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if h.deduplication > 0 {
|
|
||||||
h.wg.Add(1)
|
|
||||||
go h.cleanupLoop()
|
|
||||||
}
|
|
||||||
|
|
||||||
return h, nil
|
return h, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,6 +198,7 @@ func (h *WebhookNotifier) isDuplicate(email string) bool {
|
|||||||
}
|
}
|
||||||
ttl := time.Duration(h.deduplication) * time.Second
|
ttl := time.Duration(h.deduplication) * time.Second
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
h.maybeSweep(now, ttl)
|
||||||
if v, loaded := h.seen.LoadOrStore(email, now); loaded {
|
if v, loaded := h.seen.LoadOrStore(email, now); loaded {
|
||||||
if now.Sub(v.(time.Time)) < ttl {
|
if now.Sub(v.(time.Time)) < ttl {
|
||||||
return true
|
return true
|
||||||
@@ -256,27 +208,23 @@ func (h *WebhookNotifier) isDuplicate(email string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *WebhookNotifier) cleanupLoop() {
|
func (h *WebhookNotifier) maybeSweep(now time.Time, ttl time.Duration) {
|
||||||
defer h.wg.Done()
|
last := h.lastSweep.Load()
|
||||||
ttl := time.Duration(h.deduplication) * time.Second
|
if now.UnixNano()-last < int64(ttl) {
|
||||||
ticker := time.NewTicker(ttl)
|
|
||||||
defer ticker.Stop()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-h.done:
|
|
||||||
return
|
return
|
||||||
case <-ticker.C:
|
}
|
||||||
now := time.Now()
|
if !h.lastSweep.CompareAndSwap(last, now.UnixNano()) {
|
||||||
|
return // another goroutine did the sweep
|
||||||
|
}
|
||||||
h.seen.Range(func(key, value any) bool {
|
h.seen.Range(func(key, value any) bool {
|
||||||
if now.Sub(value.(time.Time)) >= ttl {
|
if now.Sub(value.(time.Time)) >= ttl {
|
||||||
h.seen.Delete(key)
|
h.seen.Delete(key)
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Only need to call if the Notifier is really used, otherwise GC can clean it
|
||||||
func (h *WebhookNotifier) Close() error {
|
func (h *WebhookNotifier) Close() error {
|
||||||
h.closeOnce.Do(func() {
|
h.closeOnce.Do(func() {
|
||||||
close(h.done)
|
close(h.done)
|
||||||
|
|||||||
@@ -48,6 +48,20 @@ func (m *Manager) RegisterCounter(name string) (stats.Counter, error) {
|
|||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetOrRegisterCounter implements stats.Manager.
|
||||||
|
func (m *Manager) GetOrRegisterCounter(name string) (stats.Counter, error) {
|
||||||
|
m.access.Lock()
|
||||||
|
defer m.access.Unlock()
|
||||||
|
|
||||||
|
if c, found := m.counters[name]; found {
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
errors.LogDebug(context.Background(), "create new counter ", name)
|
||||||
|
c := new(Counter)
|
||||||
|
m.counters[name] = c
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
// UnregisterCounter implements stats.Manager.
|
// UnregisterCounter implements stats.Manager.
|
||||||
func (m *Manager) UnregisterCounter(name string) error {
|
func (m *Manager) UnregisterCounter(name string) error {
|
||||||
m.access.Lock()
|
m.access.Lock()
|
||||||
@@ -97,6 +111,20 @@ func (m *Manager) RegisterOnlineMap(name string) (stats.OnlineMap, error) {
|
|||||||
return om, nil
|
return om, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetOrRegisterOnlineMap implements stats.Manager.
|
||||||
|
func (m *Manager) GetOrRegisterOnlineMap(name string) (stats.OnlineMap, error) {
|
||||||
|
m.access.Lock()
|
||||||
|
defer m.access.Unlock()
|
||||||
|
|
||||||
|
if om, found := m.onlineMaps[name]; found {
|
||||||
|
return om, nil
|
||||||
|
}
|
||||||
|
errors.LogDebug(context.Background(), "create new OnlineMap ", name)
|
||||||
|
om := NewOnlineMap()
|
||||||
|
m.onlineMaps[name] = om
|
||||||
|
return om, nil
|
||||||
|
}
|
||||||
|
|
||||||
// UnregisterOnlineMap implements stats.Manager.
|
// UnregisterOnlineMap implements stats.Manager.
|
||||||
func (m *Manager) UnregisterOnlineMap(name string) error {
|
func (m *Manager) UnregisterOnlineMap(name string) error {
|
||||||
m.access.Lock()
|
m.access.Lock()
|
||||||
@@ -149,6 +177,26 @@ func (m *Manager) RegisterChannel(name string) (stats.Channel, error) {
|
|||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetOrRegisterChannel implements stats.Manager.
|
||||||
|
func (m *Manager) GetOrRegisterChannel(name string) (stats.Channel, error) {
|
||||||
|
m.access.Lock()
|
||||||
|
defer m.access.Unlock()
|
||||||
|
|
||||||
|
if c, found := m.channels[name]; found {
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
errors.LogDebug(context.Background(), "create new channel ", name)
|
||||||
|
c := NewChannel(&ChannelConfig{BufferSize: 64, Blocking: false})
|
||||||
|
if m.running {
|
||||||
|
// Start before publishing so no goroutine can observe an unstarted channel.
|
||||||
|
if err := c.Start(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m.channels[name] = c
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
// UnregisterChannel implements stats.Manager.
|
// UnregisterChannel implements stats.Manager.
|
||||||
func (m *Manager) UnregisterChannel(name string) error {
|
func (m *Manager) UnregisterChannel(name string) error {
|
||||||
m.access.Lock()
|
m.access.Lock()
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func TestInterface(t *testing.T) {
|
func TestInterface(t *testing.T) {
|
||||||
_ = (stats.Manager)(new(Manager))
|
_ = stats.Manager(new(Manager))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStatsChannelRunnable(t *testing.T) {
|
func TestStatsChannelRunnable(t *testing.T) {
|
||||||
|
|||||||
@@ -2,10 +2,11 @@ package version
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"github.com/xtls/xray-core/common"
|
|
||||||
"github.com/xtls/xray-core/common/errors"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common"
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Version struct {
|
type Version struct {
|
||||||
|
|||||||
+1
-1
@@ -122,7 +122,7 @@ func NewReader(reader io.Reader) Reader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_, isFile := reader.(*os.File)
|
_, isFile := reader.(*os.File)
|
||||||
if !isFile && useReadv {
|
if !isFile && useReadV() {
|
||||||
if sc, ok := reader.(syscall.Conn); ok {
|
if sc, ok := reader.(syscall.Conn); ok {
|
||||||
rawConn, err := sc.SyscallConn()
|
rawConn, err := sc.SyscallConn()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ func MergeMulti(dest MultiBuffer, src MultiBuffer) (MultiBuffer, MultiBuffer) {
|
|||||||
// MergeBytes merges the given bytes into MultiBuffer and return the new address of the merged MultiBuffer.
|
// MergeBytes merges the given bytes into MultiBuffer and return the new address of the merged MultiBuffer.
|
||||||
func MergeBytes(dest MultiBuffer, src []byte) MultiBuffer {
|
func MergeBytes(dest MultiBuffer, src []byte) MultiBuffer {
|
||||||
n := len(dest)
|
n := len(dest)
|
||||||
if n > 0 && !(dest)[n-1].IsFull() {
|
if n > 0 && !dest[n-1].IsFull() {
|
||||||
nBytes, _ := (dest)[n-1].Write(src)
|
nBytes, _ := dest[n-1].Write(src)
|
||||||
src = src[nBytes:]
|
src = src[nBytes:]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -121,11 +121,11 @@ func TestPacketReader_ReadMultiBuffer(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestReaderInterface(t *testing.T) {
|
func TestReaderInterface(t *testing.T) {
|
||||||
_ = (io.Reader)(new(ReadVReader))
|
_ = io.Reader(new(ReadVReader))
|
||||||
_ = (Reader)(new(ReadVReader))
|
_ = Reader(new(ReadVReader))
|
||||||
|
|
||||||
_ = (Reader)(new(BufferedReader))
|
_ = Reader(new(BufferedReader))
|
||||||
_ = (io.Reader)(new(BufferedReader))
|
_ = io.Reader(new(BufferedReader))
|
||||||
_ = (io.ByteReader)(new(BufferedReader))
|
_ = io.ByteReader(new(BufferedReader))
|
||||||
_ = (io.WriterTo)(new(BufferedReader))
|
_ = io.WriterTo(new(BufferedReader))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ func (r *posixReader) Init(bs []*Buffer) {
|
|||||||
}
|
}
|
||||||
for idx, b := range bs {
|
for idx, b := range bs {
|
||||||
iovecs = append(iovecs, syscall.Iovec{
|
iovecs = append(iovecs, syscall.Iovec{
|
||||||
Base: &(b.v[0]),
|
Base: &b.v[0],
|
||||||
})
|
})
|
||||||
iovecs[idx].SetLen(int(Size))
|
iovecs[idx].SetLen(int(Size))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ package buf
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"io"
|
"io"
|
||||||
|
"sync/atomic"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/platform"
|
"github.com/xtls/xray-core/common/platform"
|
||||||
@@ -143,13 +144,24 @@ func (r *ReadVReader) ReadMultiBuffer() (MultiBuffer, error) {
|
|||||||
return mb, nil
|
return mb, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var useReadv bool
|
var useReadv atomic.Bool
|
||||||
|
|
||||||
func init() {
|
func useReadV() bool {
|
||||||
|
return useReadv.Load()
|
||||||
|
}
|
||||||
|
|
||||||
|
func reloadEnvSettings() error {
|
||||||
const defaultFlagValue = "NOT_DEFINED_AT_ALL"
|
const defaultFlagValue = "NOT_DEFINED_AT_ALL"
|
||||||
value := platform.NewEnvFlag(platform.UseReadV).GetValue(func() string { return defaultFlagValue })
|
value := platform.NewEnvFlag(platform.UseReadV).GetValue(func() string { return defaultFlagValue })
|
||||||
|
enabled := false
|
||||||
switch value {
|
switch value {
|
||||||
case defaultFlagValue, "auto", "enable":
|
case defaultFlagValue, "auto", "enable":
|
||||||
useReadv = true
|
enabled = true
|
||||||
}
|
}
|
||||||
|
useReadv.Store(enabled)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
platform.RegisterEnvReload(reloadEnvSettings)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,9 @@ import (
|
|||||||
"github.com/xtls/xray-core/features/stats"
|
"github.com/xtls/xray-core/features/stats"
|
||||||
)
|
)
|
||||||
|
|
||||||
const useReadv = false
|
func useReadV() bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func NewReadVReader(reader io.Reader, rawConn syscall.RawConn, counter stats.Counter) Reader {
|
func NewReadVReader(reader io.Reader, rawConn syscall.RawConn, counter stats.Counter) Reader {
|
||||||
panic("not implemented")
|
panic("not implemented")
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
|
|
||||||
type windowsReader struct {
|
type windowsReader struct {
|
||||||
bufs []syscall.WSABuf
|
bufs []syscall.WSABuf
|
||||||
|
ready bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *windowsReader) Init(bs []*Buffer) {
|
func (r *windowsReader) Init(bs []*Buffer) {
|
||||||
@@ -15,6 +16,7 @@ func (r *windowsReader) Init(bs []*Buffer) {
|
|||||||
for _, b := range bs {
|
for _, b := range bs {
|
||||||
r.bufs = append(r.bufs, syscall.WSABuf{Len: uint32(Size), Buf: &b.v[0]})
|
r.bufs = append(r.bufs, syscall.WSABuf{Len: uint32(Size), Buf: &b.v[0]})
|
||||||
}
|
}
|
||||||
|
r.ready = false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *windowsReader) Clear() {
|
func (r *windowsReader) Clear() {
|
||||||
@@ -25,6 +27,14 @@ func (r *windowsReader) Clear() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *windowsReader) Read(fd uintptr) int32 {
|
func (r *windowsReader) Read(fd uintptr) int32 {
|
||||||
|
// On the first invocation, we return -1 to indicate "not ready"
|
||||||
|
// to make rawConn.Read wait for readability using the runtime's own mechanism
|
||||||
|
// because syscall.WSARecv() is a blocking call when used with nil OVERLAPPED
|
||||||
|
if !r.ready {
|
||||||
|
r.ready = true
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
var nBytes uint32
|
var nBytes uint32
|
||||||
var flags uint32
|
var flags uint32
|
||||||
err := syscall.WSARecv(syscall.Handle(fd), &r.bufs[0], uint32(len(r.bufs)), &nBytes, &flags, nil, nil)
|
err := syscall.WSARecv(syscall.Handle(fd), &r.bufs[0], uint32(len(r.bufs)), &nBytes, &flags, nil, nil)
|
||||||
|
|||||||
@@ -118,7 +118,9 @@ func (w *BufferedWriter) Write(b []byte) (int, error) {
|
|||||||
|
|
||||||
nBytes, err := w.buffer.Write(b)
|
nBytes, err := w.buffer.Write(b)
|
||||||
totalBytes += nBytes
|
totalBytes += nBytes
|
||||||
if err != nil {
|
|
||||||
|
// ErrBufferFull means a partial write, so flush below and continue
|
||||||
|
if err != nil && err != ErrBufferFull {
|
||||||
return totalBytes, err
|
return totalBytes, err
|
||||||
}
|
}
|
||||||
if !w.buffered || w.buffer.IsFull() {
|
if !w.buffered || w.buffer.IsFull() {
|
||||||
|
|||||||
@@ -10,12 +10,12 @@ import (
|
|||||||
|
|
||||||
// [,)
|
// [,)
|
||||||
func RandBetween(from int64, to int64) int64 {
|
func RandBetween(from int64, to int64) int64 {
|
||||||
if from == to {
|
|
||||||
return from
|
|
||||||
}
|
|
||||||
if from > to {
|
if from > to {
|
||||||
from, to = to, from
|
from, to = to, from
|
||||||
}
|
}
|
||||||
|
if d := to - from; d == 0 || d == 1 {
|
||||||
|
return from
|
||||||
|
}
|
||||||
bigInt, _ := rand.Int(rand.Reader, big.NewInt(to-from))
|
bigInt, _ := rand.Int(rand.Reader, big.NewInt(to-from))
|
||||||
return from + bigInt.Int64()
|
return from + bigInt.Int64()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common"
|
||||||
|
)
|
||||||
|
|
||||||
|
var privateIPMatcher = sync.OnceValue(func() IPMatcher {
|
||||||
|
return common.Must2(IPReg.BuildIPMatcher(common.Must2(ParseIPRules([]string{
|
||||||
|
"0.0.0.0/8",
|
||||||
|
"10.0.0.0/8",
|
||||||
|
"100.64.0.0/10",
|
||||||
|
"127.0.0.0/8",
|
||||||
|
"169.254.0.0/16",
|
||||||
|
"172.16.0.0/12",
|
||||||
|
"192.0.0.0/24",
|
||||||
|
"192.0.2.0/24",
|
||||||
|
"192.88.99.0/24",
|
||||||
|
"192.168.0.0/16",
|
||||||
|
"198.18.0.0/15",
|
||||||
|
"198.51.100.0/24",
|
||||||
|
"203.0.113.0/24",
|
||||||
|
"224.0.0.0/3",
|
||||||
|
"::/127",
|
||||||
|
"fc00::/7",
|
||||||
|
"fe80::/10",
|
||||||
|
"ff00::/8",
|
||||||
|
}))))
|
||||||
|
})
|
||||||
|
|
||||||
|
func GetPrivateIPMatcher() IPMatcher { return privateIPMatcher() }
|
||||||
|
|
||||||
|
var privateDomainMatcher = sync.OnceValue(func() DomainMatcher {
|
||||||
|
return common.Must2(DomainReg.BuildDomainMatcher(common.Must2(ParseDomainRules([]string{
|
||||||
|
"lan",
|
||||||
|
"localdomain",
|
||||||
|
"example",
|
||||||
|
"invalid",
|
||||||
|
"localhost",
|
||||||
|
"test",
|
||||||
|
"local",
|
||||||
|
"home.arpa",
|
||||||
|
"internal",
|
||||||
|
"regexp:^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$", // Dotless domains
|
||||||
|
}, Domain_Domain))))
|
||||||
|
})
|
||||||
|
|
||||||
|
func GetPrivateDomainMatcher() DomainMatcher { return privateDomainMatcher() }
|
||||||
@@ -8,10 +8,15 @@ import (
|
|||||||
|
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/geodata/strmatcher"
|
"github.com/xtls/xray-core/common/geodata/strmatcher"
|
||||||
|
"github.com/xtls/xray-core/common/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
type DomainMatcher interface {
|
type DomainMatcher interface {
|
||||||
|
// Match returns the indices of all rules that match the input domain.
|
||||||
|
// The returned slice is owned by the caller and may be safely modified.
|
||||||
|
// Note: the slice may contain duplicates and the order is unspecified.
|
||||||
Match(input string) []uint32
|
Match(input string) []uint32
|
||||||
|
|
||||||
MatchAny(input string) bool
|
MatchAny(input string) bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -19,10 +24,54 @@ type DomainMatcherFactory interface {
|
|||||||
BuildMatcher(rules []*DomainRule) (DomainMatcher, error)
|
BuildMatcher(rules []*DomainRule) (DomainMatcher, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type MphDomainMatcherFactory struct{}
|
type MphDomainMatcherFactory struct {
|
||||||
|
sync.Mutex
|
||||||
|
shared *utils.WeakCacheMap[string, strmatcher.MphValueMatcher]
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildDomainRulesKey(rules []*DomainRule) string {
|
||||||
|
var sb strings.Builder
|
||||||
|
cache := false
|
||||||
|
for _, r := range rules {
|
||||||
|
switch v := r.Value.(type) {
|
||||||
|
case *DomainRule_Custom:
|
||||||
|
sb.WriteString(v.Custom.Type.String())
|
||||||
|
sb.WriteString(":")
|
||||||
|
sb.WriteString(v.Custom.Value)
|
||||||
|
sb.WriteString(",")
|
||||||
|
case *DomainRule_Geosite:
|
||||||
|
cache = true
|
||||||
|
sb.WriteString(v.Geosite.File)
|
||||||
|
sb.WriteString(":")
|
||||||
|
sb.WriteString(v.Geosite.Code)
|
||||||
|
sb.WriteString("@")
|
||||||
|
sb.WriteString(v.Geosite.Attrs)
|
||||||
|
sb.WriteString(",")
|
||||||
|
default:
|
||||||
|
panic("unknown domain rule type")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !cache {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return sb.String()
|
||||||
|
}
|
||||||
|
|
||||||
// BuildMatcher implements DomainMatcherFactory.
|
// BuildMatcher implements DomainMatcherFactory.
|
||||||
func (f *MphDomainMatcherFactory) BuildMatcher(rules []*DomainRule) (DomainMatcher, error) {
|
func (f *MphDomainMatcherFactory) BuildMatcher(rules []*DomainRule) (DomainMatcher, error) {
|
||||||
|
if len(rules) == 0 {
|
||||||
|
return nil, errors.New("empty domain rule list")
|
||||||
|
}
|
||||||
|
key := buildDomainRulesKey(rules)
|
||||||
|
if key != "" {
|
||||||
|
f.Lock()
|
||||||
|
defer f.Unlock()
|
||||||
|
if g, ok := f.shared.Load(key); ok {
|
||||||
|
errors.LogDebug(context.Background(), "geodata mph domain matcher cache HIT for ", len(rules), " rules")
|
||||||
|
return g, nil
|
||||||
|
}
|
||||||
|
errors.LogDebug(context.Background(), "geodata mph domain matcher cache MISS for ", len(rules), " rules")
|
||||||
|
}
|
||||||
g := strmatcher.NewMphValueMatcher()
|
g := strmatcher.NewMphValueMatcher()
|
||||||
for i, r := range rules {
|
for i, r := range rules {
|
||||||
switch v := r.Value.(type) {
|
switch v := r.Value.(type) {
|
||||||
@@ -53,25 +102,30 @@ func (f *MphDomainMatcherFactory) BuildMatcher(rules []*DomainRule) (DomainMatch
|
|||||||
if err := g.Build(); err != nil {
|
if err := g.Build(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if key != "" {
|
||||||
|
f.shared.Store(key, g)
|
||||||
|
}
|
||||||
return g, nil
|
return g, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type CompactDomainMatcherFactory struct {
|
type CompactDomainMatcherFactory struct {
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
shared map[string]strmatcher.MatcherGroup // TODO: cleanup
|
shared *utils.WeakCacheMap[string, strmatcher.LinearAnyMatcher]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *CompactDomainMatcherFactory) getOrCreateFrom(rule *GeoSiteRule) (strmatcher.MatcherGroup, error) {
|
func (f *CompactDomainMatcherFactory) getOrCreateFrom(rule *GeoSiteRule) (strmatcher.MatcherSet, error) {
|
||||||
key := rule.File + ":" + rule.Code + "@" + rule.Attrs
|
key := rule.File + ":" + rule.Code + "@" + rule.Attrs
|
||||||
|
|
||||||
f.Lock()
|
f.Lock()
|
||||||
defer f.Unlock()
|
defer f.Unlock()
|
||||||
|
|
||||||
if m := f.shared[key]; m != nil {
|
if s, ok := f.shared.Load(key); ok {
|
||||||
return m, nil
|
errors.LogDebug(context.Background(), "geodata geosite matcher cache HIT ", key)
|
||||||
|
return s, nil
|
||||||
}
|
}
|
||||||
|
errors.LogDebug(context.Background(), "geodata geosite matcher cache MISS ", key)
|
||||||
|
|
||||||
g := strmatcher.NewLinearValueMatcher()
|
s := strmatcher.NewLinearAnyMatcher()
|
||||||
domains, err := loadSiteWithAttrs(rule.File, rule.Code, rule.Attrs)
|
domains, err := loadSiteWithAttrs(rule.File, rule.Code, rule.Attrs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -83,16 +137,19 @@ func (f *CompactDomainMatcherFactory) getOrCreateFrom(rule *GeoSiteRule) (strmat
|
|||||||
errors.LogError(context.Background(), "ignore invalid geosite entry in ", rule.File, ":", rule.Code, " at index ", i, ", ", err)
|
errors.LogError(context.Background(), "ignore invalid geosite entry in ", rule.File, ":", rule.Code, " at index ", i, ", ", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
g.Add(m, 0)
|
s.Add(m)
|
||||||
}
|
}
|
||||||
f.shared[key] = g
|
f.shared.Store(key, s)
|
||||||
return g, err
|
return s, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// BuildMatcher implements DomainMatcherFactory.
|
// BuildMatcher implements DomainMatcherFactory.
|
||||||
func (f *CompactDomainMatcherFactory) BuildMatcher(rules []*DomainRule) (DomainMatcher, error) {
|
func (f *CompactDomainMatcherFactory) BuildMatcher(rules []*DomainRule) (DomainMatcher, error) {
|
||||||
|
if len(rules) == 0 {
|
||||||
|
return nil, errors.New("empty domain rule list")
|
||||||
|
}
|
||||||
compact := &CompactDomainMatcher{
|
compact := &CompactDomainMatcher{
|
||||||
matchers: make([]strmatcher.MatcherGroup, 0, len(rules)),
|
matchers: make([]strmatcher.MatcherSet, 0, len(rules)),
|
||||||
values: make([]uint32, 0, len(rules)),
|
values: make([]uint32, 0, len(rules)),
|
||||||
}
|
}
|
||||||
for i, r := range rules {
|
for i, r := range rules {
|
||||||
@@ -122,7 +179,7 @@ func (f *CompactDomainMatcherFactory) BuildMatcher(rules []*DomainRule) (DomainM
|
|||||||
|
|
||||||
type CompactDomainMatcher struct {
|
type CompactDomainMatcher struct {
|
||||||
custom strmatcher.ValueMatcher
|
custom strmatcher.ValueMatcher
|
||||||
matchers []strmatcher.MatcherGroup
|
matchers []strmatcher.MatcherSet
|
||||||
values []uint32
|
values []uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,7 +220,7 @@ func parseDomain(d *Domain) (strmatcher.Matcher, error) {
|
|||||||
case Domain_Regex:
|
case Domain_Regex:
|
||||||
return strmatcher.Regex.New(d.Value)
|
return strmatcher.Regex.New(d.Value)
|
||||||
case Domain_Domain:
|
case Domain_Domain:
|
||||||
return strmatcher.Domain.New(d.Value)
|
return strmatcher.Domain.New(strings.ToLower(d.Value))
|
||||||
case Domain_Full:
|
case Domain_Full:
|
||||||
return strmatcher.Full.New(strings.ToLower(d.Value))
|
return strmatcher.Full.New(strings.ToLower(d.Value))
|
||||||
default:
|
default:
|
||||||
@@ -174,8 +231,8 @@ func parseDomain(d *Domain) (strmatcher.Matcher, error) {
|
|||||||
func newDomainMatcherFactory() DomainMatcherFactory {
|
func newDomainMatcherFactory() DomainMatcherFactory {
|
||||||
switch runtime.GOOS {
|
switch runtime.GOOS {
|
||||||
case "ios", "android":
|
case "ios", "android":
|
||||||
return &CompactDomainMatcherFactory{shared: make(map[string]strmatcher.MatcherGroup)}
|
return &CompactDomainMatcherFactory{shared: utils.NewWeakCacheMap[string, strmatcher.LinearAnyMatcher]()}
|
||||||
default:
|
default:
|
||||||
return &MphDomainMatcherFactory{}
|
return &MphDomainMatcherFactory{shared: utils.NewWeakCacheMap[string, strmatcher.MphValueMatcher]()}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,11 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/geodata/strmatcher"
|
"github.com/xtls/xray-core/common/geodata/strmatcher"
|
||||||
|
"github.com/xtls/xray-core/common/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCompactDomainMatcher_PreservesCustomRuleIndices(t *testing.T) {
|
func TestCompactDomainMatcher_PreservesCustomRuleIndices(t *testing.T) {
|
||||||
factory := &CompactDomainMatcherFactory{shared: make(map[string]strmatcher.MatcherGroup)}
|
factory := &CompactDomainMatcherFactory{shared: utils.NewWeakCacheMap[string, strmatcher.LinearAnyMatcher]()}
|
||||||
matcher, err := factory.BuildMatcher([]*DomainRule{
|
matcher, err := factory.BuildMatcher([]*DomainRule{
|
||||||
{Value: &DomainRule_Custom{Custom: &Domain{Type: Domain_Full, Value: "example.com"}}},
|
{Value: &DomainRule_Custom{Custom: &Domain{Type: Domain_Full, Value: "example.com"}}},
|
||||||
{Value: &DomainRule_Custom{Custom: &Domain{Type: Domain_Domain, Value: "example.com"}}},
|
{Value: &DomainRule_Custom{Custom: &Domain{Type: Domain_Domain, Value: "example.com"}}},
|
||||||
@@ -31,7 +32,7 @@ func TestCompactDomainMatcher_PreservesCustomRuleIndices(t *testing.T) {
|
|||||||
func TestCompactDomainMatcher_PreservesMixedRuleIndices(t *testing.T) {
|
func TestCompactDomainMatcher_PreservesMixedRuleIndices(t *testing.T) {
|
||||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||||
|
|
||||||
factory := &CompactDomainMatcherFactory{shared: make(map[string]strmatcher.MatcherGroup)}
|
factory := &CompactDomainMatcherFactory{shared: utils.NewWeakCacheMap[string, strmatcher.LinearAnyMatcher]()}
|
||||||
matcher, err := factory.BuildMatcher([]*DomainRule{
|
matcher, err := factory.BuildMatcher([]*DomainRule{
|
||||||
{Value: &DomainRule_Geosite{Geosite: &GeoSiteRule{File: DefaultGeoSiteDat, Code: "CN"}}},
|
{Value: &DomainRule_Geosite{Geosite: &GeoSiteRule{File: DefaultGeoSiteDat, Code: "CN"}}},
|
||||||
{Value: &DomainRule_Custom{Custom: &Domain{Type: Domain_Full, Value: "163.com"}}},
|
{Value: &DomainRule_Custom{Custom: &Domain{Type: Domain_Full, Value: "163.com"}}},
|
||||||
@@ -48,3 +49,26 @@ func TestCompactDomainMatcher_PreservesMixedRuleIndices(t *testing.T) {
|
|||||||
t.Fatalf("Match() = %v, want %v", got, want)
|
t.Fatalf("Match() = %v, want %v", got, want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMphDomainMatcher_MatchReturnsDetachedSlice(t *testing.T) {
|
||||||
|
matcher, err := (&MphDomainMatcherFactory{shared: utils.NewWeakCacheMap[string, strmatcher.MphValueMatcher]()}).
|
||||||
|
BuildMatcher([]*DomainRule{
|
||||||
|
{Value: &DomainRule_Custom{Custom: &Domain{Type: Domain_Full, Value: "example.com"}}},
|
||||||
|
{Value: &DomainRule_Custom{Custom: &Domain{Type: Domain_Domain, Value: "example.com"}}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("BuildMatcher() failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
got := matcher.Match("example.com")
|
||||||
|
if !reflect.DeepEqual(got, []uint32{0, 1}) {
|
||||||
|
t.Fatalf("Match() = %v, want %v", got, []uint32{0, 1})
|
||||||
|
}
|
||||||
|
|
||||||
|
got[0] = 1
|
||||||
|
|
||||||
|
gotAgain := matcher.Match("example.com")
|
||||||
|
if !reflect.DeepEqual(gotAgain, []uint32{0, 1}) {
|
||||||
|
t.Fatalf("Match() after caller mutation = %v, want %v", gotAgain, []uint32{0, 1})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,17 +1,102 @@
|
|||||||
package geodata
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
"github.com/xtls/xray-core/common/utils"
|
||||||
|
"github.com/xtls/xray-core/common/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
type DomainRegistry struct {
|
type DomainRegistry struct {
|
||||||
|
mu sync.Mutex
|
||||||
factory DomainMatcherFactory
|
factory DomainMatcherFactory
|
||||||
|
matchers *utils.WeakCacheMap[uuid.UUID, DynamicDomainMatcher]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *DomainRegistry) BuildDomainMatcher(rules []*DomainRule) (DomainMatcher, error) {
|
func (r *DomainRegistry) BuildDomainMatcher(rules []*DomainRule) (DomainMatcher, error) {
|
||||||
return r.factory.BuildMatcher(rules)
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
|
m, err := r.factory.BuildMatcher(rules)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
d := NewDynamicDomainMatcher(rules, m)
|
||||||
|
r.matchers.Store(uuid.New(), d)
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *DomainRegistry) Reload() error {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
|
var matchers []*DynamicDomainMatcher
|
||||||
|
r.matchers.Range(func(_ uuid.UUID, matcher *DynamicDomainMatcher) bool {
|
||||||
|
matchers = append(matchers, matcher)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
errors.LogInfo(context.Background(), "reloading GeoSite data for ", len(matchers), " domain matcher(s)")
|
||||||
|
|
||||||
|
factory := newDomainMatcherFactory()
|
||||||
|
type reloadEntry struct {
|
||||||
|
dynamic *DynamicDomainMatcher
|
||||||
|
matcher DomainMatcher
|
||||||
|
}
|
||||||
|
reloaded := make([]reloadEntry, len(matchers))
|
||||||
|
for i, d := range matchers {
|
||||||
|
m, err := factory.BuildMatcher(d.rules)
|
||||||
|
if err != nil {
|
||||||
|
errors.LogErrorInner(context.Background(), err, "failed to reload GeoSite data for domain matcher ", i)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
reloaded[i] = reloadEntry{dynamic: d, matcher: m}
|
||||||
|
}
|
||||||
|
for _, entry := range reloaded {
|
||||||
|
entry.dynamic.Reload(entry.matcher)
|
||||||
|
}
|
||||||
|
r.factory = factory
|
||||||
|
errors.LogInfo(context.Background(), "reloaded GeoSite data for ", len(matchers), " domain matcher(s)")
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newDomainRegistry() *DomainRegistry {
|
func newDomainRegistry() *DomainRegistry {
|
||||||
return &DomainRegistry{
|
return &DomainRegistry{
|
||||||
factory: newDomainMatcherFactory(),
|
factory: newDomainMatcherFactory(),
|
||||||
|
matchers: utils.NewWeakCacheMap[uuid.UUID, DynamicDomainMatcher](),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var DomainReg = newDomainRegistry()
|
var DomainReg = newDomainRegistry()
|
||||||
|
|
||||||
|
type domainMatcherState struct {
|
||||||
|
matcher DomainMatcher
|
||||||
|
}
|
||||||
|
|
||||||
|
type DynamicDomainMatcher struct {
|
||||||
|
rules []*DomainRule
|
||||||
|
state atomic.Pointer[domainMatcherState]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match implements DomainMatcher.
|
||||||
|
func (d *DynamicDomainMatcher) Match(input string) []uint32 {
|
||||||
|
return d.state.Load().matcher.Match(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatchAny implements DomainMatcher.
|
||||||
|
func (d *DynamicDomainMatcher) MatchAny(input string) bool {
|
||||||
|
return d.state.Load().matcher.MatchAny(input)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DynamicDomainMatcher) Reload(newMatcher DomainMatcher) {
|
||||||
|
d.state.Store(&domainMatcherState{matcher: newMatcher})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDynamicDomainMatcher(rules []*DomainRule, matcher DomainMatcher) *DynamicDomainMatcher {
|
||||||
|
d := &DynamicDomainMatcher{rules: rules}
|
||||||
|
d.Reload(matcher)
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|||||||
+96
-39
@@ -433,6 +433,58 @@ func (x *CIDR) GetPrefix() uint32 {
|
|||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CIDRRule struct {
|
||||||
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
|
Cidr *CIDR `protobuf:"bytes,1,opt,name=cidr,proto3" json:"cidr,omitempty"`
|
||||||
|
ReverseMatch bool `protobuf:"varint,2,opt,name=reverse_match,json=reverseMatch,proto3" json:"reverse_match,omitempty"`
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *CIDRRule) Reset() {
|
||||||
|
*x = CIDRRule{}
|
||||||
|
mi := &file_common_geodata_geodat_proto_msgTypes[6]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *CIDRRule) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*CIDRRule) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *CIDRRule) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_common_geodata_geodat_proto_msgTypes[6]
|
||||||
|
if x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use CIDRRule.ProtoReflect.Descriptor instead.
|
||||||
|
func (*CIDRRule) Descriptor() ([]byte, []int) {
|
||||||
|
return file_common_geodata_geodat_proto_rawDescGZIP(), []int{6}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *CIDRRule) GetCidr() *CIDR {
|
||||||
|
if x != nil {
|
||||||
|
return x.Cidr
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *CIDRRule) GetReverseMatch() bool {
|
||||||
|
if x != nil {
|
||||||
|
return x.ReverseMatch
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
type GeoIP struct {
|
type GeoIP struct {
|
||||||
state protoimpl.MessageState `protogen:"open.v1"`
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`
|
Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"`
|
||||||
@@ -444,7 +496,7 @@ type GeoIP struct {
|
|||||||
|
|
||||||
func (x *GeoIP) Reset() {
|
func (x *GeoIP) Reset() {
|
||||||
*x = GeoIP{}
|
*x = GeoIP{}
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[6]
|
mi := &file_common_geodata_geodat_proto_msgTypes[7]
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
ms.StoreMessageInfo(mi)
|
ms.StoreMessageInfo(mi)
|
||||||
}
|
}
|
||||||
@@ -456,7 +508,7 @@ func (x *GeoIP) String() string {
|
|||||||
func (*GeoIP) ProtoMessage() {}
|
func (*GeoIP) ProtoMessage() {}
|
||||||
|
|
||||||
func (x *GeoIP) ProtoReflect() protoreflect.Message {
|
func (x *GeoIP) ProtoReflect() protoreflect.Message {
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[6]
|
mi := &file_common_geodata_geodat_proto_msgTypes[7]
|
||||||
if x != nil {
|
if x != nil {
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
if ms.LoadMessageInfo() == nil {
|
if ms.LoadMessageInfo() == nil {
|
||||||
@@ -469,7 +521,7 @@ func (x *GeoIP) ProtoReflect() protoreflect.Message {
|
|||||||
|
|
||||||
// Deprecated: Use GeoIP.ProtoReflect.Descriptor instead.
|
// Deprecated: Use GeoIP.ProtoReflect.Descriptor instead.
|
||||||
func (*GeoIP) Descriptor() ([]byte, []int) {
|
func (*GeoIP) Descriptor() ([]byte, []int) {
|
||||||
return file_common_geodata_geodat_proto_rawDescGZIP(), []int{6}
|
return file_common_geodata_geodat_proto_rawDescGZIP(), []int{7}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (x *GeoIP) GetCode() string {
|
func (x *GeoIP) GetCode() string {
|
||||||
@@ -502,7 +554,7 @@ type GeoIPList struct {
|
|||||||
|
|
||||||
func (x *GeoIPList) Reset() {
|
func (x *GeoIPList) Reset() {
|
||||||
*x = GeoIPList{}
|
*x = GeoIPList{}
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[7]
|
mi := &file_common_geodata_geodat_proto_msgTypes[8]
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
ms.StoreMessageInfo(mi)
|
ms.StoreMessageInfo(mi)
|
||||||
}
|
}
|
||||||
@@ -514,7 +566,7 @@ func (x *GeoIPList) String() string {
|
|||||||
func (*GeoIPList) ProtoMessage() {}
|
func (*GeoIPList) ProtoMessage() {}
|
||||||
|
|
||||||
func (x *GeoIPList) ProtoReflect() protoreflect.Message {
|
func (x *GeoIPList) ProtoReflect() protoreflect.Message {
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[7]
|
mi := &file_common_geodata_geodat_proto_msgTypes[8]
|
||||||
if x != nil {
|
if x != nil {
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
if ms.LoadMessageInfo() == nil {
|
if ms.LoadMessageInfo() == nil {
|
||||||
@@ -527,7 +579,7 @@ func (x *GeoIPList) ProtoReflect() protoreflect.Message {
|
|||||||
|
|
||||||
// Deprecated: Use GeoIPList.ProtoReflect.Descriptor instead.
|
// Deprecated: Use GeoIPList.ProtoReflect.Descriptor instead.
|
||||||
func (*GeoIPList) Descriptor() ([]byte, []int) {
|
func (*GeoIPList) Descriptor() ([]byte, []int) {
|
||||||
return file_common_geodata_geodat_proto_rawDescGZIP(), []int{7}
|
return file_common_geodata_geodat_proto_rawDescGZIP(), []int{8}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (x *GeoIPList) GetEntry() []*GeoIP {
|
func (x *GeoIPList) GetEntry() []*GeoIP {
|
||||||
@@ -548,7 +600,7 @@ type GeoIPRule struct {
|
|||||||
|
|
||||||
func (x *GeoIPRule) Reset() {
|
func (x *GeoIPRule) Reset() {
|
||||||
*x = GeoIPRule{}
|
*x = GeoIPRule{}
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[8]
|
mi := &file_common_geodata_geodat_proto_msgTypes[9]
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
ms.StoreMessageInfo(mi)
|
ms.StoreMessageInfo(mi)
|
||||||
}
|
}
|
||||||
@@ -560,7 +612,7 @@ func (x *GeoIPRule) String() string {
|
|||||||
func (*GeoIPRule) ProtoMessage() {}
|
func (*GeoIPRule) ProtoMessage() {}
|
||||||
|
|
||||||
func (x *GeoIPRule) ProtoReflect() protoreflect.Message {
|
func (x *GeoIPRule) ProtoReflect() protoreflect.Message {
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[8]
|
mi := &file_common_geodata_geodat_proto_msgTypes[9]
|
||||||
if x != nil {
|
if x != nil {
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
if ms.LoadMessageInfo() == nil {
|
if ms.LoadMessageInfo() == nil {
|
||||||
@@ -573,7 +625,7 @@ func (x *GeoIPRule) ProtoReflect() protoreflect.Message {
|
|||||||
|
|
||||||
// Deprecated: Use GeoIPRule.ProtoReflect.Descriptor instead.
|
// Deprecated: Use GeoIPRule.ProtoReflect.Descriptor instead.
|
||||||
func (*GeoIPRule) Descriptor() ([]byte, []int) {
|
func (*GeoIPRule) Descriptor() ([]byte, []int) {
|
||||||
return file_common_geodata_geodat_proto_rawDescGZIP(), []int{8}
|
return file_common_geodata_geodat_proto_rawDescGZIP(), []int{9}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (x *GeoIPRule) GetFile() string {
|
func (x *GeoIPRule) GetFile() string {
|
||||||
@@ -610,7 +662,7 @@ type IPRule struct {
|
|||||||
|
|
||||||
func (x *IPRule) Reset() {
|
func (x *IPRule) Reset() {
|
||||||
*x = IPRule{}
|
*x = IPRule{}
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[9]
|
mi := &file_common_geodata_geodat_proto_msgTypes[10]
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
ms.StoreMessageInfo(mi)
|
ms.StoreMessageInfo(mi)
|
||||||
}
|
}
|
||||||
@@ -622,7 +674,7 @@ func (x *IPRule) String() string {
|
|||||||
func (*IPRule) ProtoMessage() {}
|
func (*IPRule) ProtoMessage() {}
|
||||||
|
|
||||||
func (x *IPRule) ProtoReflect() protoreflect.Message {
|
func (x *IPRule) ProtoReflect() protoreflect.Message {
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[9]
|
mi := &file_common_geodata_geodat_proto_msgTypes[10]
|
||||||
if x != nil {
|
if x != nil {
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
if ms.LoadMessageInfo() == nil {
|
if ms.LoadMessageInfo() == nil {
|
||||||
@@ -635,7 +687,7 @@ func (x *IPRule) ProtoReflect() protoreflect.Message {
|
|||||||
|
|
||||||
// Deprecated: Use IPRule.ProtoReflect.Descriptor instead.
|
// Deprecated: Use IPRule.ProtoReflect.Descriptor instead.
|
||||||
func (*IPRule) Descriptor() ([]byte, []int) {
|
func (*IPRule) Descriptor() ([]byte, []int) {
|
||||||
return file_common_geodata_geodat_proto_rawDescGZIP(), []int{9}
|
return file_common_geodata_geodat_proto_rawDescGZIP(), []int{10}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (x *IPRule) GetValue() isIPRule_Value {
|
func (x *IPRule) GetValue() isIPRule_Value {
|
||||||
@@ -654,7 +706,7 @@ func (x *IPRule) GetGeoip() *GeoIPRule {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (x *IPRule) GetCustom() *CIDR {
|
func (x *IPRule) GetCustom() *CIDRRule {
|
||||||
if x != nil {
|
if x != nil {
|
||||||
if x, ok := x.Value.(*IPRule_Custom); ok {
|
if x, ok := x.Value.(*IPRule_Custom); ok {
|
||||||
return x.Custom
|
return x.Custom
|
||||||
@@ -672,7 +724,7 @@ type IPRule_Geoip struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type IPRule_Custom struct {
|
type IPRule_Custom struct {
|
||||||
Custom *CIDR `protobuf:"bytes,2,opt,name=custom,proto3,oneof"`
|
Custom *CIDRRule `protobuf:"bytes,2,opt,name=custom,proto3,oneof"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (*IPRule_Geoip) isIPRule_Value() {}
|
func (*IPRule_Geoip) isIPRule_Value() {}
|
||||||
@@ -693,7 +745,7 @@ type Domain_Attribute struct {
|
|||||||
|
|
||||||
func (x *Domain_Attribute) Reset() {
|
func (x *Domain_Attribute) Reset() {
|
||||||
*x = Domain_Attribute{}
|
*x = Domain_Attribute{}
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[10]
|
mi := &file_common_geodata_geodat_proto_msgTypes[11]
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
ms.StoreMessageInfo(mi)
|
ms.StoreMessageInfo(mi)
|
||||||
}
|
}
|
||||||
@@ -705,7 +757,7 @@ func (x *Domain_Attribute) String() string {
|
|||||||
func (*Domain_Attribute) ProtoMessage() {}
|
func (*Domain_Attribute) ProtoMessage() {}
|
||||||
|
|
||||||
func (x *Domain_Attribute) ProtoReflect() protoreflect.Message {
|
func (x *Domain_Attribute) ProtoReflect() protoreflect.Message {
|
||||||
mi := &file_common_geodata_geodat_proto_msgTypes[10]
|
mi := &file_common_geodata_geodat_proto_msgTypes[11]
|
||||||
if x != nil {
|
if x != nil {
|
||||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
if ms.LoadMessageInfo() == nil {
|
if ms.LoadMessageInfo() == nil {
|
||||||
@@ -807,7 +859,10 @@ const file_common_geodata_geodat_proto_rawDesc = "" +
|
|||||||
"\x05value\".\n" +
|
"\x05value\".\n" +
|
||||||
"\x04CIDR\x12\x0e\n" +
|
"\x04CIDR\x12\x0e\n" +
|
||||||
"\x02ip\x18\x01 \x01(\fR\x02ip\x12\x16\n" +
|
"\x02ip\x18\x01 \x01(\fR\x02ip\x12\x16\n" +
|
||||||
"\x06prefix\x18\x02 \x01(\rR\x06prefix\"o\n" +
|
"\x06prefix\x18\x02 \x01(\rR\x06prefix\"^\n" +
|
||||||
|
"\bCIDRRule\x12-\n" +
|
||||||
|
"\x04cidr\x18\x01 \x01(\v2\x19.xray.common.geodata.CIDRR\x04cidr\x12#\n" +
|
||||||
|
"\rreverse_match\x18\x02 \x01(\bR\freverseMatch\"o\n" +
|
||||||
"\x05GeoIP\x12\x12\n" +
|
"\x05GeoIP\x12\x12\n" +
|
||||||
"\x04code\x18\x01 \x01(\tR\x04code\x12-\n" +
|
"\x04code\x18\x01 \x01(\tR\x04code\x12-\n" +
|
||||||
"\x04cidr\x18\x02 \x03(\v2\x19.xray.common.geodata.CIDRR\x04cidr\x12#\n" +
|
"\x04cidr\x18\x02 \x03(\v2\x19.xray.common.geodata.CIDRR\x04cidr\x12#\n" +
|
||||||
@@ -817,10 +872,10 @@ const file_common_geodata_geodat_proto_rawDesc = "" +
|
|||||||
"\tGeoIPRule\x12\x12\n" +
|
"\tGeoIPRule\x12\x12\n" +
|
||||||
"\x04file\x18\x01 \x01(\tR\x04file\x12\x12\n" +
|
"\x04file\x18\x01 \x01(\tR\x04file\x12\x12\n" +
|
||||||
"\x04code\x18\x02 \x01(\tR\x04code\x12#\n" +
|
"\x04code\x18\x02 \x01(\tR\x04code\x12#\n" +
|
||||||
"\rreverse_match\x18\x03 \x01(\bR\freverseMatch\"~\n" +
|
"\rreverse_match\x18\x03 \x01(\bR\freverseMatch\"\x82\x01\n" +
|
||||||
"\x06IPRule\x126\n" +
|
"\x06IPRule\x126\n" +
|
||||||
"\x05geoip\x18\x01 \x01(\v2\x1e.xray.common.geodata.GeoIPRuleH\x00R\x05geoip\x123\n" +
|
"\x05geoip\x18\x01 \x01(\v2\x1e.xray.common.geodata.GeoIPRuleH\x00R\x05geoip\x127\n" +
|
||||||
"\x06custom\x18\x02 \x01(\v2\x19.xray.common.geodata.CIDRH\x00R\x06customB\a\n" +
|
"\x06custom\x18\x02 \x01(\v2\x1d.xray.common.geodata.CIDRRuleH\x00R\x06customB\a\n" +
|
||||||
"\x05valueB[\n" +
|
"\x05valueB[\n" +
|
||||||
"\x17com.xray.common.geodataP\x01Z(github.com/xtls/xray-core/common/geodata\xaa\x02\x13Xray.Common.Geodatab\x06proto3"
|
"\x17com.xray.common.geodataP\x01Z(github.com/xtls/xray-core/common/geodata\xaa\x02\x13Xray.Common.Geodatab\x06proto3"
|
||||||
|
|
||||||
@@ -837,7 +892,7 @@ func file_common_geodata_geodat_proto_rawDescGZIP() []byte {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var file_common_geodata_geodat_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
var file_common_geodata_geodat_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
|
||||||
var file_common_geodata_geodat_proto_msgTypes = make([]protoimpl.MessageInfo, 11)
|
var file_common_geodata_geodat_proto_msgTypes = make([]protoimpl.MessageInfo, 12)
|
||||||
var file_common_geodata_geodat_proto_goTypes = []any{
|
var file_common_geodata_geodat_proto_goTypes = []any{
|
||||||
(Domain_Type)(0), // 0: xray.common.geodata.Domain.Type
|
(Domain_Type)(0), // 0: xray.common.geodata.Domain.Type
|
||||||
(*Domain)(nil), // 1: xray.common.geodata.Domain
|
(*Domain)(nil), // 1: xray.common.geodata.Domain
|
||||||
@@ -846,28 +901,30 @@ var file_common_geodata_geodat_proto_goTypes = []any{
|
|||||||
(*GeoSiteRule)(nil), // 4: xray.common.geodata.GeoSiteRule
|
(*GeoSiteRule)(nil), // 4: xray.common.geodata.GeoSiteRule
|
||||||
(*DomainRule)(nil), // 5: xray.common.geodata.DomainRule
|
(*DomainRule)(nil), // 5: xray.common.geodata.DomainRule
|
||||||
(*CIDR)(nil), // 6: xray.common.geodata.CIDR
|
(*CIDR)(nil), // 6: xray.common.geodata.CIDR
|
||||||
(*GeoIP)(nil), // 7: xray.common.geodata.GeoIP
|
(*CIDRRule)(nil), // 7: xray.common.geodata.CIDRRule
|
||||||
(*GeoIPList)(nil), // 8: xray.common.geodata.GeoIPList
|
(*GeoIP)(nil), // 8: xray.common.geodata.GeoIP
|
||||||
(*GeoIPRule)(nil), // 9: xray.common.geodata.GeoIPRule
|
(*GeoIPList)(nil), // 9: xray.common.geodata.GeoIPList
|
||||||
(*IPRule)(nil), // 10: xray.common.geodata.IPRule
|
(*GeoIPRule)(nil), // 10: xray.common.geodata.GeoIPRule
|
||||||
(*Domain_Attribute)(nil), // 11: xray.common.geodata.Domain.Attribute
|
(*IPRule)(nil), // 11: xray.common.geodata.IPRule
|
||||||
|
(*Domain_Attribute)(nil), // 12: xray.common.geodata.Domain.Attribute
|
||||||
}
|
}
|
||||||
var file_common_geodata_geodat_proto_depIdxs = []int32{
|
var file_common_geodata_geodat_proto_depIdxs = []int32{
|
||||||
0, // 0: xray.common.geodata.Domain.type:type_name -> xray.common.geodata.Domain.Type
|
0, // 0: xray.common.geodata.Domain.type:type_name -> xray.common.geodata.Domain.Type
|
||||||
11, // 1: xray.common.geodata.Domain.attribute:type_name -> xray.common.geodata.Domain.Attribute
|
12, // 1: xray.common.geodata.Domain.attribute:type_name -> xray.common.geodata.Domain.Attribute
|
||||||
1, // 2: xray.common.geodata.GeoSite.domain:type_name -> xray.common.geodata.Domain
|
1, // 2: xray.common.geodata.GeoSite.domain:type_name -> xray.common.geodata.Domain
|
||||||
2, // 3: xray.common.geodata.GeoSiteList.entry:type_name -> xray.common.geodata.GeoSite
|
2, // 3: xray.common.geodata.GeoSiteList.entry:type_name -> xray.common.geodata.GeoSite
|
||||||
4, // 4: xray.common.geodata.DomainRule.geosite:type_name -> xray.common.geodata.GeoSiteRule
|
4, // 4: xray.common.geodata.DomainRule.geosite:type_name -> xray.common.geodata.GeoSiteRule
|
||||||
1, // 5: xray.common.geodata.DomainRule.custom:type_name -> xray.common.geodata.Domain
|
1, // 5: xray.common.geodata.DomainRule.custom:type_name -> xray.common.geodata.Domain
|
||||||
6, // 6: xray.common.geodata.GeoIP.cidr:type_name -> xray.common.geodata.CIDR
|
6, // 6: xray.common.geodata.CIDRRule.cidr:type_name -> xray.common.geodata.CIDR
|
||||||
7, // 7: xray.common.geodata.GeoIPList.entry:type_name -> xray.common.geodata.GeoIP
|
6, // 7: xray.common.geodata.GeoIP.cidr:type_name -> xray.common.geodata.CIDR
|
||||||
9, // 8: xray.common.geodata.IPRule.geoip:type_name -> xray.common.geodata.GeoIPRule
|
8, // 8: xray.common.geodata.GeoIPList.entry:type_name -> xray.common.geodata.GeoIP
|
||||||
6, // 9: xray.common.geodata.IPRule.custom:type_name -> xray.common.geodata.CIDR
|
10, // 9: xray.common.geodata.IPRule.geoip:type_name -> xray.common.geodata.GeoIPRule
|
||||||
10, // [10:10] is the sub-list for method output_type
|
7, // 10: xray.common.geodata.IPRule.custom:type_name -> xray.common.geodata.CIDRRule
|
||||||
10, // [10:10] is the sub-list for method input_type
|
11, // [11:11] is the sub-list for method output_type
|
||||||
10, // [10:10] is the sub-list for extension type_name
|
11, // [11:11] is the sub-list for method input_type
|
||||||
10, // [10:10] is the sub-list for extension extendee
|
11, // [11:11] is the sub-list for extension type_name
|
||||||
0, // [0:10] is the sub-list for field type_name
|
11, // [11:11] is the sub-list for extension extendee
|
||||||
|
0, // [0:11] is the sub-list for field type_name
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() { file_common_geodata_geodat_proto_init() }
|
func init() { file_common_geodata_geodat_proto_init() }
|
||||||
@@ -879,11 +936,11 @@ func file_common_geodata_geodat_proto_init() {
|
|||||||
(*DomainRule_Geosite)(nil),
|
(*DomainRule_Geosite)(nil),
|
||||||
(*DomainRule_Custom)(nil),
|
(*DomainRule_Custom)(nil),
|
||||||
}
|
}
|
||||||
file_common_geodata_geodat_proto_msgTypes[9].OneofWrappers = []any{
|
file_common_geodata_geodat_proto_msgTypes[10].OneofWrappers = []any{
|
||||||
(*IPRule_Geoip)(nil),
|
(*IPRule_Geoip)(nil),
|
||||||
(*IPRule_Custom)(nil),
|
(*IPRule_Custom)(nil),
|
||||||
}
|
}
|
||||||
file_common_geodata_geodat_proto_msgTypes[10].OneofWrappers = []any{
|
file_common_geodata_geodat_proto_msgTypes[11].OneofWrappers = []any{
|
||||||
(*Domain_Attribute_BoolValue)(nil),
|
(*Domain_Attribute_BoolValue)(nil),
|
||||||
(*Domain_Attribute_IntValue)(nil),
|
(*Domain_Attribute_IntValue)(nil),
|
||||||
}
|
}
|
||||||
@@ -893,7 +950,7 @@ func file_common_geodata_geodat_proto_init() {
|
|||||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_common_geodata_geodat_proto_rawDesc), len(file_common_geodata_geodat_proto_rawDesc)),
|
RawDescriptor: unsafe.Slice(unsafe.StringData(file_common_geodata_geodat_proto_rawDesc), len(file_common_geodata_geodat_proto_rawDesc)),
|
||||||
NumEnums: 1,
|
NumEnums: 1,
|
||||||
NumMessages: 11,
|
NumMessages: 12,
|
||||||
NumExtensions: 0,
|
NumExtensions: 0,
|
||||||
NumServices: 0,
|
NumServices: 0,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -66,6 +66,11 @@ message CIDR {
|
|||||||
uint32 prefix = 2;
|
uint32 prefix = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message CIDRRule {
|
||||||
|
CIDR cidr = 1;
|
||||||
|
bool reverse_match = 2;
|
||||||
|
}
|
||||||
|
|
||||||
message GeoIP {
|
message GeoIP {
|
||||||
string code = 1;
|
string code = 1;
|
||||||
repeated CIDR cidr = 2;
|
repeated CIDR cidr = 2;
|
||||||
@@ -85,6 +90,6 @@ message GeoIPRule {
|
|||||||
message IPRule {
|
message IPRule {
|
||||||
oneof value {
|
oneof value {
|
||||||
GeoIPRule geoip = 1;
|
GeoIPRule geoip = 1;
|
||||||
CIDR custom = 2;
|
CIDRRule custom = 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
|
|
||||||
"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/utils"
|
||||||
|
|
||||||
"go4.org/netipx"
|
"go4.org/netipx"
|
||||||
)
|
)
|
||||||
@@ -806,7 +807,7 @@ func (mm *HeuristicMultiIPMatcher) SetReverse(reverse bool) {
|
|||||||
|
|
||||||
type IPSetFactory struct {
|
type IPSetFactory struct {
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
shared map[string]*IPSet // TODO: cleanup
|
shared *utils.WeakCacheMap[string, IPSet]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *IPSetFactory) GetOrCreateFromGeoIPRules(rules []*GeoIPRule) (*IPSet, error) {
|
func (f *IPSetFactory) GetOrCreateFromGeoIPRules(rules []*GeoIPRule) (*IPSet, error) {
|
||||||
@@ -815,9 +816,11 @@ func (f *IPSetFactory) GetOrCreateFromGeoIPRules(rules []*GeoIPRule) (*IPSet, er
|
|||||||
f.Lock()
|
f.Lock()
|
||||||
defer f.Unlock()
|
defer f.Unlock()
|
||||||
|
|
||||||
if ipset := f.shared[key]; ipset != nil {
|
if ipset, ok := f.shared.Load(key); ok {
|
||||||
|
errors.LogDebug(context.Background(), "geodata geoip matcher cache HIT ", key)
|
||||||
return ipset, nil
|
return ipset, nil
|
||||||
}
|
}
|
||||||
|
errors.LogDebug(context.Background(), "geodata geoip matcher cache MISS ", key)
|
||||||
|
|
||||||
ipset, err := f.createFrom(func(add func(*CIDR)) error {
|
ipset, err := f.createFrom(func(add func(*CIDR)) error {
|
||||||
for _, r := range rules {
|
for _, r := range rules {
|
||||||
@@ -833,7 +836,7 @@ func (f *IPSetFactory) GetOrCreateFromGeoIPRules(rules []*GeoIPRule) (*IPSet, er
|
|||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
f.shared[key] = ipset
|
f.shared.Store(key, ipset)
|
||||||
}
|
}
|
||||||
return ipset, err
|
return ipset, err
|
||||||
}
|
}
|
||||||
@@ -915,24 +918,31 @@ func (f *IPSetFactory) createFrom(yield func(func(*CIDR)) error) (*IPSet, error)
|
|||||||
return nil, errors.New("failed to build IPv6 set").Base(err)
|
return nil, errors.New("failed to build IPv6 set").Base(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var has4, has6 bool
|
||||||
var max4, max6 int
|
var max4, max6 int
|
||||||
|
|
||||||
for _, p := range ipv4.Prefixes() {
|
for _, p := range ipv4.Prefixes() {
|
||||||
|
has4 = true
|
||||||
if b := p.Bits(); b > max4 {
|
if b := p.Bits(); b > max4 {
|
||||||
max4 = b
|
max4 = b
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, p := range ipv6.Prefixes() {
|
for _, p := range ipv6.Prefixes() {
|
||||||
|
has6 = true
|
||||||
if b := p.Bits(); b > max6 {
|
if b := p.Bits(); b > max6 {
|
||||||
max6 = b
|
max6 = b
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if max4 == 0 {
|
if !has4 {
|
||||||
max4 = 0xff
|
max4 = 0xff
|
||||||
|
} else if max4 == 0 {
|
||||||
|
max4 = 0xfe
|
||||||
}
|
}
|
||||||
if max6 == 0 {
|
if !has6 {
|
||||||
max6 = 0xff
|
max6 = 0xff
|
||||||
|
} else if max6 == 0 {
|
||||||
|
max6 = 0xfe
|
||||||
}
|
}
|
||||||
|
|
||||||
return &IPSet{ipv4: ipv4, ipv6: ipv6, max4: uint8(max4), max6: uint8(max6)}, nil
|
return &IPSet{ipv4: ipv4, ipv6: ipv6, max4: uint8(max4), max6: uint8(max6)}, nil
|
||||||
@@ -940,45 +950,58 @@ func (f *IPSetFactory) createFrom(yield func(func(*CIDR)) error) (*IPSet, error)
|
|||||||
|
|
||||||
func buildOptimizedIPMatcher(f *IPSetFactory, rules []*IPRule) (IPMatcher, error) {
|
func buildOptimizedIPMatcher(f *IPSetFactory, rules []*IPRule) (IPMatcher, error) {
|
||||||
n := len(rules)
|
n := len(rules)
|
||||||
custom := make([]*CIDR, 0, n)
|
posCustom := make([]*CIDR, 0, n)
|
||||||
pos := make([]*GeoIPRule, 0, n)
|
negCustom := make([]*CIDR, 0, n)
|
||||||
neg := make([]*GeoIPRule, 0, n)
|
posGeoip := make([]*GeoIPRule, 0, n)
|
||||||
|
negGeoip := make([]*GeoIPRule, 0, n)
|
||||||
|
|
||||||
for _, r := range rules {
|
for _, r := range rules {
|
||||||
switch v := r.Value.(type) {
|
switch v := r.Value.(type) {
|
||||||
case *IPRule_Custom:
|
case *IPRule_Custom:
|
||||||
custom = append(custom, v.Custom)
|
if !v.Custom.ReverseMatch {
|
||||||
|
posCustom = append(posCustom, v.Custom.Cidr)
|
||||||
|
} else {
|
||||||
|
negCustom = append(negCustom, v.Custom.Cidr)
|
||||||
|
}
|
||||||
case *IPRule_Geoip:
|
case *IPRule_Geoip:
|
||||||
if !v.Geoip.ReverseMatch {
|
if !v.Geoip.ReverseMatch {
|
||||||
pos = append(pos, v.Geoip)
|
posGeoip = append(posGeoip, v.Geoip)
|
||||||
} else {
|
} else {
|
||||||
neg = append(neg, v.Geoip)
|
negGeoip = append(negGeoip, v.Geoip)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
panic("unknown ip rule type")
|
panic("unknown ip rule type")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
subs := make([]*HeuristicIPMatcher, 0, 3)
|
subs := make([]*HeuristicIPMatcher, 0, 4)
|
||||||
|
|
||||||
if len(custom) > 0 {
|
if len(posCustom) > 0 {
|
||||||
ipset, err := f.CreateFromCIDRs(custom)
|
ipset, err := f.CreateFromCIDRs(posCustom)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
subs = append(subs, &HeuristicIPMatcher{ipset: ipset, reverse: false})
|
subs = append(subs, &HeuristicIPMatcher{ipset: ipset, reverse: false})
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(pos) > 0 {
|
if len(negCustom) > 0 {
|
||||||
ipset, err := f.GetOrCreateFromGeoIPRules(pos)
|
ipset, err := f.CreateFromCIDRs(negCustom)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
subs = append(subs, &HeuristicIPMatcher{ipset: ipset, reverse: true})
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(posGeoip) > 0 {
|
||||||
|
ipset, err := f.GetOrCreateFromGeoIPRules(posGeoip)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
subs = append(subs, &HeuristicIPMatcher{ipset: ipset, reverse: false})
|
subs = append(subs, &HeuristicIPMatcher{ipset: ipset, reverse: false})
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(neg) > 0 {
|
if len(negGeoip) > 0 {
|
||||||
ipset, err := f.GetOrCreateFromGeoIPRules(neg)
|
ipset, err := f.GetOrCreateFromGeoIPRules(negGeoip)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -994,3 +1017,7 @@ func buildOptimizedIPMatcher(f *IPSetFactory, rules []*IPRule) (IPMatcher, error
|
|||||||
return &HeuristicMultiIPMatcher{matchers: subs}, nil
|
return &HeuristicMultiIPMatcher{matchers: subs}, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func newIPSetFactory() *IPSetFactory {
|
||||||
|
return &IPSetFactory{shared: utils.NewWeakCacheMap[string, IPSet]()}
|
||||||
|
}
|
||||||
|
|||||||
@@ -97,6 +97,90 @@ func TestIPMatcher(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIPMatcherFullCIDR4(t *testing.T) {
|
||||||
|
matcher := buildIPMatcher(
|
||||||
|
"0.0.0.0/0",
|
||||||
|
)
|
||||||
|
|
||||||
|
testCases := []struct {
|
||||||
|
Input string
|
||||||
|
Output bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Input: "192.168.1.1",
|
||||||
|
Output: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "0.0.0.0",
|
||||||
|
Output: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "255.255.255.255",
|
||||||
|
Output: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "2001:cdba::3257:9652",
|
||||||
|
Output: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "::0",
|
||||||
|
Output: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||||
|
Output: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range testCases {
|
||||||
|
if v := matcher.Match(xnet.ParseAddress(test.Input).IP()); v != test.Output {
|
||||||
|
t.Error("unexpected output: ", v, " for test case ", test)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIPMatcherFullCIDR6(t *testing.T) {
|
||||||
|
matcher := buildIPMatcher(
|
||||||
|
"::0/0",
|
||||||
|
)
|
||||||
|
|
||||||
|
testCases := []struct {
|
||||||
|
Input string
|
||||||
|
Output bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Input: "192.168.1.1",
|
||||||
|
Output: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "0.0.0.0",
|
||||||
|
Output: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "255.255.255.255",
|
||||||
|
Output: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "2001:cdba::3257:9652",
|
||||||
|
Output: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "::0",
|
||||||
|
Output: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
|
||||||
|
Output: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range testCases {
|
||||||
|
if v := matcher.Match(xnet.ParseAddress(test.Input).IP()); v != test.Output {
|
||||||
|
t.Error("unexpected output: ", v, " for test case ", test)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestIPMatcherRegression(t *testing.T) {
|
func TestIPMatcherRegression(t *testing.T) {
|
||||||
matcher := buildIPMatcher(
|
matcher := buildIPMatcher(
|
||||||
"98.108.20.0/22",
|
"98.108.20.0/22",
|
||||||
@@ -189,6 +273,34 @@ func TestIPReverseMatcher2(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIPCustomReverseMatcher(t *testing.T) {
|
||||||
|
matcher := buildIPMatcher("!8.8.8.8/32")
|
||||||
|
|
||||||
|
testCases := []struct {
|
||||||
|
Input string
|
||||||
|
Output bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Input: "8.8.8.8",
|
||||||
|
Output: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "1.1.1.1",
|
||||||
|
Output: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Input: "2001:cdba::3257:9652",
|
||||||
|
Output: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range testCases {
|
||||||
|
if v := matcher.Match(xnet.ParseAddress(test.Input).IP()); v != test.Output {
|
||||||
|
t.Error("unexpected output: ", v, " for test case ", test)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestIPMatcherAnyMatchAndMatches(t *testing.T) {
|
func TestIPMatcherAnyMatchAndMatches(t *testing.T) {
|
||||||
matcher := buildIPMatcher(
|
matcher := buildIPMatcher(
|
||||||
"8.8.8.8/32",
|
"8.8.8.8/32",
|
||||||
@@ -203,7 +315,7 @@ func TestIPMatcherAnyMatchAndMatches(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !matcher.AnyMatch([]net.IP{
|
if !matcher.AnyMatch([]net.IP{
|
||||||
net.IP{},
|
{},
|
||||||
ip("1.1.1.1"),
|
ip("1.1.1.1"),
|
||||||
ip("8.8.8.8"),
|
ip("8.8.8.8"),
|
||||||
}) {
|
}) {
|
||||||
@@ -233,7 +345,7 @@ func TestIPMatcherAnyMatchAndMatches(t *testing.T) {
|
|||||||
|
|
||||||
if matcher.Matches([]net.IP{
|
if matcher.Matches([]net.IP{
|
||||||
ip("8.8.8.8"),
|
ip("8.8.8.8"),
|
||||||
net.IP{},
|
{},
|
||||||
}) {
|
}) {
|
||||||
t.Fatal("expect Matches to be false when any IP is invalid")
|
t.Fatal("expect Matches to be false when any IP is invalid")
|
||||||
}
|
}
|
||||||
@@ -250,7 +362,7 @@ func TestIPMatcherFilterIPs(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
matched, unmatched := matcher.FilterIPs([]net.IP{
|
matched, unmatched := matcher.FilterIPs([]net.IP{
|
||||||
net.IP{},
|
{},
|
||||||
ip("8.8.8.8"),
|
ip("8.8.8.8"),
|
||||||
ip("91.108.255.254"),
|
ip("91.108.255.254"),
|
||||||
ip("1.1.1.1"),
|
ip("1.1.1.1"),
|
||||||
|
|||||||
@@ -1,17 +1,143 @@
|
|||||||
package geodata
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
"github.com/xtls/xray-core/common/utils"
|
||||||
|
"github.com/xtls/xray-core/common/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
type IPRegistry struct {
|
type IPRegistry struct {
|
||||||
ipsetFactory *IPSetFactory
|
mu sync.Mutex
|
||||||
|
factory *IPSetFactory
|
||||||
|
matchers *utils.WeakCacheMap[uuid.UUID, DynamicIPMatcher]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *IPRegistry) BuildIPMatcher(rules []*IPRule) (IPMatcher, error) {
|
func (r *IPRegistry) BuildIPMatcher(rules []*IPRule) (IPMatcher, error) {
|
||||||
return buildOptimizedIPMatcher(r.ipsetFactory, rules)
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
|
m, err := buildOptimizedIPMatcher(r.factory, rules)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
d := NewDynamicIPMatcher(rules, m)
|
||||||
|
r.matchers.Store(uuid.New(), d)
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *IPRegistry) Reload() error {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
|
||||||
|
var matchers []*DynamicIPMatcher
|
||||||
|
r.matchers.Range(func(_ uuid.UUID, matcher *DynamicIPMatcher) bool {
|
||||||
|
matchers = append(matchers, matcher)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
errors.LogInfo(context.Background(), "reloading GeoIP data for ", len(matchers), " IP matcher(s)")
|
||||||
|
|
||||||
|
factory := newIPSetFactory()
|
||||||
|
type reloadEntry struct {
|
||||||
|
dynamic *DynamicIPMatcher
|
||||||
|
matcher IPMatcher
|
||||||
|
}
|
||||||
|
reloaded := make([]reloadEntry, len(matchers))
|
||||||
|
for i, d := range matchers {
|
||||||
|
m, err := buildOptimizedIPMatcher(factory, d.rules)
|
||||||
|
if err != nil {
|
||||||
|
errors.LogErrorInner(context.Background(), err, "failed to reload GeoIP data for IP matcher ", i)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
reloaded[i] = reloadEntry{dynamic: d, matcher: m}
|
||||||
|
}
|
||||||
|
for _, entry := range reloaded {
|
||||||
|
entry.dynamic.Reload(entry.matcher)
|
||||||
|
}
|
||||||
|
r.factory = factory
|
||||||
|
errors.LogInfo(context.Background(), "reloaded GeoIP data for ", len(matchers), " IP matcher(s)")
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newIPRegistry() *IPRegistry {
|
func newIPRegistry() *IPRegistry {
|
||||||
return &IPRegistry{
|
return &IPRegistry{
|
||||||
ipsetFactory: &IPSetFactory{shared: make(map[string]*IPSet)},
|
factory: newIPSetFactory(),
|
||||||
|
matchers: utils.NewWeakCacheMap[uuid.UUID, DynamicIPMatcher](),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var IPReg = newIPRegistry()
|
var IPReg = newIPRegistry()
|
||||||
|
|
||||||
|
type ipMatcherState struct {
|
||||||
|
matcher IPMatcher
|
||||||
|
}
|
||||||
|
|
||||||
|
type DynamicIPMatcher struct {
|
||||||
|
rules []*IPRule
|
||||||
|
state atomic.Pointer[ipMatcherState]
|
||||||
|
mu sync.Mutex
|
||||||
|
reverse bool
|
||||||
|
reverseSet bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match implements IPMatcher.
|
||||||
|
func (d *DynamicIPMatcher) Match(ip net.IP) bool {
|
||||||
|
return d.state.Load().matcher.Match(ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AnyMatch implements IPMatcher.
|
||||||
|
func (d *DynamicIPMatcher) AnyMatch(ips []net.IP) bool {
|
||||||
|
return d.state.Load().matcher.AnyMatch(ips)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Matches implements IPMatcher.
|
||||||
|
func (d *DynamicIPMatcher) Matches(ips []net.IP) bool {
|
||||||
|
return d.state.Load().matcher.Matches(ips)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterIPs implements IPMatcher.
|
||||||
|
func (d *DynamicIPMatcher) FilterIPs(ips []net.IP) (matched []net.IP, unmatched []net.IP) {
|
||||||
|
return d.state.Load().matcher.FilterIPs(ips)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToggleReverse implements IPMatcher.
|
||||||
|
func (d *DynamicIPMatcher) ToggleReverse() {
|
||||||
|
d.mu.Lock()
|
||||||
|
defer d.mu.Unlock()
|
||||||
|
|
||||||
|
d.reverse = !d.reverse
|
||||||
|
d.state.Load().matcher.ToggleReverse()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetReverse implements IPMatcher.
|
||||||
|
func (d *DynamicIPMatcher) SetReverse(reverse bool) {
|
||||||
|
d.mu.Lock()
|
||||||
|
defer d.mu.Unlock()
|
||||||
|
|
||||||
|
d.reverse = reverse
|
||||||
|
d.reverseSet = true
|
||||||
|
d.state.Load().matcher.SetReverse(reverse)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *DynamicIPMatcher) Reload(newMatcher IPMatcher) {
|
||||||
|
d.mu.Lock()
|
||||||
|
defer d.mu.Unlock()
|
||||||
|
|
||||||
|
if d.reverseSet {
|
||||||
|
newMatcher.SetReverse(d.reverse)
|
||||||
|
} else if d.reverse {
|
||||||
|
newMatcher.ToggleReverse()
|
||||||
|
}
|
||||||
|
d.state.Store(&ipMatcherState{matcher: newMatcher})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDynamicIPMatcher(rules []*IPRule, matcher IPMatcher) *DynamicIPMatcher {
|
||||||
|
d := &DynamicIPMatcher{rules: rules}
|
||||||
|
d.Reload(matcher)
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
luar "layeh.com/gopher-luar"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RegisterLua makes xray.geodata available to require in an LState.
|
||||||
|
func RegisterLua(L *lua.LState) {
|
||||||
|
L.PreloadModule("xray.geodata", func(L *lua.LState) int {
|
||||||
|
module := L.NewTable()
|
||||||
|
|
||||||
|
module.RawSetString("BuildDomainMatcher", L.NewFunction(func(L *lua.LState) int {
|
||||||
|
parsed, err := ParseDomainRules(luaRules(L), Domain_Domain)
|
||||||
|
if err != nil {
|
||||||
|
L.RaiseError("%v", err)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
matcher, err := DomainReg.BuildDomainMatcher(parsed)
|
||||||
|
if err != nil {
|
||||||
|
L.RaiseError("%v", err)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
L.Push(luar.New(L, matcher))
|
||||||
|
return 1
|
||||||
|
}))
|
||||||
|
|
||||||
|
module.RawSetString("BuildIPMatcher", L.NewFunction(func(L *lua.LState) int {
|
||||||
|
parsed, err := ParseIPRules(luaRules(L))
|
||||||
|
if err != nil {
|
||||||
|
L.RaiseError("%v", err)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
matcher, err := IPReg.BuildIPMatcher(parsed)
|
||||||
|
if err != nil {
|
||||||
|
L.RaiseError("%v", err)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
L.Push(luar.New(L, matcher))
|
||||||
|
return 1
|
||||||
|
}))
|
||||||
|
L.Push(module)
|
||||||
|
return 1
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func luaRules(L *lua.LState) []string {
|
||||||
|
rules := make([]string, L.GetTop())
|
||||||
|
for i := range rules {
|
||||||
|
value, ok := L.Get(i + 1).(lua.LString)
|
||||||
|
if !ok {
|
||||||
|
L.RaiseError("geodata rules must be strings")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
rules[i] = string(value)
|
||||||
|
}
|
||||||
|
return rules
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
lua "github.com/yuin/gopher-lua"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLuaIPMatcher(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
RegisterLua(L)
|
||||||
|
ip := L.NewUserData()
|
||||||
|
ip.Value = net.ParseIP("127.0.0.1")
|
||||||
|
L.SetGlobal("ip", ip)
|
||||||
|
ips := L.NewUserData()
|
||||||
|
ips.Value = []net.IP{ip.Value.(net.IP), net.ParseIP("8.8.8.8")}
|
||||||
|
L.SetGlobal("ips", ips)
|
||||||
|
if err := L.DoString(`
|
||||||
|
local matcher = require("xray.geodata").BuildIPMatcher("127.0.0.0/8", "::1")
|
||||||
|
assert(matcher:Match(ip))
|
||||||
|
assert(matcher:AnyMatch(ips))
|
||||||
|
assert(not matcher:Matches(ips))
|
||||||
|
local matched, unmatched = matcher:FilterIPs(ips)
|
||||||
|
assert(type(matched) == "userdata" and type(unmatched) == "userdata")
|
||||||
|
assert(#matched == 1 and #unmatched == 1)
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLuaDomainMatcher(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
RegisterLua(L)
|
||||||
|
if err := L.DoString(`
|
||||||
|
local matcher = require("xray.geodata").BuildDomainMatcher("example.com", "full:other.com")
|
||||||
|
assert(matcher:MatchAny("example.com"))
|
||||||
|
assert(matcher:MatchAny("www.example.com"))
|
||||||
|
assert(matcher:MatchAny("other.com"))
|
||||||
|
assert(not matcher:MatchAny("www.other.com"))
|
||||||
|
assert(#(matcher:Match("www.example.com")) == 1)
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLuaMatchersRejectInvalidRules(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
script string
|
||||||
|
}{
|
||||||
|
{"IP rule", `require("xray.geodata").BuildIPMatcher("not-an-ip")`},
|
||||||
|
{"non-string domain rule", `require("xray.geodata").BuildDomainMatcher("example.com", true)`},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
L := lua.NewState()
|
||||||
|
defer L.Close()
|
||||||
|
RegisterLua(L)
|
||||||
|
if err := L.DoString(tc.script); err == nil {
|
||||||
|
t.Fatal("invalid geodata rule was accepted")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,8 @@ func ParseIPRules(rules []string) ([]*IPRule, error) {
|
|||||||
var ipRules []*IPRule
|
var ipRules []*IPRule
|
||||||
|
|
||||||
for i, r := range rules {
|
for i, r := range rules {
|
||||||
|
r, reverse := cutReversePrefix(r)
|
||||||
|
|
||||||
if strings.HasPrefix(r, "geoip:") {
|
if strings.HasPrefix(r, "geoip:") {
|
||||||
r = "ext:" + DefaultGeoIPDat + ":" + r[len("geoip:"):]
|
r = "ext:" + DefaultGeoIPDat + ":" + r[len("geoip:"):]
|
||||||
}
|
}
|
||||||
@@ -32,9 +34,9 @@ func ParseIPRules(rules []string) ([]*IPRule, error) {
|
|||||||
var rule isIPRule_Value
|
var rule isIPRule_Value
|
||||||
var err error
|
var err error
|
||||||
if prefix > 0 {
|
if prefix > 0 {
|
||||||
rule, err = parseGeoIPRule(r[prefix:])
|
rule, err = parseGeoIPRule(r[prefix:], reverse)
|
||||||
} else {
|
} else {
|
||||||
rule, err = parseCustomIPRule(r)
|
rule, err = parseCustomIPRule(r, reverse)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("illegal ip rule: ", rules[i]).Base(err)
|
return nil, errors.New("illegal ip rule: ", rules[i]).Base(err)
|
||||||
@@ -45,7 +47,16 @@ func ParseIPRules(rules []string) ([]*IPRule, error) {
|
|||||||
return ipRules, nil
|
return ipRules, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseGeoIPRule(rule string) (*IPRule_Geoip, error) {
|
func cutReversePrefix(s string) (string, bool) {
|
||||||
|
reverse := false
|
||||||
|
for strings.HasPrefix(s, "!") {
|
||||||
|
s = s[1:]
|
||||||
|
reverse = !reverse
|
||||||
|
}
|
||||||
|
return s, reverse
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseGeoIPRule(rule string, reverse bool) (*IPRule_Geoip, error) {
|
||||||
file, code, ok := strings.Cut(rule, ":")
|
file, code, ok := strings.Cut(rule, ":")
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, errors.New("syntax error")
|
return nil, errors.New("syntax error")
|
||||||
@@ -55,11 +66,8 @@ func parseGeoIPRule(rule string) (*IPRule_Geoip, error) {
|
|||||||
return nil, errors.New("empty file")
|
return nil, errors.New("empty file")
|
||||||
}
|
}
|
||||||
|
|
||||||
reverse := false
|
code, codeReverse := cutReversePrefix(code)
|
||||||
if strings.HasPrefix(code, "!") {
|
reverse = reverse != codeReverse
|
||||||
code = code[1:]
|
|
||||||
reverse = true
|
|
||||||
}
|
|
||||||
if code == "" {
|
if code == "" {
|
||||||
return nil, errors.New("empty code")
|
return nil, errors.New("empty code")
|
||||||
}
|
}
|
||||||
@@ -78,13 +86,16 @@ func parseGeoIPRule(rule string) (*IPRule_Geoip, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseCustomIPRule(rule string) (*IPRule_Custom, error) {
|
func parseCustomIPRule(rule string, reverse bool) (*IPRule_Custom, error) {
|
||||||
cidr, err := parseCIDR(rule)
|
cidr, err := parseCIDR(rule)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &IPRule_Custom{
|
return &IPRule_Custom{
|
||||||
Custom: cidr,
|
Custom: &CIDRRule{
|
||||||
|
Cidr: cidr,
|
||||||
|
ReverseMatch: reverse,
|
||||||
|
},
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,7 +138,7 @@ func ParseDomainRule(r string, defaultType Domain_Type) (*DomainRule, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
prefix := 0
|
prefix := 0
|
||||||
for _, ext := range [...]string{"ext:", "ext-domain:"} {
|
for _, ext := range [...]string{"ext:", "ext-domain:", "ext-site:"} {
|
||||||
if strings.HasPrefix(r, ext) {
|
if strings.HasPrefix(r, ext) {
|
||||||
prefix = len(ext)
|
prefix = len(ext)
|
||||||
break
|
break
|
||||||
@@ -156,7 +167,7 @@ func ParseDomainRules(rules []string, defaultType Domain_Type) ([]*DomainRule, e
|
|||||||
}
|
}
|
||||||
|
|
||||||
prefix := 0
|
prefix := 0
|
||||||
for _, ext := range [...]string{"ext:", "ext-domain:"} {
|
for _, ext := range [...]string{"ext:", "ext-domain:", "ext-site:"} {
|
||||||
if strings.HasPrefix(r, ext) {
|
if strings.HasPrefix(r, ext) {
|
||||||
prefix = len(ext)
|
prefix = len(ext)
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -13,12 +13,20 @@ func TestParseIPRules(t *testing.T) {
|
|||||||
rules := []string{
|
rules := []string{
|
||||||
"geoip:us",
|
"geoip:us",
|
||||||
"geoip:cn",
|
"geoip:cn",
|
||||||
|
"!geoip:cn",
|
||||||
|
"!!geoip:cn",
|
||||||
"geoip:!cn",
|
"geoip:!cn",
|
||||||
|
"geoip:!!cn",
|
||||||
|
"!geoip:!cn",
|
||||||
"ext:geoip.dat:!cn",
|
"ext:geoip.dat:!cn",
|
||||||
|
"ext:geoip.dat:!!cn",
|
||||||
"ext:geoip.dat:ca",
|
"ext:geoip.dat:ca",
|
||||||
"ext-ip:geoip.dat:!cn",
|
"ext-ip:geoip.dat:!cn",
|
||||||
"ext-ip:geoip.dat:!ca",
|
"ext-ip:geoip.dat:!ca",
|
||||||
"192.168.0.0/24",
|
"192.168.0.0/24",
|
||||||
|
"!192.168.0.0/24",
|
||||||
|
"!!192.168.0.0/24",
|
||||||
|
"!!!192.168.0.0/24",
|
||||||
"192.168.0.1",
|
"192.168.0.1",
|
||||||
"fe80::/64",
|
"fe80::/64",
|
||||||
"fe80::",
|
"fe80::",
|
||||||
@@ -30,6 +38,53 @@ func TestParseIPRules(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestParseIPRuleReverse(t *testing.T) {
|
||||||
|
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||||
|
|
||||||
|
for _, tt := range []struct {
|
||||||
|
rule string
|
||||||
|
reverse bool
|
||||||
|
}{
|
||||||
|
{rule: "!192.168.0.0/24", reverse: true},
|
||||||
|
{rule: "!!192.168.0.0/24", reverse: false},
|
||||||
|
{rule: "!!!192.168.0.0/24", reverse: true},
|
||||||
|
{rule: "!!!!192.168.0.0/24", reverse: false},
|
||||||
|
{rule: "geoip:cn", reverse: false},
|
||||||
|
{rule: "!geoip:cn", reverse: true},
|
||||||
|
{rule: "!!geoip:cn", reverse: false},
|
||||||
|
{rule: "geoip:!cn", reverse: true},
|
||||||
|
{rule: "geoip:!!cn", reverse: false},
|
||||||
|
{rule: "!geoip:!cn", reverse: false},
|
||||||
|
{rule: "!!geoip:!cn", reverse: true},
|
||||||
|
{rule: "!geoip:!!cn", reverse: true},
|
||||||
|
{rule: "ext:geoip.dat:!!!cn", reverse: true},
|
||||||
|
} {
|
||||||
|
t.Run(tt.rule, func(t *testing.T) {
|
||||||
|
rules, err := geodata.ParseIPRules([]string{tt.rule})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Failed to parse ip rules, got %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(rules) != 1 {
|
||||||
|
t.Fatalf("Expected 1 rule, got %d", len(rules))
|
||||||
|
}
|
||||||
|
|
||||||
|
switch rule := rules[0]; {
|
||||||
|
case rule.GetGeoip() != nil:
|
||||||
|
if rule.GetGeoip().GetReverseMatch() != tt.reverse {
|
||||||
|
t.Fatalf("Expected geoip reverse match to be %t", tt.reverse)
|
||||||
|
}
|
||||||
|
case rule.GetCustom() != nil:
|
||||||
|
if rule.GetCustom().GetReverseMatch() != tt.reverse {
|
||||||
|
t.Fatalf("Expected custom reverse match to be %t", tt.reverse)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
t.Fatal("Expected ip rule")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestParseDomainRules(t *testing.T) {
|
func TestParseDomainRules(t *testing.T) {
|
||||||
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
t.Setenv("xray.location.asset", filepath.Join("..", "..", "resources"))
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package strmatcher
|
||||||
|
|
||||||
|
// LinearAnyMatcher is an implementation of AnyMatcher.
|
||||||
|
type LinearAnyMatcher struct {
|
||||||
|
full *FullMatcherSet
|
||||||
|
domain *DomainMatcherSet
|
||||||
|
substr *SubstrMatcherSet
|
||||||
|
regex *SimpleMatcherSet
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLinearAnyMatcher() *LinearAnyMatcher {
|
||||||
|
return new(LinearAnyMatcher)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add implements AnyMatcher.Add.
|
||||||
|
func (s *LinearAnyMatcher) Add(matcher Matcher) {
|
||||||
|
switch matcher := matcher.(type) {
|
||||||
|
case FullMatcher:
|
||||||
|
if s.full == nil {
|
||||||
|
s.full = NewFullMatcherSet()
|
||||||
|
}
|
||||||
|
s.full.AddFullMatcher(matcher)
|
||||||
|
case DomainMatcher:
|
||||||
|
if s.domain == nil {
|
||||||
|
s.domain = NewDomainMatcherSet()
|
||||||
|
}
|
||||||
|
s.domain.AddDomainMatcher(matcher)
|
||||||
|
case SubstrMatcher:
|
||||||
|
if s.substr == nil {
|
||||||
|
s.substr = new(SubstrMatcherSet)
|
||||||
|
}
|
||||||
|
s.substr.AddSubstrMatcher(matcher)
|
||||||
|
default:
|
||||||
|
if s.regex == nil {
|
||||||
|
s.regex = new(SimpleMatcherSet)
|
||||||
|
}
|
||||||
|
s.regex.AddMatcher(matcher)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatchAny implements AnyMatcher.MatchAny.
|
||||||
|
func (s *LinearAnyMatcher) MatchAny(input string) bool {
|
||||||
|
if s.full != nil && s.full.MatchAny(input) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if s.domain != nil && s.domain.MatchAny(input) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if s.substr != nil && s.substr.MatchAny(input) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return s.regex != nil && s.regex.MatchAny(input)
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package strmatcher
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
@@ -99,10 +100,6 @@ func (t Type) New(pattern string) (Matcher, error) {
|
|||||||
case Substr:
|
case Substr:
|
||||||
return SubstrMatcher(pattern), nil
|
return SubstrMatcher(pattern), nil
|
||||||
case Domain:
|
case Domain:
|
||||||
pattern, err := ToDomain(pattern)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return DomainMatcher(pattern), nil
|
return DomainMatcher(pattern), nil
|
||||||
case Regex: // 1. regex matching is case-sensitive
|
case Regex: // 1. regex matching is case-sensitive
|
||||||
regex, err := regexp.Compile(pattern)
|
regex, err := regexp.Compile(pattern)
|
||||||
@@ -253,13 +250,12 @@ func AddMatcherToGroup(g MatcherGroup, matcher Matcher, value uint32) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// CompositeMatches flattens the matches slice to produce a single matched indices slice.
|
// CompositeMatches flattens the matches slice to produce a single matched indices slice.
|
||||||
// It is designed to avoid new memory allocation as possible.
|
|
||||||
func CompositeMatches(matches [][]uint32) []uint32 {
|
func CompositeMatches(matches [][]uint32) []uint32 {
|
||||||
switch len(matches) {
|
switch len(matches) {
|
||||||
case 0:
|
case 0:
|
||||||
return nil
|
return nil
|
||||||
case 1:
|
case 1:
|
||||||
return matches[0]
|
return slices.Clone(matches[0])
|
||||||
default:
|
default:
|
||||||
result := make([]uint32, 0, 5)
|
result := make([]uint32, 0, 5)
|
||||||
for i := 0; i < len(matches); i++ {
|
for i := 0; i < len(matches); i++ {
|
||||||
@@ -288,3 +284,65 @@ func CompositeMatchesReverse(matches [][]uint32) []uint32 {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MatcherSetForAll is an interface indicating a MatcherSet could accept all types of matchers.
|
||||||
|
type MatcherSetForAll interface {
|
||||||
|
AddMatcher(matcher Matcher)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatcherSetForFull is an interface indicating a MatcherSet could accept FullMatchers.
|
||||||
|
type MatcherSetForFull interface {
|
||||||
|
AddFullMatcher(matcher FullMatcher)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatcherSetForDomain is an interface indicating a MatcherSet could accept DomainMatchers.
|
||||||
|
type MatcherSetForDomain interface {
|
||||||
|
AddDomainMatcher(matcher DomainMatcher)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatcherSetForSubstr is an interface indicating a MatcherSet could accept SubstrMatchers.
|
||||||
|
type MatcherSetForSubstr interface {
|
||||||
|
AddSubstrMatcher(matcher SubstrMatcher)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatcherSetForRegex is an interface indicating a MatcherSet could accept RegexMatchers.
|
||||||
|
type MatcherSetForRegex interface {
|
||||||
|
AddRegexMatcher(matcher *RegexMatcher)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddMatcherToSet is a helper function to try to add a Matcher to any kind of MatcherSet.
|
||||||
|
// It returns error if the MatcherSet does not accept the provided Matcher's type.
|
||||||
|
// This function is provided to help writing code to test a MatcherSet.
|
||||||
|
func AddMatcherToSet(s MatcherSet, matcher Matcher) error {
|
||||||
|
if s, ok := s.(IndexMatcher); ok {
|
||||||
|
s.Add(matcher)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if s, ok := s.(MatcherSetForAll); ok {
|
||||||
|
s.AddMatcher(matcher)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch matcher := matcher.(type) {
|
||||||
|
case FullMatcher:
|
||||||
|
if s, ok := s.(MatcherSetForFull); ok {
|
||||||
|
s.AddFullMatcher(matcher)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
case DomainMatcher:
|
||||||
|
if s, ok := s.(MatcherSetForDomain); ok {
|
||||||
|
s.AddDomainMatcher(matcher)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
case SubstrMatcher:
|
||||||
|
if s, ok := s.(MatcherSetForSubstr); ok {
|
||||||
|
s.AddSubstrMatcher(matcher)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
case *RegexMatcher:
|
||||||
|
if s, ok := s.(MatcherSetForRegex); ok {
|
||||||
|
s.AddRegexMatcher(matcher)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errors.New("cannot add matcher to matcher set")
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package strmatcher
|
||||||
|
|
||||||
|
type trieNode2 struct {
|
||||||
|
matched bool
|
||||||
|
children map[string]*trieNode2
|
||||||
|
}
|
||||||
|
|
||||||
|
// DomainMatcherSet is an implementation of MatcherSet.
|
||||||
|
// It uses trie to optimize both memory consumption and lookup speed. Trie node is domain label based.
|
||||||
|
type DomainMatcherSet struct {
|
||||||
|
root *trieNode2
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDomainMatcherSet() *DomainMatcherSet {
|
||||||
|
return &DomainMatcherSet{
|
||||||
|
root: new(trieNode2),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddDomainMatcher implements MatcherSetForDomain.AddDomainMatcher.
|
||||||
|
func (s *DomainMatcherSet) AddDomainMatcher(matcher DomainMatcher) {
|
||||||
|
node := s.root
|
||||||
|
pattern := matcher.Pattern()
|
||||||
|
for i := len(pattern); i > 0; {
|
||||||
|
var part string
|
||||||
|
for j := i - 1; ; j-- {
|
||||||
|
if pattern[j] == '.' {
|
||||||
|
part = pattern[j+1 : i]
|
||||||
|
i = j
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if j == 0 {
|
||||||
|
part = pattern[j:i]
|
||||||
|
i = j
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if node.children == nil {
|
||||||
|
node.children = make(map[string]*trieNode2)
|
||||||
|
}
|
||||||
|
next := node.children[part]
|
||||||
|
if next == nil {
|
||||||
|
next = new(trieNode2)
|
||||||
|
node.children[part] = next
|
||||||
|
}
|
||||||
|
node = next
|
||||||
|
}
|
||||||
|
|
||||||
|
node.matched = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatchAny implements MatcherSet.MatchAny.
|
||||||
|
func (s *DomainMatcherSet) MatchAny(input string) bool {
|
||||||
|
node := s.root
|
||||||
|
for i := len(input); i > 0; {
|
||||||
|
for j := i - 1; ; j-- {
|
||||||
|
if input[j] == '.' {
|
||||||
|
node = node.children[input[j+1:i]]
|
||||||
|
i = j
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if j == 0 {
|
||||||
|
node = node.children[input[j:i]]
|
||||||
|
i = j
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if node == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if node.matched {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if node.children == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package strmatcher_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
. "github.com/xtls/xray-core/common/geodata/strmatcher"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDomainMatcherSet(t *testing.T) {
|
||||||
|
patterns := []struct {
|
||||||
|
Pattern string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Pattern: "example.com",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Pattern: "google.com",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Pattern: "x.a.com",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Pattern: "a.b.com",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Pattern: "c.a.b.com",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Pattern: "x.y.com",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Pattern: "x.y.com",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
testCases := []struct {
|
||||||
|
Domain string
|
||||||
|
Result bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
Domain: "x.example.com",
|
||||||
|
Result: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Domain: "y.com",
|
||||||
|
Result: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Domain: "a.b.com",
|
||||||
|
Result: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Domain: "c.a.b.com",
|
||||||
|
Result: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Domain: "c.a..b.com",
|
||||||
|
Result: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Domain: ".com",
|
||||||
|
Result: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Domain: "com",
|
||||||
|
Result: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Domain: "",
|
||||||
|
Result: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Domain: "x.y.com",
|
||||||
|
Result: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
s := NewDomainMatcherSet()
|
||||||
|
for _, pattern := range patterns {
|
||||||
|
AddMatcherToSet(s, DomainMatcher(pattern.Pattern))
|
||||||
|
}
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
r := s.MatchAny(testCase.Domain)
|
||||||
|
if !reflect.DeepEqual(r, testCase.Result) {
|
||||||
|
t.Error("Failed to match domain: ", testCase.Domain, ", expect ", testCase.Result, ", but got ", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEmptyDomainMatcherSet(t *testing.T) {
|
||||||
|
s := NewDomainMatcherSet()
|
||||||
|
r := s.MatchAny("example.com")
|
||||||
|
if r {
|
||||||
|
t.Error("Expect false, but ", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package strmatcher
|
||||||
|
|
||||||
|
// FullMatcherSet is an implementation of MatcherSet.
|
||||||
|
// It uses a hash table to facilitate exact match lookup.
|
||||||
|
type FullMatcherSet struct {
|
||||||
|
matchers map[string]struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFullMatcherSet() *FullMatcherSet {
|
||||||
|
return &FullMatcherSet{
|
||||||
|
matchers: make(map[string]struct{}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddFullMatcher implements MatcherSetForFull.AddFullMatcher.
|
||||||
|
func (s *FullMatcherSet) AddFullMatcher(matcher FullMatcher) {
|
||||||
|
s.matchers[matcher.Pattern()] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MatchAny implements MatcherSet.Any.
|
||||||
|
func (s *FullMatcherSet) MatchAny(input string) bool {
|
||||||
|
_, found := s.matchers[input]
|
||||||
|
return found
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user