mirror of
https://github.com/2dust/v2rayN.git
synced 2026-11-16 01:15:01 +03:00
Compare commits
369 Commits
e6d08c2db1
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| c374f26d28 | |||
| f5bdbe3466 | |||
| 9f599c60a7 | |||
| 4e40d5f5f7 | |||
| 41231533b1 | |||
| 254b39bc45 | |||
| a6624e0370 | |||
| 33fa9865e6 | |||
| 2c90ed1a94 | |||
| 5292568150 | |||
| 49963a1662 | |||
| a42642d334 | |||
| f64c29972d | |||
| 18de5da98a | |||
| 9c7c169056 | |||
| f2f336d97c | |||
| a189c659c6 | |||
| 2faf09b842 | |||
| 480558d58e | |||
| 28f8ca7ba1 | |||
| 0734317f9f | |||
| 6288b3909e | |||
| d5338f673c | |||
| cbb8721d8a | |||
| 1eae1375bc | |||
| ddf7582b72 | |||
| 750f2fa7db | |||
| e57e122770 | |||
| e3457fa4b4 | |||
| 7188f36e44 | |||
| cdcac0404a | |||
| cc28308bd4 | |||
| f07e3dc415 | |||
| 0f71c46d3b | |||
| 968beb4432 | |||
| 1e167449ea | |||
| 73670c70d5 | |||
| 5ca37027fd | |||
| 54ecc045b5 | |||
| 92a9da8b6b | |||
| 6e48e507ea | |||
| 91d1cbe55a | |||
| f1ef8dfbe6 | |||
| 5d2e339e6d | |||
| 5211b9ce0e | |||
| c01224c37d | |||
| 052f6f0fec | |||
| 2010477f38 | |||
| 7c49b236a0 | |||
| b8458fdb7f | |||
| 92aa3ba6dd | |||
| 15ed51f942 | |||
| 8027b2cf72 | |||
| 66546700b0 | |||
| 9a029a3f7e | |||
| aa00b2c614 | |||
| 2239982a63 | |||
| 0d9e84556e | |||
| 9d1063f3f2 | |||
| 749a7312d7 | |||
| ff9fd7b988 | |||
| fe54a73d74 | |||
| 281f5ee3c7 | |||
| a74d10babb | |||
| 522bca492c | |||
| 0f1f82af4e | |||
| 3d0f45f6a8 | |||
| 19850f92be | |||
| 4c4449e74d | |||
| 59487dca75 | |||
| d4880dbe02 | |||
| 0856ffd7d8 | |||
| c436b998b4 | |||
| 7a52be4150 | |||
| 8c02b5f2f6 | |||
| 743eb323c2 | |||
| ebabf79017 | |||
| 756916978d | |||
| a2a8a77ff6 | |||
| 2bc79bc5a1 | |||
| 4c8b865d03 | |||
| 3d44ba8ec8 | |||
| aac4520f59 | |||
| b13ae2592a | |||
| bf2584c9a9 | |||
| e044b90c83 | |||
| 3dce503a08 | |||
| 70ab27e436 | |||
| 9593b289b9 | |||
| 5664270be7 | |||
| 926790b071 | |||
| e1c9633535 | |||
| 36184045bb | |||
| fcd313007a | |||
| 7e14cf9773 | |||
| ad3e24b6b5 | |||
| 4169c12a1f | |||
| 8b93d35766 | |||
| 78b0b2224b | |||
| e2f4292321 | |||
| 57f17d5939 | |||
| 66dd7da6e6 | |||
| 5e0ea3275d | |||
| 673283da4b | |||
| 1f083adbe4 | |||
| 80ab14d057 | |||
| 95f438abc9 | |||
| f1023e08e1 | |||
| 1883178b5f | |||
| 1cde521d75 | |||
| 2407d44f4f | |||
| fbf822d74c | |||
| 4869a6cbba | |||
| b501efbc45 | |||
| 5ea8ae6420 | |||
| fa9d4a4769 | |||
| 771ef3192a | |||
| f5747bb321 | |||
| d099e44ff6 | |||
| c63d271d16 | |||
| 6152cab494 | |||
| 3187eeef79 | |||
| 3364ec0e57 | |||
| 23033fa002 | |||
| 125cbb18a1 | |||
| f85326cf0e | |||
| 3666fc549d | |||
| a147249f95 | |||
| a28f68c3a7 | |||
| 1a689f869c | |||
| 50023a5976 | |||
| c659ca8af8 | |||
| 7d6a967c18 | |||
| 6c2edcb382 | |||
| 086c991464 | |||
| a9da04acc2 | |||
| e0c790eeb2 | |||
| d433aa3b04 | |||
| 91a7ed65d5 | |||
| 984e685ab3 | |||
| 29f99ceacc | |||
| 93d8174dbe | |||
| fa1e201c76 | |||
| e1cb99cd6e | |||
| 28139853a8 | |||
| 5d9718a0bb | |||
| 740729c847 | |||
| 13cd2ef80d | |||
| be3566df2f | |||
| 6e9ec6cbee | |||
| e6e95e00d7 | |||
| 2fbe81041b | |||
| 05901b5673 | |||
| bdd0ee1620 | |||
| 00d1001def | |||
| 21bafe52e0 | |||
| cef40d38ee | |||
| 4f5a6be12d | |||
| 7674d7e472 | |||
| 77c462ec7b | |||
| 526cd6834d | |||
| 7be23d7ebc | |||
| d952c180c9 | |||
| 80fa6575a3 | |||
| f05e44d7d9 | |||
| b10c16a94a | |||
| 143ada1358 | |||
| d8c7bd9d02 | |||
| 85666af36a | |||
| 7286c67a78 | |||
| 8b8e579bc8 | |||
| ed4dd7f6d9 | |||
| bb62c9eda5 | |||
| 3d50d9f82c | |||
| d05c3439f8 | |||
| cb5ae8c900 | |||
| ec6a7b3db2 | |||
| 99328a14d2 | |||
| 8ebbd7f4f8 | |||
| b8e8321603 | |||
| fe2e219b7a | |||
| df32b4d6cc | |||
| 9451b69246 | |||
| 4a59c7f4d6 | |||
| fed59a7313 | |||
| 093b8d4c34 | |||
| f03db020fa | |||
| f62eaab8c5 | |||
| 1bf3d14771 | |||
| 64aad8027a | |||
| 7870ae89cf | |||
| 521230c40d | |||
| 426d5d5a21 | |||
| 3f14c86a04 | |||
| 70b8ecd3c8 | |||
| 0d452328a2 | |||
| 2a65e5ac80 | |||
| f332caf507 | |||
| 4b412e246f | |||
| 09ac4d181a | |||
| c575527725 | |||
| 589ccc6e06 | |||
| 0a2f3e4f22 | |||
| 007adb6403 | |||
| e50c0a9170 | |||
| af0eb9ed14 | |||
| 0436081436 | |||
| 2a89a2e597 | |||
| 2be63d1655 | |||
| 74bd28bbd0 | |||
| be501cbd2a | |||
| e20b4dbfab | |||
| 728cbe70f2 | |||
| 26a86f9bd2 | |||
| c66c55b05e | |||
| ebb4bd5daa | |||
| 14e27f3d23 | |||
| 2d514ff480 | |||
| 11bd52b6a5 | |||
| 3b3fe8def3 | |||
| c9e843aa3b | |||
| 7be264c65c | |||
| 5e6660aeee | |||
| 5b27f4836f | |||
| e0ad2c46e6 | |||
| 230a2f6773 | |||
| e7cc4c832e | |||
| fb7033aab5 | |||
| b6cc3913ac | |||
| bc06a5dc21 | |||
| 9c1951178c | |||
| b3df42b9ba | |||
| e01717d832 | |||
| 8b4063b44b | |||
| 3136f573dd | |||
| e101b1d7b0 | |||
| 31044f449d | |||
| eacf8b0784 | |||
| f347fe1c03 | |||
| 71208eb711 | |||
| 339eaa6bfd | |||
| 717ef7f0a7 | |||
| 4a9d83f9dc | |||
| 1ac14d0903 | |||
| 08d423e1b4 | |||
| 9638b4c368 | |||
| 1034ce6e02 | |||
| 5efff37acb | |||
| e8cdd1cc02 | |||
| d381d429e4 | |||
| b27ae11d1e | |||
| eff584597f | |||
| ccf18ba0fb | |||
| 15ba2bdf93 | |||
| e1e6c5ddb0 | |||
| d924c6f557 | |||
| 635a04d74c | |||
| 2e1bb23da7 | |||
| 6f3bacd5b4 | |||
| 074ce5de04 | |||
| 02df430172 | |||
| 611ce0fd2c | |||
| a846e74e8f | |||
| 92c3df45ae | |||
| ee7e21268a | |||
| dc216c2b02 | |||
| beffa919d3 | |||
| a654826231 | |||
| b01476d147 | |||
| cf8dd45abe | |||
| 9bba6f53f8 | |||
| cd77f1d882 | |||
| 0427037638 | |||
| e749b81ecf | |||
| fd2c942231 | |||
| fa42eb670f | |||
| 0d42996573 | |||
| a37772f12b | |||
| 531e0e9443 | |||
| 984c77f0c4 | |||
| b5e0be47a5 | |||
| 6df0e6de1b | |||
| 2b5328665f | |||
| 4584ecc5c9 | |||
| d9dc2d7cf5 | |||
| 36f8565b7a | |||
| f55d8b2565 | |||
| 09ea4890a7 | |||
| 5cc2aaba13 | |||
| b8889bad86 | |||
| 5dd5b25869 | |||
| fafdb4a0b6 | |||
| 223642dd67 | |||
| 165e0bf9e9 | |||
| e615314582 | |||
| ca9978b625 | |||
| 74ab7ad097 | |||
| 8f5cbad988 | |||
| 1ab9757498 | |||
| 50ab02e8a9 | |||
| b9a1c129c4 | |||
| 996eb51f9b | |||
| b9a58e7137 | |||
| 9664ee380e | |||
| 6f50206606 | |||
| 1de83f96ed | |||
| 994bc1ca6a | |||
| 3ca49dd9db | |||
| a0bd8f9934 | |||
| 88d59488fd | |||
| 2c70b018ce | |||
| b6ab428dfc | |||
| 45ab7503e3 | |||
| 1768b4a7ee | |||
| 3e9f78f831 | |||
| 8c4bd52389 | |||
| fa61fedf11 | |||
| ad12a6c456 | |||
| 66b48c231f | |||
| 52766d66bf | |||
| e1a5c360ac | |||
| 0c570fcb38 | |||
| a236fab27c | |||
| f8e1186095 | |||
| ca186e2636 | |||
| 1e8ba9ad9b | |||
| 31e32f174e | |||
| bf376a8fac | |||
| 5a9a9b7ab1 | |||
| e7a9aa66dc | |||
| 709b9a0958 | |||
| 191fe48257 | |||
| 48d58d482a | |||
| 7100b3f0a5 | |||
| 8d94997ba0 | |||
| c97dc1d894 | |||
| b198fd8be7 | |||
| e0c1ff24be | |||
| 3cebf492d1 | |||
| ef46f4e7e6 | |||
| 81c118c9b2 | |||
| f1b88ccf2a | |||
| ce380b861c | |||
| 46e9e4fead | |||
| 00903d3531 | |||
| 616eea39f9 | |||
| ff456a9389 | |||
| 0d225cd29d | |||
| 67426cff12 | |||
| a8c27027b4 | |||
| 1a681695a2 | |||
| 2126ea5a87 | |||
| be005abf9e | |||
| da7dfde706 | |||
| 7491e86d80 | |||
| af037ed087 | |||
| c9298db607 | |||
| da81101cfd | |||
| 3d4f202cd7 | |||
| 35fbb137e8 | |||
| 1869a95700 | |||
| 34359885ab | |||
| 93832656dd | |||
| b1a400b393 | |||
| 879c736924 | |||
| 8147b39723 | |||
| 5fed566a32 | |||
| f0ee792778 | |||
| cd4aa5531c |
@@ -18,8 +18,8 @@ body:
|
|||||||
- type: input
|
- type: input
|
||||||
id: "os-version"
|
id: "os-version"
|
||||||
attributes:
|
attributes:
|
||||||
label: "操作系统和版本"
|
label: "操作系统 / v2rayN / Core 版本"
|
||||||
description: "操作系统和版本"
|
description: "操作系统 / v2rayN / Core 版本"
|
||||||
validations:
|
validations:
|
||||||
required: true
|
required: true
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,6 @@ updates:
|
|||||||
interval: "daily"
|
interval: "daily"
|
||||||
|
|
||||||
- package-ecosystem: "nuget"
|
- package-ecosystem: "nuget"
|
||||||
directory: "/"
|
directory: "/v2rayN"
|
||||||
schedule:
|
schedule:
|
||||||
interval: "daily"
|
interval: "daily"
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
/*
|
||||||
|
==============================================================================
|
||||||
|
THIRD-PARTY CA CERTIFICATE DATA ATTRIBUTION
|
||||||
|
==============================================================================
|
||||||
|
|
||||||
|
This component includes CA certificate data obtained from third-party sources.
|
||||||
|
|
||||||
|
1. Common CA Database (CCADB)
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
Website:
|
||||||
|
https://www.ccadb.org/
|
||||||
|
|
||||||
|
Data source:
|
||||||
|
https://ccadb.my.salesforce-sites.com/mozilla/IncludedRootsPEMTxt?TrustBitsInclude=Websites
|
||||||
|
|
||||||
|
License:
|
||||||
|
Community Data License Agreement – Permissive, Version 2.0 (CDLA-2.0 Permissive)
|
||||||
|
|
||||||
|
The names and trademarks of CCADB contributors may not be used to endorse or
|
||||||
|
promote products derived from this data without prior written permission.
|
||||||
|
|
||||||
|
License text:
|
||||||
|
https://cdla.dev/permissive-2-0/
|
||||||
|
|
||||||
|
|
||||||
|
2. Chromium Root Store
|
||||||
|
------------------------------------------------------------------------------
|
||||||
|
Source:
|
||||||
|
Chromium Project
|
||||||
|
|
||||||
|
Data source:
|
||||||
|
https://chromium.googlesource.com/chromium/src/+/main/net/data/ssl/chrome_root_store/root_store.certs?format=TEXT
|
||||||
|
|
||||||
|
License:
|
||||||
|
BSD 3-Clause License
|
||||||
|
|
||||||
|
Copyright:
|
||||||
|
Copyright (c) The Chromium Authors
|
||||||
|
|
||||||
|
The Chromium Root Store data is distributed under the BSD 3-Clause License.
|
||||||
|
|
||||||
|
License text:
|
||||||
|
https://opensource.org/licenses/BSD-3-Clause
|
||||||
|
==============================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.IO;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
var client = new HttpClient { Timeout = TimeSpan.FromMinutes(2) };
|
||||||
|
|
||||||
|
var outputDir = args.Length > 0
|
||||||
|
? args[0]
|
||||||
|
: Path.Combine(Environment.CurrentDirectory, "v2rayN", "ServiceLib", "Sample");
|
||||||
|
|
||||||
|
Directory.CreateDirectory(outputDir);
|
||||||
|
|
||||||
|
Console.WriteLine("=== Mozilla + Chrome Root Store PEM Converter ===\n");
|
||||||
|
Console.WriteLine($"Output directory: {outputDir}\n");
|
||||||
|
|
||||||
|
// Process Mozilla
|
||||||
|
await ProcessMozillaAsync(outputDir);
|
||||||
|
|
||||||
|
// Process Chrome
|
||||||
|
await ProcessChromeAsync(outputDir);
|
||||||
|
|
||||||
|
Console.WriteLine("\nAll done!");
|
||||||
|
|
||||||
|
async Task ProcessMozillaAsync(string outputDir)
|
||||||
|
{
|
||||||
|
const string certdataUrl = "https://ccadb.my.salesforce-sites.com/mozilla/IncludedRootsPEMTxt?TrustBitsInclude=Websites";
|
||||||
|
var outputFile = Path.Combine(outputDir, "mozilla_roots_pem");
|
||||||
|
|
||||||
|
Console.WriteLine("Downloading Mozilla certdata.txt...");
|
||||||
|
var content = await client.GetStringAsync(certdataUrl);
|
||||||
|
|
||||||
|
var pemMatches = Regex.Matches(content, @"(-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----)");
|
||||||
|
var pems = new List<string>();
|
||||||
|
foreach (Match m in pemMatches)
|
||||||
|
{
|
||||||
|
pems.Add(m.Groups[1].Value.Trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
await File.WriteAllTextAsync(outputFile, string.Join("\n\n", pems));
|
||||||
|
Console.WriteLine($"Mozilla roots saved to: {outputFile} ({pems.Count} certificates)");
|
||||||
|
}
|
||||||
|
|
||||||
|
async Task ProcessChromeAsync(string outputDir)
|
||||||
|
{
|
||||||
|
const string chromeCertsUrl = "https://chromium.googlesource.com/chromium/src/+/main/net/data/ssl/chrome_root_store/root_store.certs?format=TEXT";
|
||||||
|
var chromeOutput = Path.Combine(outputDir, "chrome_roots_pem");
|
||||||
|
|
||||||
|
Console.WriteLine("Downloading Chrome root_store.certs...");
|
||||||
|
var base64Content = await client.GetStringAsync(chromeCertsUrl);
|
||||||
|
var decoded = Convert.FromBase64String(base64Content.Replace("\n", ""));
|
||||||
|
|
||||||
|
var text = Encoding.UTF8.GetString(decoded);
|
||||||
|
|
||||||
|
var pemMatches = Regex.Matches(text, @"(-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----)");
|
||||||
|
var pems = new List<string>();
|
||||||
|
foreach (Match m in pemMatches)
|
||||||
|
{
|
||||||
|
pems.Add(m.Groups[1].Value.Trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
await File.WriteAllTextAsync(chromeOutput, string.Join("\n\n", pems));
|
||||||
|
Console.WriteLine($"Chrome roots saved to: {chromeOutput} ({pems.Count} certificates)");
|
||||||
|
}
|
||||||
@@ -0,0 +1,941 @@
|
|||||||
|
name: build v2rayN.WebAPI
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
release_tag:
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
default: ''
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
release_tag:
|
||||||
|
description: 'Release tag (for example 7.x.y). Empty builds a development API package.'
|
||||||
|
required: false
|
||||||
|
default: ''
|
||||||
|
type: string
|
||||||
|
pull_request:
|
||||||
|
branches: [master]
|
||||||
|
paths:
|
||||||
|
- 'v2rayN/v2rayN.WebAPI/**'
|
||||||
|
- 'v2rayN/ServiceLib/**'
|
||||||
|
- 'v2rayN/ServiceLib.Tests/**'
|
||||||
|
- 'v2rayN/Directory.Build.*'
|
||||||
|
- 'v2rayN/Directory.Packages.props'
|
||||||
|
- 'v2rayN/v2rayN.slnx'
|
||||||
|
- 'global.json'
|
||||||
|
- '.github/workflows/build-WebAPI.yml'
|
||||||
|
- '.github/workflows/release-WebAPI.yml'
|
||||||
|
- '.github/workflows/build-all.yml'
|
||||||
|
- '.github/workflows/upload-sign.yml'
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
paths:
|
||||||
|
- 'v2rayN/v2rayN.WebAPI/**'
|
||||||
|
- 'v2rayN/ServiceLib/**'
|
||||||
|
- 'v2rayN/ServiceLib.Tests/**'
|
||||||
|
- 'v2rayN/Directory.Build.*'
|
||||||
|
- 'v2rayN/Directory.Packages.props'
|
||||||
|
- 'v2rayN/v2rayN.slnx'
|
||||||
|
- 'global.json'
|
||||||
|
- '.github/workflows/build-WebAPI.yml'
|
||||||
|
- '.github/workflows/release-WebAPI.yml'
|
||||||
|
- '.github/workflows/build-all.yml'
|
||||||
|
- '.github/workflows/upload-sign.yml'
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
macos:
|
||||||
|
name: macOS WebAPI and ServiceLib tests
|
||||||
|
runs-on: macos-latest
|
||||||
|
timeout-minutes: 15
|
||||||
|
env:
|
||||||
|
TUNIT_MAX_PARALLEL_TESTS: 1
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: actions/setup-dotnet@v6
|
||||||
|
with:
|
||||||
|
dotnet-version: '10.x'
|
||||||
|
- name: Run ServiceLib.Tests
|
||||||
|
run: dotnet test --project v2rayN/ServiceLib.Tests/ServiceLib.Tests.csproj -c Release
|
||||||
|
- name: Run WebAPI.Tests
|
||||||
|
run: dotnet test --project v2rayN/v2rayN.WebAPI/Tests/v2rayN.WebAPI.Tests.csproj -c Release
|
||||||
|
|
||||||
|
identity:
|
||||||
|
name: Resolve API build identity
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
outputs:
|
||||||
|
version: ${{ steps.resolve.outputs.version }}
|
||||||
|
tag: ${{ steps.resolve.outputs.tag }}
|
||||||
|
release: ${{ steps.resolve.outputs.release }}
|
||||||
|
build_date: ${{ steps.resolve.outputs.build_date }}
|
||||||
|
steps:
|
||||||
|
- name: Resolve release identity
|
||||||
|
id: resolve
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
RELEASE_TAG: ${{ inputs.release_tag }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
build_date="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||||
|
if [[ -z "$RELEASE_TAG" ]]; then
|
||||||
|
{
|
||||||
|
echo "version=0.0.0-dev"
|
||||||
|
echo "tag="
|
||||||
|
echo "release=false"
|
||||||
|
echo "build_date=$build_date"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
[[ "$RELEASE_TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || {
|
||||||
|
echo "Invalid release tag: $RELEASE_TAG" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
{
|
||||||
|
echo "version=$RELEASE_TAG"
|
||||||
|
echo "tag=$RELEASE_TAG"
|
||||||
|
echo "release=true"
|
||||||
|
echo "build_date=$build_date"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
verify:
|
||||||
|
name: Backend, ServiceLib, package smoke
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
env:
|
||||||
|
TUNIT_MAX_PARALLEL_TESTS: 1
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: actions/setup-dotnet@v6
|
||||||
|
with:
|
||||||
|
dotnet-version: '10.x'
|
||||||
|
- name: Verify API build, backend and ServiceLib tests, native startup and package boundaries
|
||||||
|
run: bash v2rayN/v2rayN.WebAPI/Scripts/verify.sh "$RUNNER_TEMP/v2rayN.WebAPI-verify"
|
||||||
|
- name: Check patch whitespace
|
||||||
|
if: github.event_name == 'pull_request' || github.event_name == 'push' || github.event_name == 'workflow_dispatch'
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before || '' }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
base_sha="$BASE_SHA"
|
||||||
|
if [[ -z "$base_sha" ]]; then
|
||||||
|
base_sha="$(git rev-parse HEAD^)"
|
||||||
|
fi
|
||||||
|
if [[ "$base_sha" =~ ^0+$ ]]; then
|
||||||
|
empty_tree="$(git hash-object -t tree -w /dev/null)"
|
||||||
|
git diff --check "$empty_tree" HEAD
|
||||||
|
else
|
||||||
|
git diff --check "$base_sha...HEAD"
|
||||||
|
fi
|
||||||
|
|
||||||
|
windows:
|
||||||
|
name: Windows WebAPI build and runtime smoke
|
||||||
|
needs: identity
|
||||||
|
runs-on: windows-latest
|
||||||
|
env:
|
||||||
|
TUNIT_MAX_PARALLEL_TESTS: 1
|
||||||
|
WEB_VERSION: ${{ needs.identity.outputs.version }}
|
||||||
|
WEB_COMMIT: ${{ github.sha }}
|
||||||
|
WEB_BUILD_DATE: ${{ needs.identity.outputs.build_date }}
|
||||||
|
WEB_REPOSITORY: ${{ github.repository }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: actions/setup-dotnet@v6
|
||||||
|
with:
|
||||||
|
dotnet-version: '10.x'
|
||||||
|
- uses: actions/setup-python@v7
|
||||||
|
with:
|
||||||
|
python-version: '3.x'
|
||||||
|
- name: Restore WebAPI
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet restore v2rayN/v2rayN.WebAPI/v2rayN.WebAPI.csproj
|
||||||
|
- name: Restore WebAPI.Tests
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet restore v2rayN/v2rayN.WebAPI/Tests/v2rayN.WebAPI.Tests.csproj
|
||||||
|
- name: Restore ServiceLib.Tests
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet restore v2rayN/ServiceLib.Tests/ServiceLib.Tests.csproj
|
||||||
|
- name: Build WebAPI
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet build v2rayN/v2rayN.WebAPI/v2rayN.WebAPI.csproj --configuration Release --no-restore
|
||||||
|
- name: Run WebAPI.Tests
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet test --project v2rayN/v2rayN.WebAPI/Tests/v2rayN.WebAPI.Tests.csproj --configuration Release --no-restore
|
||||||
|
- name: Run ServiceLib.Tests
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet test --project v2rayN/ServiceLib.Tests/ServiceLib.Tests.csproj --configuration Release --no-restore
|
||||||
|
- name: Publish win-x64 self-contained single-file WebAPI
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64'
|
||||||
|
dotnet publish v2rayN/v2rayN.WebAPI/v2rayN.WebAPI.csproj `
|
||||||
|
--configuration Release `
|
||||||
|
--runtime win-x64 `
|
||||||
|
--self-contained true `
|
||||||
|
-p:PublishSingleFile=true `
|
||||||
|
-p:IncludeNativeLibrariesForSelfExtract=true `
|
||||||
|
-p:WebVersion=$env:WEB_VERSION `
|
||||||
|
-p:WebCommit=$env:WEB_COMMIT `
|
||||||
|
-p:WebBuildDate=$env:WEB_BUILD_DATE `
|
||||||
|
-p:WebRepository=$env:WEB_REPOSITORY `
|
||||||
|
--output $publishDirectory
|
||||||
|
$identity = [ordered]@{
|
||||||
|
product = 'v2rayN.WebAPI'
|
||||||
|
version = $env:WEB_VERSION
|
||||||
|
commit = $env:WEB_COMMIT
|
||||||
|
buildDate = $env:WEB_BUILD_DATE
|
||||||
|
rid = 'win-x64'
|
||||||
|
}
|
||||||
|
$json = $identity | ConvertTo-Json -Compress
|
||||||
|
[IO.File]::WriteAllText((Join-Path $publishDirectory 'v2rayN.WebAPI.build.json'), $json, [Text.UTF8Encoding]::new($false))
|
||||||
|
- name: Verify single-file publish output
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64'
|
||||||
|
$executable = Join-Path $publishDirectory 'v2rayN.WebAPI.exe'
|
||||||
|
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) {
|
||||||
|
throw "dotnet publish did not produce $executable"
|
||||||
|
}
|
||||||
|
if ((Get-Item -LiteralPath $executable).Length -eq 0) {
|
||||||
|
throw "Published executable is empty: $executable"
|
||||||
|
}
|
||||||
|
$looseDlls = @(Get-ChildItem -LiteralPath $publishDirectory -Filter '*.dll' -File -Recurse)
|
||||||
|
if ($looseDlls.Count -gt 0) {
|
||||||
|
throw "Single-file publish left loose DLLs: $($looseDlls.FullName -join ', ')"
|
||||||
|
}
|
||||||
|
- name: Smoke-test first startup, health endpoint and graceful shutdown
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64'
|
||||||
|
& ./v2rayN/v2rayN.WebAPI/Tests/Integration/Test-Windows.ps1 -Mode startup -PublishDirectory $publishDirectory
|
||||||
|
- name: Publish previous Windows fixture for update regression
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64-previous'
|
||||||
|
dotnet publish v2rayN/v2rayN.WebAPI/v2rayN.WebAPI.csproj `
|
||||||
|
--configuration Release `
|
||||||
|
--runtime win-x64 `
|
||||||
|
--self-contained true `
|
||||||
|
-p:PublishSingleFile=true `
|
||||||
|
-p:IncludeNativeLibrariesForSelfExtract=true `
|
||||||
|
-p:WebVersion=0.0.1-regression `
|
||||||
|
-p:WebCommit=$env:WEB_COMMIT `
|
||||||
|
-p:WebBuildDate=$env:WEB_BUILD_DATE `
|
||||||
|
-p:WebRepository=$env:WEB_REPOSITORY `
|
||||||
|
--output $publishDirectory
|
||||||
|
$identity = [ordered]@{
|
||||||
|
product = 'v2rayN.WebAPI'
|
||||||
|
version = '0.0.1-regression'
|
||||||
|
commit = $env:WEB_COMMIT
|
||||||
|
buildDate = $env:WEB_BUILD_DATE
|
||||||
|
rid = 'win-x64'
|
||||||
|
}
|
||||||
|
$json = $identity | ConvertTo-Json -Compress
|
||||||
|
[IO.File]::WriteAllText((Join-Path $publishDirectory 'v2rayN.WebAPI.build.json'), $json, [Text.UTF8Encoding]::new($false))
|
||||||
|
- name: Add the matching Windows Core bundle
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$bundle = Join-Path $env:RUNNER_TEMP 'v2rayN-windows-64.zip'
|
||||||
|
$expanded = Join-Path $env:RUNNER_TEMP 'v2rayN-windows-64-core'
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64'
|
||||||
|
$previousDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64-previous'
|
||||||
|
Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-windows-64.zip' -OutFile $bundle
|
||||||
|
Expand-Archive -LiteralPath $bundle -DestinationPath $expanded -Force
|
||||||
|
$sourceBin = Join-Path $expanded 'v2rayN-windows-64\bin'
|
||||||
|
if (-not (Test-Path -LiteralPath $sourceBin -PathType Container)) {
|
||||||
|
throw "Windows Core bundle is missing $sourceBin"
|
||||||
|
}
|
||||||
|
foreach ($directory in @($publishDirectory, $previousDirectory)) {
|
||||||
|
$destinationBin = Join-Path $directory 'bin'
|
||||||
|
New-Item -ItemType Directory -Path $destinationBin -Force | Out-Null
|
||||||
|
Copy-Item -Path (Join-Path $sourceBin '*') -Destination $destinationBin -Recurse -Force
|
||||||
|
}
|
||||||
|
foreach ($directory in @($publishDirectory, $previousDirectory)) {
|
||||||
|
$checkBin = Join-Path $directory 'bin'
|
||||||
|
foreach ($relative in @('xray\xray.exe','sing_box\sing-box.exe','mihomo\mihomo.exe','geoip.dat','geosite.dat','geoip.metadb','Country.mmdb')) {
|
||||||
|
$required = Join-Path $checkBin $relative
|
||||||
|
if (-not (Test-Path -LiteralPath $required -PathType Leaf)) { throw "Missing Windows Core asset: $required" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$candidateBin = Join-Path $publishDirectory 'bin'
|
||||||
|
& (Join-Path $candidateBin 'xray\xray.exe') -version
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "xray.exe smoke failed: $LASTEXITCODE" }
|
||||||
|
& (Join-Path $candidateBin 'sing_box\sing-box.exe') version
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "sing-box.exe smoke failed: $LASTEXITCODE" }
|
||||||
|
& (Join-Path $candidateBin 'mihomo\mihomo.exe') -v
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "mihomo.exe smoke failed: $LASTEXITCODE" }
|
||||||
|
- name: Smoke-test Windows backup restore handoff and Core intent recovery
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
& ./v2rayN/v2rayN.WebAPI/Tests/Integration/Test-Windows.ps1 `
|
||||||
|
-Mode restore `
|
||||||
|
-PublishDirectory (Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64')
|
||||||
|
- name: Smoke-test Windows self-update replacement and rollback
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
& ./v2rayN/v2rayN.WebAPI/Tests/Integration/Test-Windows.ps1 `
|
||||||
|
-Mode update `
|
||||||
|
-PreviousPublishDirectory (Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64-previous') `
|
||||||
|
-CandidatePublishDirectory (Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64')
|
||||||
|
- name: Package and smoke-test Windows full-install and app-only ZIPs
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64'
|
||||||
|
$dist = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-x64-dist'
|
||||||
|
python v2rayN/v2rayN.WebAPI/Scripts/web-release-assets.py package --rid win-x64 --publish $publishDirectory --dist $dist
|
||||||
|
$fullZip = Join-Path $dist 'v2rayN-windows-64-WebAPI.zip'
|
||||||
|
$appOnlyZip = Join-Path $dist 'v2rayN-windows-64-WebAPI-update.zip'
|
||||||
|
if (-not (Test-Path -LiteralPath $fullZip -PathType Leaf) -or -not (Test-Path -LiteralPath $appOnlyZip -PathType Leaf)) {
|
||||||
|
throw 'Windows release ZIPs were not created.'
|
||||||
|
}
|
||||||
|
$extracted = Join-Path $env:RUNNER_TEMP 'v2rayN-windows-64-WebAPI-smoke'
|
||||||
|
Expand-Archive -LiteralPath $fullZip -DestinationPath $extracted -Force
|
||||||
|
& ./v2rayN/v2rayN.WebAPI/Tests/Integration/Test-Windows.ps1 -Mode startup -PublishDirectory $extracted
|
||||||
|
"Windows full-install ZIP: $fullZip"
|
||||||
|
"Windows app-only update ZIP: $appOnlyZip"
|
||||||
|
- uses: actions/upload-artifact@v7
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
with:
|
||||||
|
name: v2rayN.WebAPI-win-x64
|
||||||
|
path: ${{ runner.temp }}/v2rayN.WebAPI-win-x64-dist/*.zip
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
# The self-update replacement smoke stays on win-x64: the updater logic is RID-generic
|
||||||
|
# and the per-RID PE/ELF checks are covered by unit tests. This job proves the win-arm64
|
||||||
|
# build, first startup, health endpoint and graceful shutdown on native ARM64 Windows.
|
||||||
|
windows-arm64:
|
||||||
|
name: Windows ARM64 WebAPI build and runtime smoke
|
||||||
|
needs: identity
|
||||||
|
runs-on: windows-11-arm
|
||||||
|
env:
|
||||||
|
TUNIT_MAX_PARALLEL_TESTS: 1
|
||||||
|
WEB_VERSION: ${{ needs.identity.outputs.version }}
|
||||||
|
WEB_COMMIT: ${{ github.sha }}
|
||||||
|
WEB_BUILD_DATE: ${{ needs.identity.outputs.build_date }}
|
||||||
|
WEB_REPOSITORY: ${{ github.repository }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: actions/setup-dotnet@v6
|
||||||
|
with:
|
||||||
|
dotnet-version: '10.x'
|
||||||
|
- uses: actions/setup-python@v7
|
||||||
|
with:
|
||||||
|
python-version: '3.x'
|
||||||
|
- name: Restore WebAPI
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet restore v2rayN/v2rayN.WebAPI/v2rayN.WebAPI.csproj
|
||||||
|
- name: Restore WebAPI.Tests
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet restore v2rayN/v2rayN.WebAPI/Tests/v2rayN.WebAPI.Tests.csproj
|
||||||
|
- name: Restore ServiceLib.Tests
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet restore v2rayN/ServiceLib.Tests/ServiceLib.Tests.csproj
|
||||||
|
- name: Build WebAPI
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet build v2rayN/v2rayN.WebAPI/v2rayN.WebAPI.csproj --configuration Release --no-restore
|
||||||
|
- name: Run WebAPI.Tests
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet test --project v2rayN/v2rayN.WebAPI/Tests/v2rayN.WebAPI.Tests.csproj --configuration Release --no-restore
|
||||||
|
- name: Run ServiceLib.Tests
|
||||||
|
shell: pwsh
|
||||||
|
run: dotnet test --project v2rayN/ServiceLib.Tests/ServiceLib.Tests.csproj --configuration Release --no-restore
|
||||||
|
- name: Publish win-arm64 self-contained single-file WebAPI
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-arm64'
|
||||||
|
dotnet publish v2rayN/v2rayN.WebAPI/v2rayN.WebAPI.csproj `
|
||||||
|
--configuration Release `
|
||||||
|
--runtime win-arm64 `
|
||||||
|
--self-contained true `
|
||||||
|
-p:PublishSingleFile=true `
|
||||||
|
-p:IncludeNativeLibrariesForSelfExtract=true `
|
||||||
|
-p:WebVersion=$env:WEB_VERSION `
|
||||||
|
-p:WebCommit=$env:WEB_COMMIT `
|
||||||
|
-p:WebBuildDate=$env:WEB_BUILD_DATE `
|
||||||
|
-p:WebRepository=$env:WEB_REPOSITORY `
|
||||||
|
--output $publishDirectory
|
||||||
|
$identity = [ordered]@{
|
||||||
|
product = 'v2rayN.WebAPI'
|
||||||
|
version = $env:WEB_VERSION
|
||||||
|
commit = $env:WEB_COMMIT
|
||||||
|
buildDate = $env:WEB_BUILD_DATE
|
||||||
|
rid = 'win-arm64'
|
||||||
|
}
|
||||||
|
$json = $identity | ConvertTo-Json -Compress
|
||||||
|
[IO.File]::WriteAllText((Join-Path $publishDirectory 'v2rayN.WebAPI.build.json'), $json, [Text.UTF8Encoding]::new($false))
|
||||||
|
- name: Smoke-test first startup, health endpoint and graceful shutdown
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-arm64'
|
||||||
|
& ./v2rayN/v2rayN.WebAPI/Tests/Integration/Test-Windows.ps1 -Mode startup -PublishDirectory $publishDirectory
|
||||||
|
- name: Add the matching Windows ARM64 Core bundle
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$bundle = Join-Path $env:RUNNER_TEMP 'v2rayN-windows-arm64.zip'
|
||||||
|
$expanded = Join-Path $env:RUNNER_TEMP 'v2rayN-windows-arm64-core'
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-arm64'
|
||||||
|
Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-windows-arm64.zip' -OutFile $bundle
|
||||||
|
Expand-Archive -LiteralPath $bundle -DestinationPath $expanded -Force
|
||||||
|
$sourceBin = Join-Path $expanded 'v2rayN-windows-arm64\bin'
|
||||||
|
if (-not (Test-Path -LiteralPath $sourceBin -PathType Container)) {
|
||||||
|
throw "Windows ARM64 Core bundle is missing $sourceBin"
|
||||||
|
}
|
||||||
|
$destinationBin = Join-Path $publishDirectory 'bin'
|
||||||
|
New-Item -ItemType Directory -Path $destinationBin -Force | Out-Null
|
||||||
|
Copy-Item -Path (Join-Path $sourceBin '*') -Destination $destinationBin -Recurse -Force
|
||||||
|
foreach ($relative in @('xray\xray.exe','sing_box\sing-box.exe','mihomo\mihomo.exe','geoip.dat','geosite.dat','geoip.metadb','Country.mmdb')) {
|
||||||
|
$required = Join-Path $destinationBin $relative
|
||||||
|
if (-not (Test-Path -LiteralPath $required -PathType Leaf)) { throw "Missing Windows ARM64 Core asset: $required" }
|
||||||
|
}
|
||||||
|
& (Join-Path $destinationBin 'xray\xray.exe') -version
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "xray.exe smoke failed: $LASTEXITCODE" }
|
||||||
|
& (Join-Path $destinationBin 'sing_box\sing-box.exe') version
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "sing-box.exe smoke failed: $LASTEXITCODE" }
|
||||||
|
& (Join-Path $destinationBin 'mihomo\mihomo.exe') -v
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "mihomo.exe smoke failed: $LASTEXITCODE" }
|
||||||
|
- name: Package Windows ARM64 full-install and app-only ZIPs
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$publishDirectory = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-arm64'
|
||||||
|
$dist = Join-Path $env:RUNNER_TEMP 'v2rayN.WebAPI-win-arm64-dist'
|
||||||
|
python v2rayN/v2rayN.WebAPI/Scripts/web-release-assets.py package --rid win-arm64 --publish $publishDirectory --dist $dist
|
||||||
|
$fullZip = Join-Path $dist 'v2rayN-windows-arm64-WebAPI.zip'
|
||||||
|
$appOnlyZip = Join-Path $dist 'v2rayN-windows-arm64-WebAPI-update.zip'
|
||||||
|
if (-not (Test-Path -LiteralPath $fullZip -PathType Leaf) -or -not (Test-Path -LiteralPath $appOnlyZip -PathType Leaf)) {
|
||||||
|
throw 'Windows ARM64 release ZIPs were not created.'
|
||||||
|
}
|
||||||
|
$extracted = Join-Path $env:RUNNER_TEMP 'v2rayN-windows-arm64-WebAPI-smoke'
|
||||||
|
Expand-Archive -LiteralPath $fullZip -DestinationPath $extracted -Force
|
||||||
|
& ./v2rayN/v2rayN.WebAPI/Tests/Integration/Test-Windows.ps1 -Mode startup -PublishDirectory $extracted
|
||||||
|
"Windows ARM64 full-install ZIP: $fullZip"
|
||||||
|
"Windows ARM64 app-only update ZIP: $appOnlyZip"
|
||||||
|
- uses: actions/upload-artifact@v7
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
with:
|
||||||
|
name: v2rayN.WebAPI-win-arm64
|
||||||
|
path: ${{ runner.temp }}/v2rayN.WebAPI-win-arm64-dist/*.zip
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
native:
|
||||||
|
name: Native API build (${{ matrix.rid }})
|
||||||
|
needs: identity
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
# Development builds keep x64 coverage; releases also validate ARM64.
|
||||||
|
# Only tested Linux RIDs are enabled; native RID/runner pairs are independent
|
||||||
|
# of Desktop workflows and the container platform matrix.
|
||||||
|
include: >-
|
||||||
|
${{ fromJSON(needs.identity.outputs.release == 'true'
|
||||||
|
&& '[{"rid":"linux-x64","runner":"ubuntu-24.04"},{"rid":"linux-arm64","runner":"ubuntu-24.04-arm"}]'
|
||||||
|
|| '[{"rid":"linux-x64","runner":"ubuntu-24.04"}]') }}
|
||||||
|
runs-on: ${{ matrix.runner }}
|
||||||
|
env:
|
||||||
|
RID: ${{ matrix.rid }}
|
||||||
|
V2RAYN_WEB_VERSION: ${{ needs.identity.outputs.version }}
|
||||||
|
V2RAYN_WEB_REPOSITORY: ${{ github.repository }}
|
||||||
|
V2RAYN_WEB_COMMIT: ${{ github.sha }}
|
||||||
|
V2RAYN_WEB_BUILD_DATE: ${{ needs.identity.outputs.build_date }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: actions/setup-dotnet@v6
|
||||||
|
with:
|
||||||
|
dotnet-version: '10.x'
|
||||||
|
- name: Publish native API
|
||||||
|
run: bash v2rayN/v2rayN.WebAPI/Scripts/publish-native.sh "$RID"
|
||||||
|
- name: Verify native executable
|
||||||
|
run: test -x "v2rayN/v2rayN.WebAPI/publish/$RID/v2rayN.WebAPI"
|
||||||
|
- name: Add the matching Linux Core bundle
|
||||||
|
if: needs.identity.outputs.release == 'true'
|
||||||
|
run: sh v2rayN/v2rayN.WebAPI/Scripts/fetch-core-bundle.sh "$RID" "v2rayN/v2rayN.WebAPI/publish/$RID/bin"
|
||||||
|
- name: Package API install and self-update ZIPs
|
||||||
|
if: needs.identity.outputs.release == 'true'
|
||||||
|
run: python3 v2rayN/v2rayN.WebAPI/Scripts/web-release-assets.py package --rid "$RID" --publish "v2rayN/v2rayN.WebAPI/publish/$RID" --dist dist
|
||||||
|
- name: Smoke-test bundled Cores
|
||||||
|
if: needs.identity.outputs.release == 'true'
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
publish="v2rayN/v2rayN.WebAPI/publish/$RID"
|
||||||
|
"$publish/bin/xray/xray" -version
|
||||||
|
"$publish/bin/sing_box/sing-box" version
|
||||||
|
"$publish/bin/mihomo/mihomo" -v
|
||||||
|
- uses: actions/upload-artifact@v7
|
||||||
|
if: needs.identity.outputs.release == 'true'
|
||||||
|
with:
|
||||||
|
name: v2rayN.WebAPI-${{ matrix.rid }}
|
||||||
|
path: dist/*.zip
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
# linux-riscv64 runs natively on the RISE RISC-V runners with the community
|
||||||
|
# xujiegb/dotnet-riscv SDK; single-file publish is verified to work there.
|
||||||
|
native-riscv64:
|
||||||
|
name: Native API build (linux-riscv64)
|
||||||
|
needs: identity
|
||||||
|
if: needs.identity.outputs.release == 'true'
|
||||||
|
runs-on: ubuntu-24.04-riscv
|
||||||
|
container: debian:13
|
||||||
|
env:
|
||||||
|
RID: linux-riscv64
|
||||||
|
V2RAYN_WEB_VERSION: ${{ needs.identity.outputs.version }}
|
||||||
|
V2RAYN_WEB_REPOSITORY: ${{ github.repository }}
|
||||||
|
V2RAYN_WEB_COMMIT: ${{ github.sha }}
|
||||||
|
V2RAYN_WEB_BUILD_DATE: ${{ needs.identity.outputs.build_date }}
|
||||||
|
steps:
|
||||||
|
- name: Prepare tools (Debian)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y sudo git rsync findutils tar gzip unzip which curl jq wget file ca-certificates python3 libc6-dev libgcc-s1 libstdc++6 zlib1g libatomic1 libicu76 || \
|
||||||
|
apt-get install -y sudo git rsync findutils tar gzip unzip which curl jq wget file ca-certificates python3 libc6-dev libgcc-s1 libstdc++6 zlib1g libatomic1 libicu72
|
||||||
|
- name: Checkout repo
|
||||||
|
shell: bash
|
||||||
|
env: { GITHUB_TOKEN: "${{ github.token }}" }
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
rm -rf ./*
|
||||||
|
git init .
|
||||||
|
git config --global --add safe.directory "$PWD"
|
||||||
|
git remote add origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"
|
||||||
|
git fetch --depth=1 origin "${GITHUB_SHA}"
|
||||||
|
git checkout FETCH_HEAD
|
||||||
|
- name: Install community .NET SDK (linux-riscv64)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
SDK=dotnet-sdk-10.0.111-linux-riscv64.tar.gz
|
||||||
|
curl -fL "https://github.com/xujiegb/dotnet-riscv/releases/download/10.0.111/$SDK" -o /tmp/$SDK
|
||||||
|
mkdir -p "$HOME/.dotnet"
|
||||||
|
tar -C "$HOME/.dotnet" -xzf /tmp/$SDK
|
||||||
|
echo "DOTNET_ROOT=$HOME/.dotnet" >> "$GITHUB_ENV"
|
||||||
|
echo "$HOME/.dotnet" >> "$GITHUB_PATH"
|
||||||
|
export DOTNET_ROOT="$HOME/.dotnet"
|
||||||
|
export PATH="$DOTNET_ROOT:$PATH"
|
||||||
|
dotnet --info
|
||||||
|
- name: Publish native API
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
export DOTNET_ROOT="$HOME/.dotnet"
|
||||||
|
export PATH="$DOTNET_ROOT:$PATH"
|
||||||
|
bash v2rayN/v2rayN.WebAPI/Scripts/publish-native.sh "$RID"
|
||||||
|
test -x "v2rayN/v2rayN.WebAPI/publish/$RID/v2rayN.WebAPI"
|
||||||
|
- name: Add the matching Linux Core bundle
|
||||||
|
shell: bash
|
||||||
|
run: sh v2rayN/v2rayN.WebAPI/Scripts/fetch-core-bundle.sh "$RID" "v2rayN/v2rayN.WebAPI/publish/$RID/bin"
|
||||||
|
- name: Package API install and self-update ZIPs
|
||||||
|
shell: bash
|
||||||
|
run: python3 v2rayN/v2rayN.WebAPI/Scripts/web-release-assets.py package --rid "$RID" --publish "v2rayN/v2rayN.WebAPI/publish/$RID" --dist dist
|
||||||
|
- name: Smoke-test bundled Cores
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
publish="v2rayN/v2rayN.WebAPI/publish/$RID"
|
||||||
|
"$publish/bin/xray/xray" -version
|
||||||
|
"$publish/bin/sing_box/sing-box" version
|
||||||
|
"$publish/bin/mihomo/mihomo" -v
|
||||||
|
- name: Smoke-test the published API (native riscv64)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
publish="v2rayN/v2rayN.WebAPI/publish/$RID"
|
||||||
|
"$publish/v2rayN.WebAPI" --help | head -n 5
|
||||||
|
export V2RAYN_WEB_API_KEY=ci-smoke-key-0123456789abcdef
|
||||||
|
export ASPNETCORE_URLS=http://127.0.0.1:5080
|
||||||
|
cd "$publish"
|
||||||
|
./v2rayN.WebAPI --foreground --no-open > /tmp/smoke.log 2>&1 &
|
||||||
|
app_pid=$!
|
||||||
|
echo "$app_pid" > /tmp/smoke.pid
|
||||||
|
echo "riscv64 API smoke application PID: $app_pid"
|
||||||
|
ok=0
|
||||||
|
for i in $(seq 1 90); do
|
||||||
|
if curl --noproxy '*' -fsS http://127.0.0.1:5080/api/health >/dev/null 2>&1; then ok=1; break; fi
|
||||||
|
if ! kill -0 "$app_pid" 2>/dev/null; then break; fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
if [ "$ok" != 1 ]; then
|
||||||
|
echo 'riscv64 API smoke did not become healthy'
|
||||||
|
tail -n 60 /tmp/smoke.log || true
|
||||||
|
kill -TERM "$app_pid" 2>/dev/null || true
|
||||||
|
sleep 1
|
||||||
|
kill -KILL "$app_pid" 2>/dev/null || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
kill -TERM "$app_pid"
|
||||||
|
stopped=0
|
||||||
|
for i in $(seq 1 30); do
|
||||||
|
if ! kill -0 "$app_pid" 2>/dev/null; then stopped=1; break; fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
if [ "$stopped" != 1 ]; then
|
||||||
|
echo 'riscv64 API smoke did not exit within 30s after SIGTERM'
|
||||||
|
tail -n 60 /tmp/smoke.log || true
|
||||||
|
kill -KILL "$app_pid" 2>/dev/null || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
set +e
|
||||||
|
wait "$app_pid"
|
||||||
|
exit_code=$?
|
||||||
|
set -e
|
||||||
|
if [ "$exit_code" -ne 0 ]; then
|
||||||
|
echo "riscv64 API smoke exited with status $exit_code after SIGTERM"
|
||||||
|
tail -n 60 /tmp/smoke.log || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo 'linux-riscv64 native API smoke OK'
|
||||||
|
- uses: actions/upload-artifact@v7
|
||||||
|
with:
|
||||||
|
name: v2rayN.WebAPI-linux-riscv64
|
||||||
|
path: dist/*.zip
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
# linux-loongarch64 publishes inside the upstream QEMU loong64 VM with the official
|
||||||
|
# Loongson .NET SDK; the VM runs the native smoke before the host packages the ZIPs.
|
||||||
|
native-loong64:
|
||||||
|
name: Native API build (linux-loongarch64)
|
||||||
|
needs: identity
|
||||||
|
if: needs.identity.outputs.release == 'true'
|
||||||
|
runs-on: ubuntu-26.04-arm
|
||||||
|
env:
|
||||||
|
RID: linux-loongarch64
|
||||||
|
V2RAYN_WEB_VERSION: ${{ needs.identity.outputs.version }}
|
||||||
|
V2RAYN_WEB_REPOSITORY: ${{ github.repository }}
|
||||||
|
V2RAYN_WEB_COMMIT: ${{ github.sha }}
|
||||||
|
V2RAYN_WEB_BUILD_DATE: ${{ needs.identity.outputs.build_date }}
|
||||||
|
QCOW2_URL: https://github.com/xujiegb/debian-loong64-qcow2/releases/download/13.5/debian13-loong64.qcow2
|
||||||
|
EFI_CODE_URL: https://github.com/xujiegb/debian-loong64-qcow2/releases/download/13.5/edk2-loongarch64-code.fd
|
||||||
|
EFI_VARS_URL: https://github.com/xujiegb/debian-loong64-qcow2/releases/download/13.5/edk2-loongarch64-vars.fd
|
||||||
|
QCOW2_IMAGE: debian13-loong64.qcow2
|
||||||
|
EFI_CODE: edk2-loongarch64-code.fd
|
||||||
|
EFI_VARS: edk2-loongarch64-vars.fd
|
||||||
|
QEMU_VERSION: 10.2.4
|
||||||
|
steps:
|
||||||
|
- name: Prepare host tools
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y git rsync qemu-utils qemu-system-common expect wget curl ca-certificates libfdt1 libglib2.0-0 libpixman-1-0 libslirp0 virtiofsd
|
||||||
|
sudo ln -sf /usr/libexec/virtiofsd /usr/local/bin/virtiofsd
|
||||||
|
virtiofsd --version || virtiofsd --help | head
|
||||||
|
- name: Host clone repo
|
||||||
|
shell: bash
|
||||||
|
env: { GITHUB_TOKEN: "${{ github.token }}" }
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
rm -rf repo
|
||||||
|
git init repo
|
||||||
|
git -C repo config --global --add safe.directory "$PWD/repo" || true
|
||||||
|
git -C repo remote add origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"
|
||||||
|
git -C repo fetch --depth=1 origin "${GITHUB_SHA}"
|
||||||
|
git -C repo checkout FETCH_HEAD
|
||||||
|
- name: Download QEMU prebuild
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
wget -O qemu-linux-arm64-v8.2.tar.gz "https://github.com/xujiegb/qemu-linux-prebuild/releases/download/${QEMU_VERSION}/qemu-linux-arm64-v8.2.tar.gz"
|
||||||
|
tar -xzf qemu-linux-arm64-v8.2.tar.gz
|
||||||
|
mkdir -p "$HOME/qemu-install"
|
||||||
|
rsync -a qemu-linux-arm64-v8.2/ "$HOME/qemu-install/"
|
||||||
|
"$HOME/qemu-install/bin/qemu-system-loongarch64" --version
|
||||||
|
- name: Download loong64 qcow2 and EFI firmware
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
wget -O "$QCOW2_IMAGE" "$QCOW2_URL"
|
||||||
|
wget -O "$EFI_CODE" "$EFI_CODE_URL"
|
||||||
|
wget -O "$EFI_VARS" "$EFI_VARS_URL"
|
||||||
|
qemu-img info "$QCOW2_IMAGE"
|
||||||
|
- name: Stage the VM build script and the matching Core bundle
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
cat > webapi-loong.env <<EOF
|
||||||
|
WEB_VERSION=${V2RAYN_WEB_VERSION}
|
||||||
|
WEB_REPOSITORY=${V2RAYN_WEB_REPOSITORY}
|
||||||
|
WEB_COMMIT=${V2RAYN_WEB_COMMIT}
|
||||||
|
WEB_BUILD_DATE=${V2RAYN_WEB_BUILD_DATE}
|
||||||
|
EOF
|
||||||
|
cat > webapi-loong-run.sh <<'SCRIPT'
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set +e
|
||||||
|
set -o pipefail
|
||||||
|
source /workspace/webapi-loong.env
|
||||||
|
export DOTNET_ROOT=/root/.dotnet
|
||||||
|
export PATH="$DOTNET_ROOT:$PATH"
|
||||||
|
mkdir -p /root/.dotnet
|
||||||
|
SDK=dotnet-sdk-10.0.111-linux-loongarch64.tar.gz
|
||||||
|
curl -fL "https://github.com/loongson/dotnet/releases/download/v10.0.111-loongarch64/$SDK" -o /tmp/$SDK || exit 9
|
||||||
|
tar -C /root/.dotnet -xzf /tmp/$SDK || exit 9
|
||||||
|
dotnet --info >/dev/null 2>&1 || exit 9
|
||||||
|
cd /root/v2rayN-src || exit 9
|
||||||
|
mkdir -p /workspace/publish/linux-loongarch64
|
||||||
|
V2RAYN_WEB_VERSION="$WEB_VERSION" V2RAYN_WEB_REPOSITORY="$WEB_REPOSITORY" V2RAYN_WEB_COMMIT="$WEB_COMMIT" V2RAYN_WEB_BUILD_DATE="$WEB_BUILD_DATE" \
|
||||||
|
bash v2rayN/v2rayN.WebAPI/Scripts/publish-native.sh linux-loongarch64 /workspace/publish/linux-loongarch64 2>&1 | tee /tmp/publish.log
|
||||||
|
rc=$?
|
||||||
|
if [ $rc -eq 0 ]; then
|
||||||
|
mkdir -p /workspace/publish/linux-loongarch64/bin
|
||||||
|
cp -a /workspace/core-bundle/. /workspace/publish/linux-loongarch64/bin/
|
||||||
|
# Smoke a VM-local copy: the shared publish tree must stay exactly the packaging
|
||||||
|
# input, without runtime lock/data files owned by the VM user.
|
||||||
|
rm -rf /root/websmoke
|
||||||
|
cp -a /workspace/publish/linux-loongarch64 /root/websmoke
|
||||||
|
cd /root/websmoke || exit 9
|
||||||
|
./bin/xray/xray -version >/dev/null || rc=9
|
||||||
|
./bin/sing_box/sing-box version >/dev/null || rc=9
|
||||||
|
./bin/mihomo/mihomo -v >/dev/null || rc=9
|
||||||
|
./v2rayN.WebAPI --help >/dev/null || rc=9
|
||||||
|
V2RAYN_WEB_API_KEY=ci-smoke-key-0123456789abcdef ASPNETCORE_URLS=http://127.0.0.1:5080 ./v2rayN.WebAPI --foreground --no-open > /tmp/smoke.log 2>&1 &
|
||||||
|
APP=$!
|
||||||
|
echo "$APP" > /tmp/smoke.pid
|
||||||
|
ok=0
|
||||||
|
for i in $(seq 1 90); do
|
||||||
|
if curl --noproxy '*' -fsS http://127.0.0.1:5080/api/health >/dev/null 2>&1; then ok=1; break; fi
|
||||||
|
if ! kill -0 "$APP" 2>/dev/null; then break; fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
if [ "$ok" != 1 ]; then
|
||||||
|
echo 'loongarch64 API smoke did not become healthy'
|
||||||
|
tail -n 60 /tmp/smoke.log
|
||||||
|
kill -KILL "$APP" 2>/dev/null || true
|
||||||
|
rc=9
|
||||||
|
fi
|
||||||
|
if [ "$rc" = 0 ]; then
|
||||||
|
kill -TERM "$APP"
|
||||||
|
exited=0
|
||||||
|
for i in $(seq 1 60); do
|
||||||
|
if ! kill -0 "$APP" 2>/dev/null; then exited=1; break; fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
if [ "$exited" != 1 ]; then
|
||||||
|
echo 'loongarch64 API smoke did not exit within 60s after SIGTERM'
|
||||||
|
tail -n 60 /tmp/smoke.log
|
||||||
|
kill -KILL "$APP" 2>/dev/null || true
|
||||||
|
rc=9
|
||||||
|
else
|
||||||
|
wait "$APP"
|
||||||
|
app_rc=$?
|
||||||
|
if [ "$app_rc" != 0 ]; then
|
||||||
|
echo "loongarch64 API smoke exited with status $app_rc after SIGTERM"
|
||||||
|
tail -n 60 /tmp/smoke.log
|
||||||
|
rc=9
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ "$rc" != 0 ]; then echo '=== publish.log ==='; tail -n 120 /tmp/publish.log 2>/dev/null; fi
|
||||||
|
echo "__WEBAPI_DONE__$rc"
|
||||||
|
SCRIPT
|
||||||
|
bash repo/v2rayN/v2rayN.WebAPI/Scripts/fetch-core-bundle.sh "$RID" "$GITHUB_WORKSPACE/core-bundle"
|
||||||
|
ls -la "$GITHUB_WORKSPACE/core-bundle" | head -n 15
|
||||||
|
- name: Build WebAPI loongarch64 in the VM (publish + native smoke)
|
||||||
|
shell: bash
|
||||||
|
timeout-minutes: 180
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
mkdir -p "$GITHUB_WORKSPACE/dist"
|
||||||
|
export VIRTIOFSD_SOCKET="$RUNNER_TEMP/virtiofs-webapi-loongarch64.sock"
|
||||||
|
rm -f "$VIRTIOFSD_SOCKET"
|
||||||
|
|
||||||
|
sudo virtiofsd --socket-path="$VIRTIOFSD_SOCKET" --shared-dir="$GITHUB_WORKSPACE" --cache=auto &
|
||||||
|
|
||||||
|
VIRTIOFSD_PID=$!
|
||||||
|
trap 'sudo kill "$VIRTIOFSD_PID" 2>/dev/null || true; rm -f "$VIRTIOFSD_SOCKET"' EXIT
|
||||||
|
|
||||||
|
for i in {1..100}; do
|
||||||
|
[[ -S "$VIRTIOFSD_SOCKET" ]] && break
|
||||||
|
sleep 0.1
|
||||||
|
done
|
||||||
|
[[ -S "$VIRTIOFSD_SOCKET" ]] || { echo "virtiofsd socket not created"; exit 1; }
|
||||||
|
sudo chown "$USER:$(id -gn)" "$VIRTIOFSD_SOCKET" || true
|
||||||
|
sudo chmod 660 "$VIRTIOFSD_SOCKET" || true
|
||||||
|
expect <<'EOF'
|
||||||
|
log_user 1
|
||||||
|
set timeout 10800
|
||||||
|
set qemu_bin "$env(HOME)/qemu-install/bin/qemu-system-loongarch64"
|
||||||
|
set qemu_rom_dir "$env(HOME)/qemu-install/share/qemu"
|
||||||
|
set virtiofs_socket $env(VIRTIOFSD_SOCKET)
|
||||||
|
set qcow2 $env(QCOW2_IMAGE)
|
||||||
|
set efi_code $env(EFI_CODE)
|
||||||
|
set efi_vars $env(EFI_VARS)
|
||||||
|
proc wait_prompt {} {
|
||||||
|
expect {
|
||||||
|
-re "__CI_PROMPT__# " {}
|
||||||
|
timeout { exit 1 }
|
||||||
|
eof { exit 1 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
proc run_cmd {cmd} {
|
||||||
|
send -- "$cmd\r"
|
||||||
|
wait_prompt
|
||||||
|
}
|
||||||
|
spawn $qemu_bin \
|
||||||
|
-L $qemu_rom_dir \
|
||||||
|
-machine virt \
|
||||||
|
-accel tcg,thread=multi,tb-size=2048 \
|
||||||
|
-cpu la464 \
|
||||||
|
-m 9216 \
|
||||||
|
-object memory-backend-memfd,id=mem0,size=9216M,share=on \
|
||||||
|
-numa node,memdev=mem0 \
|
||||||
|
-smp 4 \
|
||||||
|
-drive if=pflash,format=raw,unit=0,file=$efi_code,readonly=on \
|
||||||
|
-drive if=pflash,format=raw,unit=1,file=$efi_vars \
|
||||||
|
-device virtio-blk-pci,drive=hd0,bootindex=1 \
|
||||||
|
-drive if=none,media=disk,id=hd0,file=$qcow2,format=qcow2 \
|
||||||
|
-netdev user,id=net0 \
|
||||||
|
-device virtio-net-pci-non-transitional,netdev=net0 \
|
||||||
|
-chardev socket,id=charfs0,path=$virtiofs_socket \
|
||||||
|
-device vhost-user-fs-pci,chardev=charfs0,tag=workspace \
|
||||||
|
-display none \
|
||||||
|
-serial stdio \
|
||||||
|
-monitor none
|
||||||
|
expect -re "login:|debian login:"
|
||||||
|
send -- "root\r"
|
||||||
|
expect -re "Password:|密码:|密码:"
|
||||||
|
send -- "password\r"
|
||||||
|
expect {
|
||||||
|
-re "# " {}
|
||||||
|
timeout { exit 1 }
|
||||||
|
eof { exit 1 }
|
||||||
|
}
|
||||||
|
send -- "export TERM=dumb; export PS1='__CI_PROMPT__# '\r"
|
||||||
|
wait_prompt
|
||||||
|
run_cmd "mkdir -p /workspace"
|
||||||
|
run_cmd "mount -t virtiofs workspace /workspace"
|
||||||
|
run_cmd "IFACE=\$(ip -o link show | awk -F': ' '\$2 != \"lo\" {print \$2; exit}') ; ip link set \$IFACE up || true"
|
||||||
|
run_cmd "dhclient \$IFACE || true"
|
||||||
|
run_cmd "printf 'nameserver 10.0.2.3\nnameserver 1.1.1.1\n' >/etc/resolv.conf"
|
||||||
|
run_cmd "apt-get update || apt-get update || apt-get update"
|
||||||
|
run_cmd "DEBIAN_FRONTEND=noninteractive apt-get install -y sudo git rsync findutils tar gzip unzip which curl jq wget file ca-certificates python3 libc6-dev libgcc-s1 libstdc++6 zlib1g libatomic1 libicu76 || DEBIAN_FRONTEND=noninteractive apt-get install -y sudo git rsync findutils tar gzip unzip which curl jq wget file ca-certificates python3 libc6-dev libgcc-s1 libstdc++6 zlib1g libatomic1"
|
||||||
|
run_cmd "rm -rf /root/v2rayN-src"
|
||||||
|
run_cmd "rsync -a /workspace/repo/ /root/v2rayN-src/"
|
||||||
|
run_cmd "cd /root/v2rayN-src && git config --global --add safe.directory /root/v2rayN-src"
|
||||||
|
send -- "bash /workspace/webapi-loong-run.sh\r"
|
||||||
|
expect {
|
||||||
|
-re "__WEBAPI_DONE__0" { send -- "poweroff\r" }
|
||||||
|
-re "__WEBAPI_DONE__" { exit 1 }
|
||||||
|
timeout { exit 1 }
|
||||||
|
eof { exit 1 }
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
- name: Verify the loongarch64 publish tree
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
publish="$GITHUB_WORKSPACE/publish/linux-loongarch64"
|
||||||
|
test -x "$publish/v2rayN.WebAPI"
|
||||||
|
test -f "$publish/v2rayN.WebAPI.build.json"
|
||||||
|
unreadable="$(find "$publish" ! -readable -print -quit)"
|
||||||
|
if [ -n "$unreadable" ]; then
|
||||||
|
echo "The loongarch64 publish tree contains unreadable entries:"
|
||||||
|
find "$publish" ! -readable -print | head -n 20
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "loongarch64 publish tree is complete and readable"
|
||||||
|
- name: Package API install and self-update ZIPs
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
python3 repo/v2rayN/v2rayN.WebAPI/Scripts/web-release-assets.py package --rid "$RID" --publish "$GITHUB_WORKSPACE/publish/linux-loongarch64" --dist "$GITHUB_WORKSPACE/dist"
|
||||||
|
ls -la "$GITHUB_WORKSPACE/dist"
|
||||||
|
- uses: actions/upload-artifact@v7
|
||||||
|
with:
|
||||||
|
name: v2rayN.WebAPI-linux-loongarch64
|
||||||
|
path: dist/*.zip
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
container:
|
||||||
|
name: API Containerfile (${{ matrix.rid }})
|
||||||
|
needs: identity
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
# Development builds keep amd64 coverage; releases also validate ARM64.
|
||||||
|
include: >-
|
||||||
|
${{ fromJSON(needs.identity.outputs.release == 'true'
|
||||||
|
&& '[{"rid":"linux-x64","platform":"linux/amd64"},{"rid":"linux-arm64","platform":"linux/arm64"}]'
|
||||||
|
|| '[{"rid":"linux-x64","platform":"linux/amd64"}]') }}
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: docker/setup-buildx-action@v4
|
||||||
|
- name: Build API container (no push)
|
||||||
|
uses: docker/build-push-action@v7
|
||||||
|
env:
|
||||||
|
DOCKER_BUILD_RECORD_UPLOAD: false
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./v2rayN/v2rayN.WebAPI/Containerfile
|
||||||
|
platforms: ${{ matrix.platform }}
|
||||||
|
tags: v2rayn-webapi:ci
|
||||||
|
build-args: |
|
||||||
|
RID=${{ matrix.rid }}
|
||||||
|
WEB_VERSION=${{ needs.identity.outputs.version }}
|
||||||
|
WEB_REPOSITORY=${{ github.repository }}
|
||||||
|
WEB_COMMIT=${{ github.sha }}
|
||||||
|
WEB_BUILD_DATE=${{ needs.identity.outputs.build_date }}
|
||||||
|
push: false
|
||||||
|
|
||||||
|
release-assets:
|
||||||
|
name: Assemble API release assets
|
||||||
|
if: needs.identity.outputs.release == 'true'
|
||||||
|
needs: [identity, verify, windows, windows-arm64, native, native-riscv64, native-loong64, container]
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- uses: actions/download-artifact@v8
|
||||||
|
with:
|
||||||
|
pattern: v2rayN.WebAPI-*
|
||||||
|
path: release-assets
|
||||||
|
merge-multiple: true
|
||||||
|
- name: Build and verify WebAPI-update.json
|
||||||
|
env:
|
||||||
|
RELEASE_TAG: ${{ needs.identity.outputs.tag }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
python3 v2rayN/v2rayN.WebAPI/Scripts/web-update-manifest.py write \
|
||||||
|
--version "$RELEASE_TAG" \
|
||||||
|
--repository "${{ github.repository }}" \
|
||||||
|
--commit "${{ github.sha }}" \
|
||||||
|
--build-date "${{ needs.identity.outputs.build_date }}" \
|
||||||
|
--dist release-assets \
|
||||||
|
--output release-assets/WebAPI-update.json
|
||||||
|
python3 v2rayN/v2rayN.WebAPI/Scripts/web-update-manifest.py verify \
|
||||||
|
--manifest release-assets/WebAPI-update.json \
|
||||||
|
--dist release-assets \
|
||||||
|
--repository "${{ github.repository }}"
|
||||||
|
- name: Smoke-test full API ZIP
|
||||||
|
run: bash v2rayN/v2rayN.WebAPI/Tests/Integration/test-full-zip-runtime.sh release-assets/v2rayN-linux-64-WebAPI.zip
|
||||||
|
- uses: actions/upload-artifact@v7
|
||||||
|
with:
|
||||||
|
name: WebAPI-release-packages
|
||||||
|
path: release-assets/*.zip
|
||||||
|
if-no-files-found: error
|
||||||
|
- uses: actions/upload-artifact@v7
|
||||||
|
with:
|
||||||
|
name: WebAPI-release-manifest
|
||||||
|
path: release-assets/WebAPI-update.json
|
||||||
|
if-no-files-found: error
|
||||||
@@ -9,8 +9,24 @@ on:
|
|||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
actions: write
|
actions: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
public-key:
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
uses: ./.github/workflows/pub-key.yml
|
||||||
|
with:
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
secrets:
|
||||||
|
GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
|
||||||
|
|
||||||
|
release-WebAPI:
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
uses: ./.github/workflows/release-WebAPI.yml
|
||||||
|
with:
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
update:
|
update:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -70,3 +86,17 @@ jobs:
|
|||||||
\"release_tag\": \"${{ inputs.release_tag }}\"
|
\"release_tag\": \"${{ inputs.release_tag }}\"
|
||||||
}
|
}
|
||||||
}"
|
}"
|
||||||
|
|
||||||
|
- name: Trigger build windows x86
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
run: |
|
||||||
|
curl -X POST \
|
||||||
|
-H "Accept: application/vnd.github.v3+json" \
|
||||||
|
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
|
||||||
|
https://api.github.com/repos/${{ github.repository }}/actions/workflows/build-windows-x86.yml/dispatches \
|
||||||
|
-d "{
|
||||||
|
\"ref\": \"master\",
|
||||||
|
\"inputs\": {
|
||||||
|
\"release_tag\": \"${{ inputs.release_tag }}\"
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
|||||||
+171
-396
@@ -12,6 +12,7 @@ on:
|
|||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
actions: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -26,17 +27,30 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
target: linux
|
target: linux
|
||||||
release_tag: ${{ inputs.release_tag }}
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
|
build-aot:
|
||||||
|
uses: ./.github/workflows/build.yml
|
||||||
|
with:
|
||||||
|
target: linux
|
||||||
|
isAot: true
|
||||||
|
|
||||||
|
release-aot-zip:
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
needs: build-aot
|
||||||
|
uses: ./.github/workflows/package-zip.yml
|
||||||
|
with:
|
||||||
|
target: linux
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
isAot: true
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
deb:
|
deb:
|
||||||
name: build and release deb x64 & arm64
|
name: build and release deb x64 & arm64 & riscv64 & ppc64le & loong64
|
||||||
if: |
|
if: (github.event_name == 'workflow_dispatch' && inputs.release_tag != '') || (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
|
||||||
(github.event_name == 'workflow_dispatch' && inputs.release_tag != '') ||
|
runs-on: ubuntu-26.04
|
||||||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
|
|
||||||
runs-on: ubuntu-24.04
|
|
||||||
container: debian:13
|
container: debian:13
|
||||||
env:
|
env: { RELEASE_TAG: "${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}" }
|
||||||
RELEASE_TAG: ${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Prepare tools (Debian)
|
- name: Prepare tools (Debian)
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -44,224 +58,101 @@ jobs:
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
apt-get update
|
apt-get update
|
||||||
apt-get install -y sudo git rsync findutils tar gzip unzip which curl jq wget file \
|
apt-get install -y sudo git rsync findutils tar gzip unzip which curl jq wget file ca-certificates desktop-file-utils xdg-utils fakeroot dpkg-dev libc6 libgcc-s1 libstdc++6 zlib1g libicu-dev libssl-dev
|
||||||
ca-certificates desktop-file-utils xdg-utils fakeroot dpkg-dev \
|
|
||||||
libc6 libgcc-s1 libstdc++6 zlib1g libicu-dev libssl-dev
|
|
||||||
|
|
||||||
- name: Checkout repo (for scripts)
|
- name: Checkout repo (for scripts)
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
with:
|
with: { submodules: 'recursive', fetch-depth: '0' }
|
||||||
submodules: 'recursive'
|
|
||||||
fetch-depth: '0'
|
|
||||||
|
|
||||||
- name: Ensure script permissions
|
- name: Ensure script permissions
|
||||||
run: chmod 755 package-debian.sh
|
run: chmod 755 package-debian.sh
|
||||||
|
|
||||||
- name: Package DEB (Debian-family)
|
- name: Package DEB (Debian-family)
|
||||||
run: ./package-debian.sh "${RELEASE_TAG}" --arch all
|
run: ./package-debian.sh "${RELEASE_TAG}" --arch all
|
||||||
|
|
||||||
- name: Collect DEBs into workspace
|
- name: Collect DEBs into workspace
|
||||||
run: |
|
run: |
|
||||||
mkdir -p "$GITHUB_WORKSPACE/dist/deb"
|
mkdir -p "$GITHUB_WORKSPACE/dist/deb"
|
||||||
rsync -av "$HOME/debbuild/" "$GITHUB_WORKSPACE/dist/deb/" || true
|
rsync -av "$HOME/debbuild/" "$GITHUB_WORKSPACE/dist/deb/" || true
|
||||||
find "$GITHUB_WORKSPACE/dist/deb" -name "v2rayn_*_amd64.deb" \
|
|
||||||
-exec mv {} "$GITHUB_WORKSPACE/dist/deb/v2rayN-linux-64.deb" \; || true
|
find "$GITHUB_WORKSPACE/dist/deb" -name "v2rayn_*_amd64.deb" -exec mv {} "$GITHUB_WORKSPACE/dist/deb/v2rayN-linux-64.deb" \; || true
|
||||||
find "$GITHUB_WORKSPACE/dist/deb" -name "v2rayn_*_arm64.deb" \
|
find "$GITHUB_WORKSPACE/dist/deb" -name "v2rayn_*_arm64.deb" -exec mv {} "$GITHUB_WORKSPACE/dist/deb/v2rayN-linux-arm64.deb" \; || true
|
||||||
-exec mv {} "$GITHUB_WORKSPACE/dist/deb/v2rayN-linux-arm64.deb" \; || true
|
find "$GITHUB_WORKSPACE/dist/deb" -name "v2rayn_*_riscv64.deb" -exec mv {} "$GITHUB_WORKSPACE/dist/deb/v2rayN-linux-riscv64.deb" \; || true
|
||||||
|
find "$GITHUB_WORKSPACE/dist/deb" -name "v2rayn_*_ppc64el.deb" -exec mv {} "$GITHUB_WORKSPACE/dist/deb/v2rayN-linux-ppc64le.deb" \; || true
|
||||||
|
find "$GITHUB_WORKSPACE/dist/deb" -name "v2rayn_*_loong64.deb" -exec mv {} "$GITHUB_WORKSPACE/dist/deb/v2rayN-linux-loong64.deb" \; || true
|
||||||
|
|
||||||
echo "==== Dist tree ===="
|
echo "==== Dist tree ===="
|
||||||
ls -R "$GITHUB_WORKSPACE/dist/deb" || true
|
ls -R "$GITHUB_WORKSPACE/dist/deb" || true
|
||||||
|
- name: Upload DEB artifact
|
||||||
- name: Upload DEBs to release
|
uses: actions/upload-artifact@v7
|
||||||
uses: svenstaro/upload-release-action@v2
|
with: { name: release-deb, path: "dist/deb/**/*.deb", if-no-files-found: error }
|
||||||
with:
|
|
||||||
file: dist/deb/**/*.deb
|
|
||||||
tag: ${{ env.RELEASE_TAG }}
|
|
||||||
file_glob: true
|
|
||||||
prerelease: true
|
|
||||||
|
|
||||||
rpm:
|
rpm:
|
||||||
name: build and release rpm x64 & arm64
|
name: build and release rpm x64 & arm64 & riscv64 & ppc64le & loong64
|
||||||
if: |
|
if: (github.event_name == 'workflow_dispatch' && inputs.release_tag != '') || (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
|
||||||
(github.event_name == 'workflow_dispatch' && inputs.release_tag != '') ||
|
runs-on: ubuntu-26.04
|
||||||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
|
|
||||||
runs-on: ubuntu-24.04
|
|
||||||
container: registry.access.redhat.com/ubi10/ubi
|
container: registry.access.redhat.com/ubi10/ubi
|
||||||
env:
|
env: { RELEASE_TAG: "${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}" }
|
||||||
RELEASE_TAG: ${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Prepare tools (Red Hat)
|
- name: Prepare tools (Red Hat)
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
. /etc/os-release
|
. /etc/os-release
|
||||||
EL_MAJOR="${VERSION_ID%%.*}"
|
EL_MAJOR="${VERSION_ID%%.*}"
|
||||||
echo "EL_MAJOR=${EL_MAJOR}"
|
echo "EL_MAJOR=${EL_MAJOR}"
|
||||||
|
|
||||||
dnf -y makecache || true
|
dnf -y makecache || true
|
||||||
command -v curl >/dev/null || dnf -y install curl ca-certificates
|
command -v curl >/dev/null || dnf -y install curl ca-certificates
|
||||||
|
|
||||||
ARCH="$(uname -m)"
|
ARCH="$(uname -m)"
|
||||||
case "$ARCH" in x86_64|aarch64) ;; *) echo "Unsupported arch: $ARCH"; exit 1 ;; esac
|
case "$ARCH" in x86_64|aarch64) ;; *) echo "Unsupported arch: $ARCH"; exit 1 ;; esac
|
||||||
|
|
||||||
install_epel_from_dir() {
|
install_epel_from_dir() {
|
||||||
local base="$1" rpm
|
local base="$1" rpm
|
||||||
echo "Try: $base"
|
echo "Try: $base"
|
||||||
|
rpm="$({ curl -fsSL "$base/Packages/" 2>/dev/null; curl -fsSL "$base/Packages/e/" 2>/dev/null | sed 's|href="|href="e/|'; } |
|
||||||
rpm="$(
|
sed -n 's/.*href="\([^"]*epel-release-[^"]*\.noarch\.rpm\)".*/\1/p' | sort -V | tail -n1)" || true
|
||||||
{
|
[[ -n "$rpm" ]] || return 1
|
||||||
curl -fsSL "$base/Packages/" 2>/dev/null
|
dnf -y install "$base/Packages/$rpm"
|
||||||
curl -fsSL "$base/Packages/e/" 2>/dev/null | sed 's|href="|href="e/|'
|
|
||||||
} |
|
|
||||||
sed -n 's/.*href="\([^"]*epel-release-[^"]*\.noarch\.rpm\)".*/\1/p' |
|
|
||||||
sort -V | tail -n1
|
|
||||||
)" || true
|
|
||||||
|
|
||||||
if [[ -n "$rpm" ]]; then
|
|
||||||
dnf -y install "$base/Packages/$rpm"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
return 1
|
|
||||||
}
|
}
|
||||||
|
|
||||||
FEDORA="https://dl.fedoraproject.org/pub/epel/epel-release-latest-${EL_MAJOR}.noarch.rpm"
|
FEDORA="https://dl.fedoraproject.org/pub/epel/epel-release-latest-${EL_MAJOR}.noarch.rpm"
|
||||||
|
ROCKY="https://dl.rockylinux.org/pub/rocky/${EL_MAJOR}/extras/${ARCH}/os"
|
||||||
|
ALMA="https://repo.almalinux.org/almalinux/${EL_MAJOR}/extras/${ARCH}/os"
|
||||||
|
|
||||||
echo "Try Fedora: $FEDORA"
|
echo "Try Fedora: $FEDORA"
|
||||||
|
curl -fsSLI "$FEDORA" >/dev/null && dnf -y install "$FEDORA" ||
|
||||||
|
install_epel_from_dir "$ROCKY" ||
|
||||||
|
install_epel_from_dir "$ALMA" ||
|
||||||
|
{ echo "EPEL bootstrap failed (Fedora/Rocky/Alma)"; exit 1; }
|
||||||
|
|
||||||
if curl -fsSLI "$FEDORA" >/dev/null; then
|
dnf -y install sudo git rpm-build rpmdevtools dnf-plugins-core rsync findutils tar gzip unzip which
|
||||||
dnf -y install "$FEDORA"
|
|
||||||
else
|
|
||||||
ROCKY="https://dl.rockylinux.org/pub/rocky/${EL_MAJOR}/extras/${ARCH}/os"
|
|
||||||
if install_epel_from_dir "$ROCKY"; then
|
|
||||||
:
|
|
||||||
else
|
|
||||||
ALMA="https://repo.almalinux.org/almalinux/${EL_MAJOR}/extras/${ARCH}/os"
|
|
||||||
if install_epel_from_dir "$ALMA"; then
|
|
||||||
:
|
|
||||||
else
|
|
||||||
echo "EPEL bootstrap failed (Fedora/Rocky/Alma)"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
dnf -y install sudo git rpm-build rpmdevtools dnf-plugins-core \
|
|
||||||
rsync findutils tar gzip unzip which
|
|
||||||
|
|
||||||
dnf repolist | grep -i epel || true
|
dnf repolist | grep -i epel || true
|
||||||
|
|
||||||
- name: Checkout repo (for scripts)
|
- name: Checkout repo (for scripts)
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
with:
|
with: { submodules: 'recursive', fetch-depth: '0' }
|
||||||
submodules: 'recursive'
|
|
||||||
fetch-depth: '0'
|
|
||||||
|
|
||||||
- name: Ensure script permissions
|
- name: Ensure script permissions
|
||||||
run: chmod 755 package-rhel.sh
|
run: chmod 755 package-rhel.sh
|
||||||
|
|
||||||
- name: Package RPM (RHEL-family)
|
- name: Package RPM (RHEL-family)
|
||||||
run: ./package-rhel.sh "${RELEASE_TAG}" --arch all
|
run: ./package-rhel.sh "${RELEASE_TAG}" --arch all
|
||||||
|
|
||||||
- name: Collect RPMs into workspace
|
- name: Collect RPMs into workspace
|
||||||
run: |
|
run: |
|
||||||
mkdir -p "$GITHUB_WORKSPACE/dist/rpm"
|
mkdir -p "$GITHUB_WORKSPACE/dist/rpm"
|
||||||
rsync -av "$HOME/rpmbuild/RPMS/" "$GITHUB_WORKSPACE/dist/rpm/" || true
|
rsync -av "$HOME/rpmbuild/RPMS/" "$GITHUB_WORKSPACE/dist/rpm/" || true
|
||||||
find "$GITHUB_WORKSPACE/dist/rpm" -name "v2rayN-*-1*.x86_64.rpm" -exec mv {} "$GITHUB_WORKSPACE/dist/rpm/v2rayN-linux-rhel-64.rpm" \; || true
|
|
||||||
|
find "$GITHUB_WORKSPACE/dist/rpm" -name "v2rayN-*-1*.x86_64.rpm" -exec mv {} "$GITHUB_WORKSPACE/dist/rpm/v2rayN-linux-rhel-64.rpm" \; || true
|
||||||
find "$GITHUB_WORKSPACE/dist/rpm" -name "v2rayN-*-1*.aarch64.rpm" -exec mv {} "$GITHUB_WORKSPACE/dist/rpm/v2rayN-linux-rhel-arm64.rpm" \; || true
|
find "$GITHUB_WORKSPACE/dist/rpm" -name "v2rayN-*-1*.aarch64.rpm" -exec mv {} "$GITHUB_WORKSPACE/dist/rpm/v2rayN-linux-rhel-arm64.rpm" \; || true
|
||||||
|
find "$GITHUB_WORKSPACE/dist/rpm" -name "v2rayN-*-1*.riscv64.rpm" -exec mv {} "$GITHUB_WORKSPACE/dist/rpm/v2rayN-linux-rhel-riscv64.rpm" \; || true
|
||||||
|
find "$GITHUB_WORKSPACE/dist/rpm" -name "v2rayN-*-1*.ppc64le.rpm" -exec mv {} "$GITHUB_WORKSPACE/dist/rpm/v2rayN-linux-rhel-ppc64le.rpm" \; || true
|
||||||
|
find "$GITHUB_WORKSPACE/dist/rpm" -name "v2rayN-*-1*.loongarch64.rpm" -exec mv {} "$GITHUB_WORKSPACE/dist/rpm/v2rayN-linux-rhel-loong64.rpm" \; || true
|
||||||
|
|
||||||
echo "==== Dist tree ===="
|
echo "==== Dist tree ===="
|
||||||
ls -R "$GITHUB_WORKSPACE/dist/rpm" || true
|
ls -R "$GITHUB_WORKSPACE/dist/rpm" || true
|
||||||
|
- name: Upload RPM artifact
|
||||||
|
uses: actions/upload-artifact@v7
|
||||||
|
with: { name: release-rpm, path: "dist/rpm/**/*.rpm", if-no-files-found: error }
|
||||||
|
|
||||||
- name: Upload RPMs to release
|
deb-x86:
|
||||||
uses: svenstaro/upload-release-action@v2
|
name: build and release deb x86
|
||||||
with:
|
if: (github.event_name == 'workflow_dispatch' && inputs.release_tag != '') || (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
|
||||||
file: dist/rpm/**/*.rpm
|
runs-on: ubuntu-26.04
|
||||||
tag: ${{ env.RELEASE_TAG }}
|
|
||||||
file_glob: true
|
|
||||||
prerelease: true
|
|
||||||
|
|
||||||
rpm-riscv64:
|
|
||||||
name: build and release rpm riscv64
|
|
||||||
if: |
|
|
||||||
(github.event_name == 'workflow_dispatch' && inputs.release_tag != '') ||
|
|
||||||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
|
|
||||||
runs-on: ubuntu-24.04-riscv
|
|
||||||
container: rockylinux/rockylinux:10
|
|
||||||
env:
|
|
||||||
RELEASE_TAG: ${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Prepare tools (Red Hat)
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
dnf -y makecache
|
|
||||||
dnf -y install \
|
|
||||||
sudo git rpm-build rpmdevtools dnf-plugins-core \
|
|
||||||
rsync findutils tar gzip unzip which jq
|
|
||||||
|
|
||||||
- name: Checkout repo (for scripts)
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ github.token }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
rm -rf ./*
|
|
||||||
git init .
|
|
||||||
git config --global --add safe.directory "$PWD"
|
|
||||||
git remote add origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"
|
|
||||||
git fetch --depth=1 origin "${GITHUB_SHA}"
|
|
||||||
git checkout FETCH_HEAD
|
|
||||||
git submodule update --init --recursive
|
|
||||||
|
|
||||||
- name: Ensure script permissions
|
|
||||||
run: chmod 755 package-rhel-riscv.sh
|
|
||||||
|
|
||||||
- name: Package RPM (RHEL-family)
|
|
||||||
run: ./package-rhel-riscv.sh "${RELEASE_TAG}"
|
|
||||||
|
|
||||||
- name: Collect RPMs into workspace
|
|
||||||
run: |
|
|
||||||
mkdir -p "$GITHUB_WORKSPACE/dist/rpm-riscv64"
|
|
||||||
rsync -av "$HOME/rpmbuild/RPMS/" "$GITHUB_WORKSPACE/dist/rpm-riscv64/" || true
|
|
||||||
find "$GITHUB_WORKSPACE/dist/rpm-riscv64" -name "*.riscv64.rpm" \
|
|
||||||
-exec mv {} "$GITHUB_WORKSPACE/dist/rpm-riscv64/v2rayN-linux-rhel-riscv64.rpm" \; || true
|
|
||||||
echo "==== Dist tree ===="
|
|
||||||
ls -R "$GITHUB_WORKSPACE/dist/rpm-riscv64" || true
|
|
||||||
|
|
||||||
- name: Upload RPMs to release
|
|
||||||
shell: bash
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ github.token }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
shopt -s globstar nullglob
|
|
||||||
|
|
||||||
files=(dist/rpm-riscv64/**/*.rpm)
|
|
||||||
(( ${#files[@]} )) || { echo "No RPMs found."; exit 1; }
|
|
||||||
|
|
||||||
api="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases/tags/${RELEASE_TAG}"
|
|
||||||
upload_url="$(curl -fsSL -H "Authorization: Bearer ${GITHUB_TOKEN}" "$api" | jq -r '.upload_url // empty' | sed 's/{?name,label}//')"
|
|
||||||
[[ "$upload_url" ]] || { echo "Release upload URL not found: ${RELEASE_TAG}"; exit 1; }
|
|
||||||
|
|
||||||
for f in "${files[@]}"; do
|
|
||||||
echo "Uploading ${f##*/}"
|
|
||||||
curl -fsSL -X POST \
|
|
||||||
-H "Authorization: Bearer ${GITHUB_TOKEN}" \
|
|
||||||
-H "Content-Type: application/x-rpm" \
|
|
||||||
--data-binary @"$f" \
|
|
||||||
"${upload_url}?name=${f##*/}"
|
|
||||||
done
|
|
||||||
|
|
||||||
deb-riscv64:
|
|
||||||
name: build and release deb riscv64
|
|
||||||
if: |
|
|
||||||
(github.event_name == 'workflow_dispatch' && inputs.release_tag != '') ||
|
|
||||||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
|
|
||||||
runs-on: ubuntu-24.04-riscv
|
|
||||||
container: debian:13
|
container: debian:13
|
||||||
env:
|
env: { RELEASE_TAG: "${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}" }
|
||||||
RELEASE_TAG: ${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Prepare tools (Debian)
|
- name: Prepare tools (Debian)
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -269,234 +160,118 @@ jobs:
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
apt-get update
|
apt-get update
|
||||||
apt-get install -y sudo git rsync findutils tar gzip unzip which curl jq wget file \
|
apt-get install -y sudo git rsync findutils tar gzip unzip which curl jq wget file ca-certificates desktop-file-utils xdg-utils fakeroot dpkg-dev libc6 libgcc-s1 libstdc++6 zlib1g libicu-dev libssl-dev
|
||||||
ca-certificates desktop-file-utils xdg-utils fakeroot dpkg-dev \
|
- name: Checkout repo (for scripts)
|
||||||
gcc make libc6-dev libgcc-s1 libstdc++6 zlib1g libatomic1
|
uses: actions/checkout@v7
|
||||||
|
with: { submodules: 'recursive', fetch-depth: '0' }
|
||||||
|
- name: Ensure script permissions
|
||||||
|
run: chmod 755 package-debian-x86.sh
|
||||||
|
- name: Package DEB x86 (Debian-family)
|
||||||
|
run: ./package-debian-x86.sh "${RELEASE_TAG}"
|
||||||
|
- name: Collect x86 DEB into workspace
|
||||||
|
run: |
|
||||||
|
mkdir -p "$GITHUB_WORKSPACE/dist/deb-x86"
|
||||||
|
rsync -av "$HOME/debbuild/" "$GITHUB_WORKSPACE/dist/deb-x86/" || true
|
||||||
|
|
||||||
|
find "$GITHUB_WORKSPACE/dist/deb-x86" -name "v2rayn_*_i386.deb" \
|
||||||
|
-exec mv {} "$GITHUB_WORKSPACE/dist/deb-x86/v2rayN-linux-86.deb" \; || true
|
||||||
|
|
||||||
|
echo "==== Dist tree ===="
|
||||||
|
ls -R "$GITHUB_WORKSPACE/dist/deb-x86" || true
|
||||||
|
- name: Upload x86 DEB artifact
|
||||||
|
uses: actions/upload-artifact@v7
|
||||||
|
with: { name: release-deb-x86, path: "dist/deb-x86/**/*.deb", if-no-files-found: error }
|
||||||
|
|
||||||
|
rpm-x86:
|
||||||
|
name: build and release rpm x86
|
||||||
|
if: (github.event_name == 'workflow_dispatch' && inputs.release_tag != '') || (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
|
||||||
|
runs-on: ubuntu-26.04
|
||||||
|
container: registry.access.redhat.com/ubi10/ubi
|
||||||
|
env: { RELEASE_TAG: "${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}" }
|
||||||
|
steps:
|
||||||
|
- name: Prepare tools (Red Hat)
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
. /etc/os-release
|
||||||
|
EL_MAJOR="${VERSION_ID%%.*}"
|
||||||
|
echo "EL_MAJOR=${EL_MAJOR}"
|
||||||
|
dnf -y makecache || true
|
||||||
|
command -v curl >/dev/null || dnf -y install curl ca-certificates
|
||||||
|
ARCH="$(uname -m)"
|
||||||
|
case "$ARCH" in x86_64|aarch64) ;; *) echo "Unsupported arch: $ARCH"; exit 1 ;; esac
|
||||||
|
|
||||||
|
install_epel_from_dir() {
|
||||||
|
local base="$1" rpm
|
||||||
|
echo "Try: $base"
|
||||||
|
rpm="$({ curl -fsSL "$base/Packages/" 2>/dev/null; curl -fsSL "$base/Packages/e/" 2>/dev/null | sed 's|href="|href="e/|'; } |
|
||||||
|
sed -n 's/.*href="\([^"]*epel-release-[^"]*\.noarch\.rpm\)".*/\1/p' | sort -V | tail -n1)" || true
|
||||||
|
[[ -n "$rpm" ]] || return 1
|
||||||
|
dnf -y install "$base/Packages/$rpm"
|
||||||
|
}
|
||||||
|
|
||||||
|
FEDORA="https://dl.fedoraproject.org/pub/epel/epel-release-latest-${EL_MAJOR}.noarch.rpm"
|
||||||
|
ROCKY="https://dl.rockylinux.org/pub/rocky/${EL_MAJOR}/extras/${ARCH}/os"
|
||||||
|
ALMA="https://repo.almalinux.org/almalinux/${EL_MAJOR}/extras/${ARCH}/os"
|
||||||
|
|
||||||
|
echo "Try Fedora: $FEDORA"
|
||||||
|
curl -fsSLI "$FEDORA" >/dev/null && dnf -y install "$FEDORA" ||
|
||||||
|
install_epel_from_dir "$ROCKY" ||
|
||||||
|
install_epel_from_dir "$ALMA" ||
|
||||||
|
{ echo "EPEL bootstrap failed (Fedora/Rocky/Alma)"; exit 1; }
|
||||||
|
|
||||||
|
dnf -y install sudo git rpm-build rpmdevtools dnf-plugins-core rsync findutils tar gzip unzip which python3
|
||||||
|
dnf repolist | grep -i epel || true
|
||||||
|
|
||||||
- name: Checkout repo (for scripts)
|
- name: Checkout repo (for scripts)
|
||||||
shell: bash
|
uses: actions/checkout@v7
|
||||||
env:
|
with: { submodules: 'recursive', fetch-depth: '0' }
|
||||||
GITHUB_TOKEN: ${{ github.token }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
rm -rf ./*
|
|
||||||
git init .
|
|
||||||
git config --global --add safe.directory "$PWD"
|
|
||||||
git remote add origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"
|
|
||||||
git fetch --depth=1 origin "${GITHUB_SHA}"
|
|
||||||
git checkout FETCH_HEAD
|
|
||||||
git submodule update --init --recursive
|
|
||||||
|
|
||||||
- name: Ensure script permissions
|
- name: Ensure script permissions
|
||||||
run: chmod 755 package-debian-riscv.sh
|
run: chmod 755 package-rhel-x86.sh
|
||||||
|
|
||||||
- name: Package DEB (Debian-family)
|
- name: Package RPM x86 (RHEL-family)
|
||||||
run: ./package-debian-riscv.sh "${RELEASE_TAG}"
|
run: ./package-rhel-x86.sh "${RELEASE_TAG}"
|
||||||
|
|
||||||
- name: Collect DEBs into workspace
|
- name: Collect x86 RPM into workspace
|
||||||
run: |
|
run: |
|
||||||
mkdir -p "$GITHUB_WORKSPACE/dist/deb-riscv64"
|
mkdir -p "$GITHUB_WORKSPACE/dist/rpm-x86"
|
||||||
rsync -av "$HOME/debbuild/" "$GITHUB_WORKSPACE/dist/deb-riscv64/" || true
|
rsync -av "$HOME/rpmbuild/RPMS/" "$GITHUB_WORKSPACE/dist/rpm-x86/" || true
|
||||||
find "$GITHUB_WORKSPACE/dist/deb-riscv64" -name "*.deb" \
|
|
||||||
-exec mv {} "$GITHUB_WORKSPACE/dist/deb-riscv64/v2rayN-linux-riscv64.deb" \; || true
|
|
||||||
echo "==== Dist tree ===="
|
|
||||||
ls -R "$GITHUB_WORKSPACE/dist/deb-riscv64" || true
|
|
||||||
|
|
||||||
- name: Upload DEBs to release
|
find "$GITHUB_WORKSPACE/dist/rpm-x86" -name "v2rayN-*-1*.i686.rpm" \
|
||||||
shell: bash
|
-exec mv {} "$GITHUB_WORKSPACE/dist/rpm-x86/v2rayN-linux-rhel-86.rpm" \; || true
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ github.token }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
shopt -s globstar nullglob
|
|
||||||
|
|
||||||
files=(dist/deb-riscv64/**/*.deb)
|
|
||||||
(( ${#files[@]} )) || { echo "No DEBs found."; exit 1; }
|
|
||||||
|
|
||||||
api="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/releases/tags/${RELEASE_TAG}"
|
|
||||||
upload_url="$(curl -fsSL -H "Authorization: Bearer ${GITHUB_TOKEN}" "$api" | jq -r '.upload_url // empty' | sed 's/{?name,label}//')"
|
|
||||||
[[ "$upload_url" ]] || { echo "Release upload URL not found: ${RELEASE_TAG}"; exit 1; }
|
|
||||||
|
|
||||||
for f in "${files[@]}"; do
|
|
||||||
echo "Uploading ${f##*/}"
|
|
||||||
curl -fsSL -X POST \
|
|
||||||
-H "Authorization: Bearer ${GITHUB_TOKEN}" \
|
|
||||||
-H "Content-Type: application/vnd.debian.binary-package" \
|
|
||||||
--data-binary @"$f" \
|
|
||||||
"${upload_url}?name=${f##*/}"
|
|
||||||
done
|
|
||||||
|
|
||||||
deb-loong64:
|
|
||||||
name: build and release deb loong64
|
|
||||||
if: |
|
|
||||||
(github.event_name == 'workflow_dispatch' && inputs.release_tag != '') ||
|
|
||||||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/'))
|
|
||||||
runs-on: ubuntu-24.04
|
|
||||||
|
|
||||||
env:
|
|
||||||
RELEASE_TAG: ${{ case(inputs.release_tag != '', inputs.release_tag, github.ref_name) }}
|
|
||||||
QCOW2_URL: https://github.com/xujiegb/debian-loong64-qcow2/releases/download/13.5/debian13-loong64.qcow2
|
|
||||||
EFI_CODE_URL: https://github.com/xujiegb/debian-loong64-qcow2/releases/download/13.5/edk2-loongarch64-code.fd
|
|
||||||
EFI_VARS_URL: https://github.com/xujiegb/debian-loong64-qcow2/releases/download/13.5/edk2-loongarch64-vars.fd
|
|
||||||
QCOW2_IMAGE: debian13-loong64.qcow2
|
|
||||||
EFI_CODE: edk2-loongarch64-code.fd
|
|
||||||
EFI_VARS: edk2-loongarch64-vars.fd
|
|
||||||
QEMU_VERSION: 10.2.3
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Prepare host tools
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y rsync qemu-utils expect wget curl ca-certificates libfdt1 libglib2.0-0 libpixman-1-0 libslirp0
|
|
||||||
|
|
||||||
- name: Checkout repo
|
|
||||||
uses: actions/checkout@v6
|
|
||||||
with:
|
|
||||||
submodules: recursive
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Download QEMU prebuild
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
wget -O qemu-linux-x64.tar.gz \
|
|
||||||
"https://github.com/xujiegb/qemu-linux-prebuild/releases/download/${QEMU_VERSION}/qemu-linux-x64.tar.gz"
|
|
||||||
|
|
||||||
tar -xzf qemu-linux-x64.tar.gz
|
|
||||||
|
|
||||||
mkdir -p "$HOME/qemu-install"
|
|
||||||
|
|
||||||
rsync -a qemu-linux-x64/ "$HOME/qemu-install/"
|
|
||||||
|
|
||||||
"$HOME/qemu-install/bin/qemu-system-loongarch64" --version
|
|
||||||
|
|
||||||
- name: Download loong64 qcow2 and EFI firmware
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
wget -O "$QCOW2_IMAGE" "$QCOW2_URL"
|
|
||||||
wget -O "$EFI_CODE" "$EFI_CODE_URL"
|
|
||||||
wget -O "$EFI_VARS" "$EFI_VARS_URL"
|
|
||||||
|
|
||||||
qemu-img info "$QCOW2_IMAGE"
|
|
||||||
|
|
||||||
- name: Build loong64 DEB in VM through serial console
|
|
||||||
shell: bash
|
|
||||||
timeout-minutes: 180
|
|
||||||
env:
|
|
||||||
RELEASE_TAG: ${{ env.RELEASE_TAG }}
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
mkdir -p "$GITHUB_WORKSPACE/dist/deb-loong64"
|
|
||||||
|
|
||||||
expect <<'EOF'
|
|
||||||
log_user 1
|
|
||||||
set timeout -1
|
|
||||||
|
|
||||||
set release_tag $env(RELEASE_TAG)
|
|
||||||
set qemu_bin "$env(HOME)/qemu-install/bin/qemu-system-loongarch64"
|
|
||||||
set qemu_rom_dir "$env(HOME)/qemu-install/share/qemu"
|
|
||||||
|
|
||||||
set workspace $env(GITHUB_WORKSPACE)
|
|
||||||
set repo $env(GITHUB_REPOSITORY)
|
|
||||||
set sha $env(GITHUB_SHA)
|
|
||||||
|
|
||||||
set qcow2 $env(QCOW2_IMAGE)
|
|
||||||
set efi_code $env(EFI_CODE)
|
|
||||||
set efi_vars $env(EFI_VARS)
|
|
||||||
|
|
||||||
proc wait_prompt {} {
|
|
||||||
expect {
|
|
||||||
-re "__CI_PROMPT__# " {}
|
|
||||||
timeout { exit 1 }
|
|
||||||
eof { exit 1 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
proc run_cmd {cmd} {
|
|
||||||
send -- "$cmd\r"
|
|
||||||
wait_prompt
|
|
||||||
}
|
|
||||||
|
|
||||||
spawn $qemu_bin \
|
|
||||||
-L $qemu_rom_dir \
|
|
||||||
-machine virt \
|
|
||||||
-accel tcg,thread=multi,tb-size=2048 \
|
|
||||||
-cpu la464 \
|
|
||||||
-m 9216 \
|
|
||||||
-smp 4 \
|
|
||||||
-drive if=pflash,format=raw,unit=0,file=$efi_code,readonly=on \
|
|
||||||
-drive if=pflash,format=raw,unit=1,file=$efi_vars \
|
|
||||||
-device virtio-blk-pci,drive=hd0,bootindex=1 \
|
|
||||||
-drive if=none,media=disk,id=hd0,file=$qcow2,format=qcow2 \
|
|
||||||
-netdev user,id=net0 \
|
|
||||||
-device virtio-net-pci,netdev=net0 \
|
|
||||||
-virtfs local,path=$workspace,mount_tag=workspace,security_model=none,id=workspace \
|
|
||||||
-display none \
|
|
||||||
-serial stdio \
|
|
||||||
-monitor none
|
|
||||||
|
|
||||||
expect -re "login:|debian login:"
|
|
||||||
send -- "root\r"
|
|
||||||
|
|
||||||
expect -re "Password:|密码:|密码:"
|
|
||||||
send -- "password\r"
|
|
||||||
|
|
||||||
expect {
|
|
||||||
-re "# " {}
|
|
||||||
timeout { exit 1 }
|
|
||||||
eof { exit 1 }
|
|
||||||
}
|
|
||||||
|
|
||||||
send -- "export TERM=dumb; export PS1='__CI_PROMPT__# '\r"
|
|
||||||
wait_prompt
|
|
||||||
|
|
||||||
run_cmd "mkdir -p /workspace"
|
|
||||||
run_cmd "mount -t 9p -o trans=virtio,version=9p2000.L workspace /workspace || mount -t 9p -o trans=virtio workspace /workspace"
|
|
||||||
run_cmd "IFACE=\$(ip -o link show | awk -F': ' '\$2 != \"lo\" {print \$2; exit}') ; ip link set \$IFACE up || true"
|
|
||||||
run_cmd "dhclient \$IFACE || true"
|
|
||||||
run_cmd "printf 'nameserver 10.0.2.3\nnameserver 1.1.1.1\n' >/etc/resolv.conf"
|
|
||||||
run_cmd "apt-get update || apt-get update || apt-get update"
|
|
||||||
run_cmd "DEBIAN_FRONTEND=noninteractive apt-get install -y sudo git rsync findutils tar gzip unzip which curl jq wget file ca-certificates desktop-file-utils xdg-utils fakeroot dpkg-dev gcc make libc6-dev libgcc-s1 libstdc++6 zlib1g libatomic1"
|
|
||||||
run_cmd "rm -rf /root/v2rayN-src"
|
|
||||||
run_cmd "git clone --recursive https://github.com/$repo.git /root/v2rayN-src"
|
|
||||||
run_cmd "cd /root/v2rayN-src && git fetch --depth=1 origin $sha && git checkout FETCH_HEAD && git submodule update --init --recursive"
|
|
||||||
run_cmd "cd /root/v2rayN-src && chmod 755 package-debian-loong.sh"
|
|
||||||
|
|
||||||
send -- "cd /root/v2rayN-src; cat >/tmp/run-loong-build.sh <<'SCRIPT'\nset +e\nset -o pipefail\nbash -x ./package-debian-loong.sh \"\$RELEASE_TAG\" 2>&1 | tee /tmp/build.log\nrc=\$?\nmkdir -p /workspace/dist/deb-loong64\ncp -av /root/debbuild/*.deb /workspace/dist/deb-loong64/ 2>/dev/null || true\necho __BUILD_DONE__\$rc\nSCRIPT\nRELEASE_TAG=\"$release_tag\" bash /tmp/run-loong-build.sh\r"
|
|
||||||
|
|
||||||
expect {
|
|
||||||
-re "__BUILD_DONE__0" {
|
|
||||||
send -- "poweroff\r"
|
|
||||||
}
|
|
||||||
default {
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Collect DEBs
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
mkdir -p "$GITHUB_WORKSPACE/dist/deb-loong64"
|
|
||||||
|
|
||||||
find "$GITHUB_WORKSPACE/dist/deb-loong64" -name "*.deb" \
|
|
||||||
-exec mv {} "$GITHUB_WORKSPACE/dist/deb-loong64/v2rayN-linux-loong64.deb" \; || true
|
|
||||||
|
|
||||||
echo "==== Dist tree ===="
|
echo "==== Dist tree ===="
|
||||||
ls -R "$GITHUB_WORKSPACE/dist/deb-loong64"
|
ls -R "$GITHUB_WORKSPACE/dist/rpm-x86" || true
|
||||||
|
|
||||||
- name: Upload DEBs to release
|
- name: Upload x86 RPM artifact
|
||||||
uses: svenstaro/upload-release-action@v2
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with: { name: release-rpm-x86, path: "dist/rpm-x86/**/*.rpm", if-no-files-found: error }
|
||||||
file: dist/deb-loong64/**/*.deb
|
|
||||||
tag: ${{ env.RELEASE_TAG }}
|
release-deb:
|
||||||
file_glob: true
|
name: sign and upload deb x64 arm64 riscv64 ppc64le loong64
|
||||||
prerelease: true
|
needs: deb
|
||||||
|
uses: ./.github/workflows/upload-sign.yml
|
||||||
|
with: { release_tag: "${{ inputs.release_tag || github.ref_name }}", artifact_name: release-deb, file_pattern: "*.deb" }
|
||||||
|
secrets: { GPG_PRIVATE_KEY: "${{ secrets.GPG_PRIVATE_KEY }}" }
|
||||||
|
|
||||||
|
release-rpm:
|
||||||
|
name: sign and upload rpm x64 arm64 riscv64 ppc64le loong64
|
||||||
|
needs: rpm
|
||||||
|
uses: ./.github/workflows/upload-sign.yml
|
||||||
|
with: { release_tag: "${{ inputs.release_tag || github.ref_name }}", artifact_name: release-rpm, file_pattern: "*.rpm" }
|
||||||
|
secrets: { GPG_PRIVATE_KEY: "${{ secrets.GPG_PRIVATE_KEY }}" }
|
||||||
|
|
||||||
|
release-deb-x86:
|
||||||
|
name: sign and upload deb x86
|
||||||
|
needs: deb-x86
|
||||||
|
uses: ./.github/workflows/upload-sign.yml
|
||||||
|
with: { release_tag: "${{ inputs.release_tag || github.ref_name }}", artifact_name: release-deb-x86, file_pattern: "*.deb" }
|
||||||
|
secrets: { GPG_PRIVATE_KEY: "${{ secrets.GPG_PRIVATE_KEY }}" }
|
||||||
|
|
||||||
|
release-rpm-x86:
|
||||||
|
name: sign and upload rpm x86
|
||||||
|
needs: rpm-x86
|
||||||
|
uses: ./.github/workflows/upload-sign.yml
|
||||||
|
with: { release_tag: "${{ inputs.release_tag || github.ref_name }}", artifact_name: release-rpm-x86, file_pattern: "*.rpm" }
|
||||||
|
secrets: { GPG_PRIVATE_KEY: "${{ secrets.GPG_PRIVATE_KEY }}" }
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ on:
|
|||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
actions: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -26,7 +27,24 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
target: macos
|
target: macos
|
||||||
release_tag: ${{ inputs.release_tag }}
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
|
build-aot:
|
||||||
|
uses: ./.github/workflows/build.yml
|
||||||
|
with:
|
||||||
|
target: macos
|
||||||
|
isAot: true
|
||||||
|
|
||||||
|
release-aot-zip:
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
needs: build-aot
|
||||||
|
uses: ./.github/workflows/package-zip.yml
|
||||||
|
with:
|
||||||
|
target: macos
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
isAot: true
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
dmg:
|
dmg:
|
||||||
name: package and release macOS dmg
|
name: package and release macOS dmg
|
||||||
if: inputs.release_tag != ''
|
if: inputs.release_tag != ''
|
||||||
@@ -45,7 +63,7 @@ jobs:
|
|||||||
}}
|
}}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Restore build artifacts
|
- name: Restore build artifacts
|
||||||
uses: actions/download-artifact@v8
|
uses: actions/download-artifact@v8
|
||||||
@@ -62,13 +80,24 @@ jobs:
|
|||||||
- name: Package dmg
|
- name: Package dmg
|
||||||
run: ./package-osx.sh macos-$Arch v2rayN-macos-$Arch ${{ inputs.release_tag }}
|
run: ./package-osx.sh macos-$Arch v2rayN-macos-$Arch ${{ inputs.release_tag }}
|
||||||
|
|
||||||
- name: Sleep for race condition between matrix jobs
|
- name: Upload dmg artifact
|
||||||
run: sleep "$(od -An -N2 -tu2 /dev/urandom | awk 'NR==1{printf "%.2f", $1/5461}')"
|
uses: actions/upload-artifact@v7
|
||||||
|
|
||||||
- name: Upload dmg to release
|
|
||||||
uses: svenstaro/upload-release-action@v2
|
|
||||||
with:
|
with:
|
||||||
file: ${{ github.workspace }}/v2rayN*.dmg
|
name: release-dmg-${{ matrix.arch }}
|
||||||
tag: ${{ inputs.release_tag }}
|
path: v2rayN*.dmg
|
||||||
file_glob: true
|
if-no-files-found: error
|
||||||
prerelease: true
|
|
||||||
|
release-dmg:
|
||||||
|
name: sign and upload macOS dmg
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
needs: dmg
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
arch: [ x64, arm64 ]
|
||||||
|
uses: ./.github/workflows/upload-sign.yml
|
||||||
|
with:
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
artifact_name: release-dmg-${{ matrix.arch }}
|
||||||
|
file_pattern: '*.dmg'
|
||||||
|
secrets:
|
||||||
|
GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ on:
|
|||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
actions: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -26,3 +27,20 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
target: windows-desktop
|
target: windows-desktop
|
||||||
release_tag: ${{ inputs.release_tag }}
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
secrets: inherit
|
||||||
|
|
||||||
|
build-aot:
|
||||||
|
uses: ./.github/workflows/build.yml
|
||||||
|
with:
|
||||||
|
target: windows
|
||||||
|
isAot: true
|
||||||
|
|
||||||
|
release-aot-zip:
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
needs: build-aot
|
||||||
|
uses: ./.github/workflows/package-zip.yml
|
||||||
|
with:
|
||||||
|
target: windows-desktop
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
isAot: true
|
||||||
|
secrets: inherit
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
name: release Windows x86
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
release_tag:
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
actions: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
package-x86:
|
||||||
|
name: build and release windows x86 WPF & Avalonia
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
runs-on: windows-latest
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- flavor: wpf
|
||||||
|
project: ./v2rayN/v2rayN/v2rayN.csproj
|
||||||
|
zip_name: v2rayN-windows-86.zip
|
||||||
|
- flavor: desktop
|
||||||
|
project: ./v2rayN/v2rayN.Desktop/v2rayN.Desktop.csproj
|
||||||
|
zip_name: v2rayN-windows-86-desktop.zip
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Purge SDKs
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
echo "Before:"
|
||||||
|
dotnet --list-sdks
|
||||||
|
|
||||||
|
dotnet --list-sdks | % {
|
||||||
|
$_ -match '^\S+\s+\[(.+)\]$' > $null
|
||||||
|
$d = Join-Path $Matches[1] $_.Split()[0]
|
||||||
|
Write-Host "Removing $d"
|
||||||
|
if ($IsWindows) { rm $d -r -fo } else { sudo rm -rf "$d" }
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "After:"
|
||||||
|
dotnet --list-sdks 2>$null; $LASTEXITCODE=0
|
||||||
|
|
||||||
|
- name: Setup .NET 10.0.1xx
|
||||||
|
uses: actions/setup-dotnet@v6
|
||||||
|
with:
|
||||||
|
dotnet-version: 10.0.1xx
|
||||||
|
|
||||||
|
- name: Publish ${{ matrix.flavor }} win-x86
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
dotnet restore "${{ matrix.project }}" -r win-x86
|
||||||
|
|
||||||
|
dotnet publish "${{ matrix.project }}" `
|
||||||
|
-c Release `
|
||||||
|
-r win-x86 `
|
||||||
|
-p:SelfContained=true `
|
||||||
|
-p:EnableWindowsTargeting=true `
|
||||||
|
-o "publish/${{ matrix.flavor }}"
|
||||||
|
|
||||||
|
- name: Publish AmazTool win-x86
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
dotnet publish "./v2rayN/AmazTool/AmazTool.csproj" `
|
||||||
|
-c Release `
|
||||||
|
-r win-x86 `
|
||||||
|
-p:SelfContained=true `
|
||||||
|
-p:PublishTrimmed=true `
|
||||||
|
-p:EnableWindowsTargeting=true `
|
||||||
|
-o "publish/${{ matrix.flavor }}"
|
||||||
|
|
||||||
|
- name: Detect bundled core versions
|
||||||
|
id: detect-core
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Force -Path "tmp/probe" | Out-Null
|
||||||
|
|
||||||
|
Invoke-WebRequest -Uri "https://github.com/2dust/v2rayN-core-bin/raw/refs/heads/master/v2rayN-windows-64/bin/xray/xray.exe" -OutFile "tmp/probe/xray.exe"
|
||||||
|
$xrayOutput = (& "tmp/probe/xray.exe" version) -join "`n"
|
||||||
|
Write-Host $xrayOutput
|
||||||
|
|
||||||
|
$xrayMatch = [regex]::Match($xrayOutput, 'Xray\s+([0-9.]+)')
|
||||||
|
if ($xrayMatch.Success) {
|
||||||
|
$xrayVer = $xrayMatch.Groups[1].Value
|
||||||
|
} else {
|
||||||
|
throw "Failed to detect Xray version"
|
||||||
|
}
|
||||||
|
|
||||||
|
Invoke-WebRequest -Uri "https://github.com/2dust/v2rayN-core-bin/raw/refs/heads/master/v2rayN-windows-64/bin/sing_box/sing-box.exe" -OutFile "tmp/probe/sing-box.exe"
|
||||||
|
$singOutput = (& "tmp/probe/sing-box.exe" version) -join "`n"
|
||||||
|
Write-Host $singOutput
|
||||||
|
|
||||||
|
$singMatch = [regex]::Match($singOutput, 'sing-box version\s+([0-9.]+)')
|
||||||
|
if ($singMatch.Success) {
|
||||||
|
$singVer = $singMatch.Groups[1].Value
|
||||||
|
} else {
|
||||||
|
throw "Failed to detect sing-box version"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host "Bundled Xray version: $xrayVer"
|
||||||
|
Write-Host "Bundled sing-box version: $singVer"
|
||||||
|
|
||||||
|
"xray_version=$xrayVer" >> $env:GITHUB_OUTPUT
|
||||||
|
"sing_version=$singVer" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Download x86 cores and rule assets
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
$headers = @{
|
||||||
|
Authorization = "Bearer $env:GH_TOKEN"
|
||||||
|
Accept = "application/vnd.github+json"
|
||||||
|
"X-GitHub-Api-Version" = "2022-11-28"
|
||||||
|
}
|
||||||
|
|
||||||
|
$root = "publish/${{ matrix.flavor }}"
|
||||||
|
$bin = Join-Path $root "bin"
|
||||||
|
$xrayDir = Join-Path $bin "xray"
|
||||||
|
$singDir = Join-Path $bin "sing_box"
|
||||||
|
$srssDir = Join-Path $bin "srss"
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Force -Path $xrayDir, $singDir, $srssDir | Out-Null
|
||||||
|
|
||||||
|
$xrayVer = "${{ steps.detect-core.outputs.xray_version }}"
|
||||||
|
$singVer = "${{ steps.detect-core.outputs.sing_version }}"
|
||||||
|
|
||||||
|
$xrayTag = "v$xrayVer"
|
||||||
|
$singTag = "v$singVer"
|
||||||
|
|
||||||
|
$xrayUrl = "https://github.com/XTLS/Xray-core/releases/download/$xrayTag/Xray-windows-32.zip"
|
||||||
|
$singUrl = "https://github.com/SagerNet/sing-box/releases/download/$singTag/sing-box-$singVer-windows-386.zip"
|
||||||
|
|
||||||
|
Write-Host "Bundled Xray version: $xrayVer"
|
||||||
|
Write-Host "Bundled sing-box version: $singVer"
|
||||||
|
Write-Host "Xray: $xrayUrl"
|
||||||
|
Write-Host "sing-box: $singUrl"
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Force -Path "tmp" | Out-Null
|
||||||
|
|
||||||
|
Invoke-WebRequest -Uri $xrayUrl -OutFile "tmp/xray.zip"
|
||||||
|
Expand-Archive -Force "tmp/xray.zip" "tmp/xray"
|
||||||
|
|
||||||
|
Get-ChildItem "tmp/xray" -Recurse -Include "*.exe","*.dll" | ForEach-Object {
|
||||||
|
Copy-Item $_.FullName (Join-Path $xrayDir $_.Name) -Force
|
||||||
|
}
|
||||||
|
|
||||||
|
Invoke-WebRequest -Uri $singUrl -OutFile "tmp/sing-box.zip"
|
||||||
|
Expand-Archive -Force "tmp/sing-box.zip" "tmp/sing-box"
|
||||||
|
|
||||||
|
$singExe = Get-ChildItem "tmp/sing-box" -Recurse -Filter "sing-box.exe" | Select-Object -First 1
|
||||||
|
if (-not $singExe) {
|
||||||
|
throw "sing-box.exe not found"
|
||||||
|
}
|
||||||
|
|
||||||
|
Copy-Item $singExe.FullName "$singDir/sing-box.exe" -Force
|
||||||
|
|
||||||
|
$cronet = Get-ChildItem "tmp/sing-box" -Recurse -Filter "libcronet*.dll" | Select-Object -First 1
|
||||||
|
if ($cronet) {
|
||||||
|
Copy-Item $cronet.FullName "$singDir/libcronet.dll" -Force
|
||||||
|
}
|
||||||
|
|
||||||
|
Invoke-WebRequest -Uri "https://github.com/Loyalsoldier/V2ray-rules-dat/releases/latest/download/geosite.dat" -OutFile "$bin/geosite.dat"
|
||||||
|
Invoke-WebRequest -Uri "https://github.com/Loyalsoldier/V2ray-rules-dat/releases/latest/download/geoip.dat" -OutFile "$bin/geoip.dat"
|
||||||
|
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/Loyalsoldier/geoip/release/geoip-only-cn-private.dat" -OutFile "$bin/geoip-only-cn-private.dat"
|
||||||
|
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb" -OutFile "$bin/Country.mmdb"
|
||||||
|
Invoke-WebRequest -Uri "https://github.com/MetaCubeX/meta-rules-dat/releases/latest/download/geoip.metadb" -OutFile "$bin/geoip.metadb"
|
||||||
|
|
||||||
|
$geoipRules = @(
|
||||||
|
"geoip-private.srs",
|
||||||
|
"geoip-cn.srs",
|
||||||
|
"geoip-facebook.srs",
|
||||||
|
"geoip-fastly.srs",
|
||||||
|
"geoip-google.srs",
|
||||||
|
"geoip-netflix.srs",
|
||||||
|
"geoip-telegram.srs",
|
||||||
|
"geoip-twitter.srs"
|
||||||
|
)
|
||||||
|
|
||||||
|
foreach ($f in $geoipRules) {
|
||||||
|
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/2dust/sing-box-rules/refs/heads/rule-set-geoip/$f" -OutFile "$srssDir/$f"
|
||||||
|
}
|
||||||
|
|
||||||
|
$geositeRules = @(
|
||||||
|
"geosite-cn.srs",
|
||||||
|
"geosite-gfw.srs",
|
||||||
|
"geosite-google.srs",
|
||||||
|
"geosite-greatfire.srs",
|
||||||
|
"geosite-geolocation-cn.srs",
|
||||||
|
"geosite-category-ads-all.srs",
|
||||||
|
"geosite-private.srs"
|
||||||
|
)
|
||||||
|
|
||||||
|
foreach ($f in $geositeRules) {
|
||||||
|
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/2dust/sing-box-rules/refs/heads/rule-set-geosite/$f" -OutFile "$srssDir/$f"
|
||||||
|
}
|
||||||
|
|
||||||
|
- name: Package zip
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
Compress-Archive `
|
||||||
|
-Path "publish/${{ matrix.flavor }}/*" `
|
||||||
|
-DestinationPath "${{ matrix.zip_name }}" `
|
||||||
|
-Force
|
||||||
|
|
||||||
|
- name: Upload zip artifact
|
||||||
|
uses: actions/upload-artifact@v7
|
||||||
|
with:
|
||||||
|
name: release-windows-x86-${{ matrix.flavor }}
|
||||||
|
path: ${{ matrix.zip_name }}
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
release-x86:
|
||||||
|
name: sign and upload windows x86
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
needs: package-x86
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
flavor: [ wpf, desktop ]
|
||||||
|
uses: ./.github/workflows/upload-sign.yml
|
||||||
|
with:
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
artifact_name: release-windows-x86-${{ matrix.flavor }}
|
||||||
|
file_pattern: '*.zip'
|
||||||
|
secrets:
|
||||||
|
GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
|
||||||
@@ -12,6 +12,7 @@ on:
|
|||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
actions: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -27,3 +28,4 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
target: windows
|
target: windows
|
||||||
release_tag: ${{ inputs.release_tag }}
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
secrets: inherit
|
||||||
|
|||||||
+81
-13
@@ -10,6 +10,10 @@ on:
|
|||||||
required: false
|
required: false
|
||||||
type: string
|
type: string
|
||||||
default: './v2rayN.Desktop/v2rayN.Desktop.csproj'
|
default: './v2rayN.Desktop/v2rayN.Desktop.csproj'
|
||||||
|
isAot:
|
||||||
|
required: false
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
@@ -22,11 +26,11 @@ jobs:
|
|||||||
case(
|
case(
|
||||||
inputs.target == 'macos', 'macos-latest',
|
inputs.target == 'macos', 'macos-latest',
|
||||||
inputs.target == 'linux', 'ubuntu-24.04',
|
inputs.target == 'linux', 'ubuntu-24.04',
|
||||||
|
inputs.target == 'windows', 'windows-latest',
|
||||||
'ubuntu-latest'
|
'ubuntu-latest'
|
||||||
)
|
)
|
||||||
}}
|
}}
|
||||||
env:
|
env:
|
||||||
Output: "${{ github.workspace }}/${{ matrix.arch }}"
|
|
||||||
RID: |-
|
RID: |-
|
||||||
${{
|
${{
|
||||||
case(
|
case(
|
||||||
@@ -40,32 +44,96 @@ jobs:
|
|||||||
${{
|
${{
|
||||||
case(
|
case(
|
||||||
inputs.target == 'windows', '-p:EnableWindowsTargeting=true',
|
inputs.target == 'windows', '-p:EnableWindowsTargeting=true',
|
||||||
|
inputs.target == 'linux', (matrix.arch == 'arm64' && '-p:LinkerFlavor=lld -p:ObjCopyName=llvm-objcopy' || ''),
|
||||||
''
|
''
|
||||||
)
|
)
|
||||||
}}
|
}}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
with:
|
with:
|
||||||
submodules: 'recursive'
|
submodules: 'recursive'
|
||||||
fetch-depth: '0'
|
fetch-depth: '0'
|
||||||
|
|
||||||
- name: Setup .NET
|
- name: Purge SDKs
|
||||||
uses: actions/setup-dotnet@v5.3.0
|
shell: pwsh
|
||||||
with:
|
run: |
|
||||||
dotnet-version: '10.0.1xx'
|
echo "Before:"
|
||||||
|
dotnet --list-sdks
|
||||||
|
|
||||||
|
dotnet --list-sdks | % {
|
||||||
|
$_ -match '^\S+\s+\[(.+)\]$' > $null
|
||||||
|
$d = Join-Path $Matches[1] $_.Split()[0]
|
||||||
|
Write-Host "Removing $d"
|
||||||
|
if ($IsWindows) { rm $d -r -fo } else { sudo rm -rf "$d" }
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "After:"
|
||||||
|
dotnet --list-sdks 2>$null; $LASTEXITCODE=0
|
||||||
|
|
||||||
- name: Build v2rayN
|
- name: Setup .NET
|
||||||
working-directory: ./v2rayN
|
uses: actions/setup-dotnet@v6
|
||||||
run: dotnet publish $Project -c Release -r $RID -p:SelfContained=true $ExtOpt -o $Output
|
with:
|
||||||
|
dotnet-version: 10.0.x
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
shell: bash
|
||||||
|
if: inputs.target == 'linux' && inputs.isAot
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y clang zlib1g-dev build-essential
|
||||||
|
|
||||||
|
- name: Install dependencies cross-arch
|
||||||
|
shell: bash
|
||||||
|
if: inputs.target == 'linux' && inputs.isAot && matrix.arch == 'arm64'
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y lld llvm binutils-aarch64-linux-gnu gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross
|
||||||
|
|
||||||
|
- name: Set AOT Environment Variable
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
if [ "${{ inputs.isAot }}" = "true" ]; then
|
||||||
|
echo "DOTNET_AOT_ARG=-p:IsAot=true" >> $GITHUB_ENV
|
||||||
|
else
|
||||||
|
echo "DOTNET_AOT_ARG=-p:IsAot=false" >> $GITHUB_ENV
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Set OUTPUT Environment Variable
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
RAW_PATH="${{ github.workspace }}/${{ matrix.arch }}${{ inputs.isAot && '-aot' || '' }}"
|
||||||
|
echo "OUTPUT=${RAW_PATH//\\//}" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
- name: Build AmazTool
|
- name: Build AmazTool
|
||||||
|
shell: bash
|
||||||
working-directory: ./v2rayN
|
working-directory: ./v2rayN
|
||||||
run: dotnet publish ./AmazTool/AmazTool.csproj -c Release -r $RID -p:SelfContained=true -p:PublishTrimmed=true $ExtOpt -o $Output
|
run: dotnet publish ./AmazTool/AmazTool.csproj -c Release -r $RID -p:SelfContained=true -p:PublishTrimmed=true $ExtOpt ${{ env.DOTNET_AOT_ARG }} -o ${{ env.OUTPUT }}
|
||||||
|
|
||||||
|
- name: Build v2rayN WPF
|
||||||
|
shell: bash
|
||||||
|
if: inputs.project == './v2rayN/v2rayN.csproj'
|
||||||
|
working-directory: ./v2rayN
|
||||||
|
run: dotnet publish $Project -c Release -r $RID -p:SelfContained=true $ExtOpt -o ${{ env.OUTPUT }}
|
||||||
|
|
||||||
|
- name: Build v2rayN Avalonia
|
||||||
|
shell: bash
|
||||||
|
if: inputs.project == './v2rayN.Desktop/v2rayN.Desktop.csproj'
|
||||||
|
working-directory: ./v2rayN
|
||||||
|
run: dotnet publish $Project -c Release -r $RID -p:SelfContained=true $ExtOpt ${{ env.DOTNET_AOT_ARG }} -o ${{ env.OUTPUT }}
|
||||||
|
|
||||||
|
- name: Remove Debug Symbols
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
find ${{ env.OUTPUT }} -type f -name '*.pdb' -delete
|
||||||
|
find ${{ env.OUTPUT }} -type f -name '*.debug' -delete
|
||||||
|
find ${{ env.OUTPUT }} -type f -name '*.dbg' -delete
|
||||||
|
find ${{ env.OUTPUT }} -type f -name '*.sym' -delete
|
||||||
|
find ${{ env.OUTPUT }} -name '*.dSYM' -exec rm -rf {} +
|
||||||
|
|
||||||
- name: Upload build artifacts
|
- name: Upload build artifacts
|
||||||
uses: actions/upload-artifact@v7.0.1
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with:
|
||||||
name: ${{ matrix.arch }}
|
name: ${{ matrix.arch }}${{ inputs.isAot && '-aot' || '' }}
|
||||||
path: ${{ matrix.arch }}
|
path: ${{ env.OUTPUT }}
|
||||||
|
|||||||
@@ -9,9 +9,17 @@ on:
|
|||||||
target: # windows linux macos windows-desktop
|
target: # windows linux macos windows-desktop
|
||||||
required: true
|
required: true
|
||||||
type: string
|
type: string
|
||||||
|
isAot:
|
||||||
|
required: false
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
secrets:
|
||||||
|
GPG_PRIVATE_KEY:
|
||||||
|
required: true
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
actions: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
package:
|
package:
|
||||||
@@ -37,31 +45,76 @@ jobs:
|
|||||||
}}
|
}}
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Set package variables
|
||||||
|
id: package-vars
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
INPUT_TARGET: ${{ inputs.target }}
|
||||||
|
INPUT_IS_AOT: ${{ inputs.isAot }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
package_dir="v2rayN-${Target}-${Arch}"
|
||||||
|
package_file="${package_dir}.zip"
|
||||||
|
build_artifact_name="${{ matrix.arch }}"
|
||||||
|
rename_suffix=""
|
||||||
|
if [[ "$INPUT_IS_AOT" == "true" ]]; then
|
||||||
|
build_artifact_name="${build_artifact_name}-aot"
|
||||||
|
rename_suffix="-aot"
|
||||||
|
fi
|
||||||
|
if [[ "$INPUT_TARGET" == "windows-desktop" ]]; then
|
||||||
|
rename_suffix="-desktop${rename_suffix}"
|
||||||
|
fi
|
||||||
|
final_package_file="${package_dir}${rename_suffix}.zip"
|
||||||
|
|
||||||
|
{
|
||||||
|
echo "build_artifact_name=${build_artifact_name}"
|
||||||
|
echo "package_dir=${package_dir}"
|
||||||
|
echo "package_file=${package_file}"
|
||||||
|
echo "final_package_file=${final_package_file}"
|
||||||
|
echo "rename_suffix=${rename_suffix}"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Restore build artifacts
|
- name: Restore build artifacts
|
||||||
uses: actions/download-artifact@v8
|
uses: actions/download-artifact@v8
|
||||||
with:
|
with:
|
||||||
name: ${{ matrix.arch }}
|
name: ${{ steps.package-vars.outputs.build_artifact_name }}
|
||||||
path: v2rayN-${{ env.Target }}-${{ env.Arch }}
|
path: ${{ steps.package-vars.outputs.package_dir }}
|
||||||
|
|
||||||
- name: Get v2rayN-core-bin
|
|
||||||
run: wget -nv -O v2rayN-$Target-$Arch.zip "https://github.com/2dust/v2rayN-core-bin/raw/refs/heads/master/v2rayN-$Target-$Arch.zip"
|
|
||||||
|
|
||||||
- name: Package zip archive
|
|
||||||
run: 7z a -tZip v2rayN-$Target-$Arch.zip v2rayN-$Target-$Arch -mx1
|
|
||||||
|
|
||||||
- name: Rename windows-desktop
|
- name: Get v2rayN-core-bin
|
||||||
if: inputs.target == 'windows-desktop'
|
run: |
|
||||||
run: mv "v2rayN-$Target-$Arch.zip" "v2rayN-$Target-$Arch-desktop.zip"
|
wget -nv -O "${{ steps.package-vars.outputs.package_file }}" "https://github.com/2dust/v2rayN-core-bin/raw/refs/heads/master/v2rayN-$Target-$Arch.zip"
|
||||||
|
|
||||||
- name: Sleep for race condition between matrix jobs
|
- name: Package zip archive
|
||||||
run: sleep "$(od -An -N2 -tu2 /dev/urandom | awk 'NR==1{printf "%.2f", $1/5461}')"
|
shell: bash
|
||||||
|
run: |
|
||||||
- name: Upload zip archive to release
|
7z a -tZip "${{ steps.package-vars.outputs.package_file }}" "${{ steps.package-vars.outputs.package_dir }}" -mx1
|
||||||
uses: svenstaro/upload-release-action@v2
|
|
||||||
|
- name: Rename package archive
|
||||||
|
if: steps.package-vars.outputs.rename_suffix != ''
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
mv "${{ steps.package-vars.outputs.package_file }}" \
|
||||||
|
"${{ steps.package-vars.outputs.package_dir }}${{ steps.package-vars.outputs.rename_suffix }}.zip"
|
||||||
|
|
||||||
|
- name: Upload zip artifact
|
||||||
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with:
|
||||||
file: ${{ github.workspace }}/v2rayN*.zip
|
name: release-${{ inputs.target }}-${{ matrix.arch }}${{ inputs.isAot && '-aot' || '' }}
|
||||||
tag: ${{ inputs.release_tag }}
|
path: ${{ steps.package-vars.outputs.final_package_file }}
|
||||||
file_glob: true
|
if-no-files-found: error
|
||||||
prerelease: true
|
|
||||||
|
release:
|
||||||
|
name: sign and upload zip x64 arm64
|
||||||
|
needs: package
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
arch: [ x64, arm64 ]
|
||||||
|
uses: ./.github/workflows/upload-sign.yml
|
||||||
|
with:
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
artifact_name: release-${{ inputs.target }}-${{ matrix.arch }}${{ inputs.isAot && '-aot' || '' }}
|
||||||
|
file_pattern: '*.zip'
|
||||||
|
secrets:
|
||||||
|
GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
name: publish GPG public key
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
release_tag:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
secrets:
|
||||||
|
GPG_PRIVATE_KEY:
|
||||||
|
required: true
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
release_tag:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-26.04
|
||||||
|
steps:
|
||||||
|
- name: Import GPG private key
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
install -m 700 -d ~/.gnupg
|
||||||
|
printf '%s' "$GPG_PRIVATE_KEY" | gpg --batch --import
|
||||||
|
|
||||||
|
- name: Export GPG public key
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
fingerprint="$(gpg --batch --list-secret-keys --with-colons | awk -F: '$1 == "fpr" { print $10; exit }')"
|
||||||
|
[[ -n "$fingerprint" ]] || { echo "No GPG secret key found."; exit 1; }
|
||||||
|
gpg --batch --armor --export "$fingerprint" > v2rayN-public-key.asc
|
||||||
|
|
||||||
|
- name: Upload GPG public key to release
|
||||||
|
uses: svenstaro/upload-release-action@v2
|
||||||
|
with:
|
||||||
|
file: v2rayN-public-key.asc
|
||||||
|
tag: ${{ inputs.release_tag }}
|
||||||
|
prerelease: true
|
||||||
|
overwrite: true
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
name: release v2rayN.WebAPI
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
release_tag:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
secrets:
|
||||||
|
GPG_PRIVATE_KEY:
|
||||||
|
required: false
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
release_tag:
|
||||||
|
description: 'Release tag (for example 7.x.y).'
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
actions: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
uses: ./.github/workflows/build-WebAPI.yml
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
with:
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
|
||||||
|
release-web-packages:
|
||||||
|
name: sign and upload Web API packages
|
||||||
|
# Upload through the shared signing flow, exactly like the desktop packages.
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
needs: build
|
||||||
|
uses: ./.github/workflows/upload-sign.yml
|
||||||
|
with:
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
artifact_name: WebAPI-release-packages
|
||||||
|
file_pattern: 'v2rayN-*-WebAPI*.zip'
|
||||||
|
secrets: { GPG_PRIVATE_KEY: "${{ secrets.GPG_PRIVATE_KEY }}" }
|
||||||
|
|
||||||
|
release-web-manifest:
|
||||||
|
name: sign and upload Web update manifest
|
||||||
|
if: inputs.release_tag != ''
|
||||||
|
# Advertise the update only after its packages and manifest have been uploaded.
|
||||||
|
needs: [build, release-web-packages]
|
||||||
|
uses: ./.github/workflows/upload-sign.yml
|
||||||
|
with:
|
||||||
|
release_tag: ${{ inputs.release_tag }}
|
||||||
|
artifact_name: WebAPI-release-manifest
|
||||||
|
file_pattern: 'WebAPI-update.json'
|
||||||
|
secrets: { GPG_PRIVATE_KEY: "${{ secrets.GPG_PRIVATE_KEY }}" }
|
||||||
+33
-10
@@ -1,29 +1,52 @@
|
|||||||
name: Code Test
|
name: Code Test
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- master
|
||||||
|
paths:
|
||||||
|
- 'v2rayN/ServiceLib/**'
|
||||||
|
- 'v2rayN/ServiceLib.UdpTest/**'
|
||||||
|
- 'v2rayN/ServiceLib.Tests/**'
|
||||||
|
- 'v2rayN/Directory.Build.*'
|
||||||
|
- 'v2rayN/Directory.Packages.props'
|
||||||
|
- 'global.json'
|
||||||
|
- '.github/workflows/test.yml'
|
||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
paths:
|
paths:
|
||||||
- 'v2rayN/ServiceLib/Services/CoreConfig/**'
|
- 'v2rayN/ServiceLib/**'
|
||||||
- 'v2rayN/ServiceLib/Handler/Fmt/**'
|
- 'v2rayN/ServiceLib.UdpTest/**'
|
||||||
|
- 'v2rayN/ServiceLib.Tests/**'
|
||||||
|
- 'v2rayN/Directory.Build.*'
|
||||||
|
- 'v2rayN/Directory.Packages.props'
|
||||||
|
- 'global.json'
|
||||||
- '.github/workflows/test.yml'
|
- '.github/workflows/test.yml'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
checks: write
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v6
|
uses: actions/checkout@v7
|
||||||
with:
|
|
||||||
submodules: 'recursive'
|
|
||||||
fetch-depth: '0'
|
|
||||||
|
|
||||||
- name: Setup .NET
|
- name: Setup .NET
|
||||||
uses: actions/setup-dotnet@v5.3.0
|
uses: actions/setup-dotnet@v6
|
||||||
with:
|
with:
|
||||||
dotnet-version: '8.0.x'
|
dotnet-version: '10.x'
|
||||||
|
dotnet-quality: 'ga'
|
||||||
|
|
||||||
- name: Test Code
|
- name: Test Code
|
||||||
working-directory: ./v2rayN
|
run: dotnet test --project ./v2rayN/ServiceLib.Tests -c Release --results-directory ./TestResults -- --report-trx
|
||||||
run: dotnet test ./ServiceLib.Tests
|
|
||||||
|
- name: Comment PR with results
|
||||||
|
if: always()
|
||||||
|
uses: EnricoMi/publish-unit-test-result-action@v2
|
||||||
|
with:
|
||||||
|
files: ./TestResults/*.trx
|
||||||
|
comment_mode: failures
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
name: Update Certificate
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 0 * * *'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
update-cert:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Setup .NET
|
||||||
|
uses: actions/setup-dotnet@v6
|
||||||
|
with:
|
||||||
|
dotnet-version: 10.0.x
|
||||||
|
|
||||||
|
- name: Update Certificate
|
||||||
|
run: |
|
||||||
|
dotnet run .github/scripts/UpdateCert.cs
|
||||||
|
|
||||||
|
- name: Create Pull Request
|
||||||
|
uses: peter-evans/create-pull-request@v8
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
commit-message: "Update certificate"
|
||||||
|
title: "Update certificate"
|
||||||
|
body: "This pull request updates the certificate."
|
||||||
|
branch: github-actions/update-certificate
|
||||||
|
delete-branch: true
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
name: sign and upload release files
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
release_tag:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
artifact_name:
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
file_pattern:
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
default: '**/*'
|
||||||
|
content_type:
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
default: application/octet-stream
|
||||||
|
secrets:
|
||||||
|
GPG_PRIVATE_KEY:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
actions: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
upload:
|
||||||
|
runs-on: ubuntu-26.04
|
||||||
|
steps:
|
||||||
|
- name: Download release artifact
|
||||||
|
uses: actions/download-artifact@v8
|
||||||
|
with:
|
||||||
|
name: ${{ inputs.artifact_name }}
|
||||||
|
path: dist
|
||||||
|
|
||||||
|
- name: Import GPG private key
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
install -m 700 -d ~/.gnupg
|
||||||
|
printf '%s' "$GPG_PRIVATE_KEY" | gpg --batch --import
|
||||||
|
|
||||||
|
- name: Sign release files
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
cd dist
|
||||||
|
shopt -s globstar nullglob
|
||||||
|
files=( ${{ inputs.file_pattern }} )
|
||||||
|
(( ${#files[@]} )) || { echo "No files matched: ${{ inputs.file_pattern }}"; exit 1; }
|
||||||
|
for f in "${files[@]}"; do
|
||||||
|
[[ -f "$f" ]] || continue
|
||||||
|
gpg --batch --yes --armor --detach-sign --output "$f.sig" "$f"
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Upload release files
|
||||||
|
uses: svenstaro/upload-release-action@v2
|
||||||
|
with:
|
||||||
|
file: dist/${{ inputs.file_pattern }}
|
||||||
|
tag: ${{ inputs.release_tag }}
|
||||||
|
file_glob: true
|
||||||
|
prerelease: true
|
||||||
|
overwrite: true
|
||||||
|
|
||||||
|
- name: Upload release signatures
|
||||||
|
uses: svenstaro/upload-release-action@v2
|
||||||
|
with:
|
||||||
|
file: dist/${{ inputs.file_pattern }}.sig
|
||||||
|
tag: ${{ inputs.release_tag }}
|
||||||
|
file_glob: true
|
||||||
|
prerelease: true
|
||||||
|
overwrite: true
|
||||||
@@ -19,12 +19,19 @@ jobs:
|
|||||||
$wingetPackage = "2dust.v2rayN"
|
$wingetPackage = "2dust.v2rayN"
|
||||||
$gitToken = "${{ secrets.PT_WINGET }}"
|
$gitToken = "${{ secrets.PT_WINGET }}"
|
||||||
|
|
||||||
$github = Invoke-RestMethod -uri "https://api.github.com/repos/2dust/v2rayN/releases"
|
$headers = @{ Authorization = "Bearer $gitToken"; Accept = "application/vnd.github+json" }
|
||||||
|
|
||||||
|
$github = Invoke-RestMethod -Uri "https://api.github.com/repos/2dust/v2rayN/releases" -Headers $headers
|
||||||
|
|
||||||
$targetRelease = $github | Where-Object -Property prerelease -match 'False' | Select -First 1
|
$targetRelease = $github | Where-Object -Property prerelease -match 'False' | Select -First 1
|
||||||
|
|
||||||
$x64InstallerUrl = $targetRelease | Select -ExpandProperty assets -First 1 | Where-Object -Property name -match 'v2rayN-windows-64\.zip' | Select -ExpandProperty browser_download_url
|
$assets = $targetRelease | Select -ExpandProperty assets -First 1
|
||||||
$arm64InstallerUrl = $targetRelease | Select -ExpandProperty assets -First 1 | Where-Object -Property name -match 'v2rayN-windows-arm64\.zip' | Select -ExpandProperty browser_download_url
|
$x64InstallerUrl = $assets | Where-Object { $_.name -eq 'v2rayN-windows-64.zip' } | Select -ExpandProperty browser_download_url
|
||||||
|
$arm64InstallerUrl = $assets | Where-Object { $_.name -eq 'v2rayN-windows-arm64.zip' } | Select -ExpandProperty browser_download_url
|
||||||
|
|
||||||
|
if (-not $x64InstallerUrl -or -not $arm64InstallerUrl) {
|
||||||
|
throw "Could not find required installers in release assets."
|
||||||
|
}
|
||||||
|
|
||||||
$ver = $targetRelease.tag_name
|
$ver = $targetRelease.tag_name
|
||||||
|
|
||||||
|
|||||||
@@ -84,6 +84,9 @@ StyleCopReport.xml
|
|||||||
*.rsp
|
*.rsp
|
||||||
# but not Directory.Build.rsp, as it configures directory-level build defaults
|
# but not Directory.Build.rsp, as it configures directory-level build defaults
|
||||||
!Directory.Build.rsp
|
!Directory.Build.rsp
|
||||||
|
bin/
|
||||||
|
obj/
|
||||||
|
build/
|
||||||
*.sbr
|
*.sbr
|
||||||
*.tlb
|
*.tlb
|
||||||
*.tli
|
*.tli
|
||||||
|
|||||||
@@ -1,18 +1,80 @@
|
|||||||
# v2rayN
|
# v2rayN
|
||||||
|
|
||||||
A GUI client for Windows, Linux and macOS, support [Xray](https://github.com/XTLS/Xray-core)
|
### A GUI client for Windows, Linux and macOS. Support [Xray](https://github.com/XTLS/Xray-core) and [sing-box](https://github.com/SagerNet/sing-box) and [others](https://github.com/2dust/v2rayN/wiki/List-of-supported-cores)
|
||||||
and [sing-box](https://github.com/SagerNet/sing-box)
|
|
||||||
and [others](https://github.com/2dust/v2rayN/wiki/List-of-supported-cores)
|
|
||||||
|
|
||||||
[](https://github.com/2dust/v2rayN/commits/master)
|
|
||||||
[](https://www.codefactor.io/repository/github/2dust/v2rayn)
|
[](https://www.codefactor.io/repository/github/2dust/v2rayn)
|
||||||
[](https://github.com/2dust/v2rayN/releases)
|
[](https://github.com/2dust/v2rayN/releases)
|
||||||
[](https://t.me/v2rayn)
|
[](https://github.com/2dust/v2rayN/releases)
|
||||||
|
[](https://t.me/v2rayn)
|
||||||
|
|
||||||
|
[](https://github.com/2dust/v2rayN)
|
||||||
|
[](https://github.com/2dust/v2rayN)
|
||||||
|
[](https://github.com/2dust/v2rayN)
|
||||||
|
[](https://github.com/2dust/v2rayN)
|
||||||
|
|
||||||
## How to use
|
|
||||||
|
|
||||||
Read the [Wiki](https://github.com/2dust/v2rayN/wiki) for details.
|
---
|
||||||
|
|
||||||
## Telegram Channel
|
## Download / 下载
|
||||||
|
|
||||||
[github_2dust](https://t.me/github_2dust)
|
Download the latest release here:
|
||||||
|
|
||||||
|
在这里下载最新版本:
|
||||||
|
|
||||||
|
[https://github.com/2dust/v2rayN/releases](https://github.com/2dust/v2rayN/releases)
|
||||||
|
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> v2rayN is the desktop version. For the mobile version, please visit the v2rayNG \
|
||||||
|
> v2rayN 是电脑版,手机版请访问 v2rayNG
|
||||||
|
>
|
||||||
|
> https://github.com/2dust/v2rayNG
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Documentation / 使用文档
|
||||||
|
|
||||||
|
Read the Wiki for usage guides and configuration details.
|
||||||
|
|
||||||
|
请阅读 Wiki 获取使用说明和配置教程。
|
||||||
|
|
||||||
|
[https://github.com/2dust/v2rayN/wiki](https://github.com/2dust/v2rayN/wiki)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Supported Platforms / 支持平台
|
||||||
|
|
||||||
|
| Platform / 平台 | x64 | x86 | arm64 | riscv64 | loong64 | ppc64le |
|
||||||
|
| --- | --- | --- | --- | --- | --- | --- |
|
||||||
|
| Windows | ✅ | ✅ | ✅ | - | - | - |
|
||||||
|
| Linux | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||||
|
| macOS | ✅ | - | ✅ | - | - | - |
|
||||||
|
|
||||||
|
Minimum OS requirements: [Release files introduction](https://github.com/2dust/v2rayN/wiki/Release-files-introduction) / 最低系统要求:[发布文件介绍](https://github.com/2dust/v2rayN/wiki/Release-files-introduction)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## GPG Verification / GPG 签名校验
|
||||||
|
|
||||||
|
Release files are signed with GPG to verify authenticity and integrity, helping prevent mirror, ISP, or CDN hijacking.
|
||||||
|
|
||||||
|
发布文件已使用 GPG 签名,可用于校验文件真实性与完整性,预防镜像站、运营商或 CDN 劫持。
|
||||||
|
|
||||||
|
### Fingerprint / 公钥指纹
|
||||||
|
|
||||||
|
```text
|
||||||
|
7694 5E9F 3E9A 168F 8070 F195 805D 661C
|
||||||
|
134D FAF6 8903 C199 463C 31E5 AE90 3AE0
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Community / 社区
|
||||||
|
|
||||||
|
Telegram Group / Telegram 群组:
|
||||||
|
|
||||||
|
[https://t.me/v2rayN](https://t.me/v2rayN)
|
||||||
|
|
||||||
|
Telegram Channel / Telegram 频道:
|
||||||
|
|
||||||
|
[https://t.me/github_2dust](https://t.me/github_2dust)
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"test": {
|
||||||
|
"runner": "Microsoft.Testing.Platform"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,742 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
VERSION_ARG=""
|
|
||||||
WITH_CORE="both"
|
|
||||||
FORCE_NETCORE=0
|
|
||||||
BUILD_FROM=""
|
|
||||||
XRAY_VER="${XRAY_VER:-}"
|
|
||||||
SING_VER="${SING_VER:-}"
|
|
||||||
|
|
||||||
MIN_KERNEL="5.10"
|
|
||||||
PKGROOT="v2rayN-publish"
|
|
||||||
PROJECT_HINT="v2rayN.Desktop/v2rayN.Desktop.csproj"
|
|
||||||
OUTPUT_DIR="${HOME}/debbuild"
|
|
||||||
DOTNET_TFM="net10.0"
|
|
||||||
DOTNET_LOONGARCH_VERSION="10.0.108"
|
|
||||||
DOTNET_LOONGARCH_TAG="v10.0.108-loongarch64"
|
|
||||||
DOTNET_LOONGARCH_BASE="https://github.com/loongson/dotnet/releases/download"
|
|
||||||
DOTNET_LOONGARCH_FILE="dotnet-sdk-${DOTNET_LOONGARCH_VERSION}-linux-loongarch64.tar.gz"
|
|
||||||
DOTNET_SDK_URL="${DOTNET_LOONGARCH_BASE}/${DOTNET_LOONGARCH_TAG}/${DOTNET_LOONGARCH_FILE}"
|
|
||||||
|
|
||||||
OS_ID=""
|
|
||||||
OS_NAME=""
|
|
||||||
OS_VERSION_ID=""
|
|
||||||
HOST_ARCH=""
|
|
||||||
SCRIPT_DIR=""
|
|
||||||
PROJECT=""
|
|
||||||
VERSION=""
|
|
||||||
|
|
||||||
declare -a BUILT_DEBS=()
|
|
||||||
|
|
||||||
die() {
|
|
||||||
echo "$*" >&2
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
parse_args() {
|
|
||||||
local first_arg="${1:-}"
|
|
||||||
|
|
||||||
if [[ -n "$first_arg" && "$first_arg" != --* ]]; then
|
|
||||||
VERSION_ARG="$first_arg"
|
|
||||||
shift || true
|
|
||||||
fi
|
|
||||||
|
|
||||||
while [[ $# -gt 0 ]]; do
|
|
||||||
case "$1" in
|
|
||||||
--with-core) WITH_CORE="${2:-both}"; shift 2 ;;
|
|
||||||
--xray-ver) XRAY_VER="${2:-}"; shift 2 ;;
|
|
||||||
--singbox-ver) SING_VER="${2:-}"; shift 2 ;;
|
|
||||||
--netcore) FORCE_NETCORE=1; shift ;;
|
|
||||||
--buildfrom) BUILD_FROM="${2:-}"; shift 2 ;;
|
|
||||||
*)
|
|
||||||
[[ -n "${VERSION_ARG:-}" ]] || VERSION_ARG="$1"
|
|
||||||
shift
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
|
|
||||||
if [[ -n "${VERSION_ARG:-}" && -n "${BUILD_FROM:-}" ]]; then
|
|
||||||
die "You cannot specify both an explicit version and --buildfrom at the same time.
|
|
||||||
Provide either a version (e.g. 7.14.0) OR --buildfrom 1|2|3."
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
detect_environment() {
|
|
||||||
local current_kernel=""
|
|
||||||
local lowest=""
|
|
||||||
|
|
||||||
. /etc/os-release
|
|
||||||
|
|
||||||
OS_ID="${ID:-}"
|
|
||||||
OS_NAME="${NAME:-$OS_ID}"
|
|
||||||
OS_VERSION_ID="${VERSION_ID:-}"
|
|
||||||
HOST_ARCH="$(uname -m)"
|
|
||||||
|
|
||||||
case "$OS_ID" in
|
|
||||||
debian)
|
|
||||||
echo "Detected supported system: ${OS_NAME:-$OS_ID} ${OS_VERSION_ID:-}"
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
die "Unsupported system: ${OS_NAME:-unknown} (${OS_ID:-unknown}).
|
|
||||||
This script only supports: Debian."
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
case "$HOST_ARCH" in
|
|
||||||
loongarch64) ;;
|
|
||||||
*) die "Only supports loongarch64" ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
current_kernel="$(uname -r)"
|
|
||||||
lowest="$(printf '%s\n%s\n' "$MIN_KERNEL" "$current_kernel" | sort -V | head -n1)"
|
|
||||||
|
|
||||||
[[ "$lowest" == "$MIN_KERNEL" ]] || die "Kernel $current_kernel is below $MIN_KERNEL"
|
|
||||||
echo "[OK] Kernel $current_kernel verified."
|
|
||||||
}
|
|
||||||
|
|
||||||
install_dependencies() {
|
|
||||||
local install_ok=0
|
|
||||||
local tmp_dotnet=""
|
|
||||||
|
|
||||||
mkdir -p "$OUTPUT_DIR"
|
|
||||||
|
|
||||||
if command -v apt-get >/dev/null 2>&1; then
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get -y install \
|
|
||||||
curl unzip tar jq rsync ca-certificates git dpkg-dev fakeroot file \
|
|
||||||
desktop-file-utils xdg-utils wget gcc make pkg-config \
|
|
||||||
libicu-dev libssl-dev libfontconfig1 libfreetype6 zlib1g
|
|
||||||
|
|
||||||
mkdir -p "$HOME/.dotnet"
|
|
||||||
tmp_dotnet="$(mktemp -d)"
|
|
||||||
curl -fL "$DOTNET_SDK_URL" -o "$tmp_dotnet/$DOTNET_LOONGARCH_FILE"
|
|
||||||
tar -C "$HOME/.dotnet" -xzf "$tmp_dotnet/$DOTNET_LOONGARCH_FILE"
|
|
||||||
rm -rf "$tmp_dotnet"
|
|
||||||
|
|
||||||
export PATH="$HOME/.dotnet:$PATH"
|
|
||||||
export DOTNET_ROOT="$HOME/.dotnet"
|
|
||||||
|
|
||||||
mkdir -p "$HOME/.nuget/NuGet"
|
|
||||||
|
|
||||||
cat > "$HOME/.nuget/NuGet/NuGet.Config" <<EOF
|
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<configuration>
|
|
||||||
<packageSources>
|
|
||||||
<clear />
|
|
||||||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
|
|
||||||
<add key="loongnix" value="https://lnuget.loongnix.cn/v3/index.json" allowInsecureConnections="true" />
|
|
||||||
</packageSources>
|
|
||||||
</configuration>
|
|
||||||
EOF
|
|
||||||
|
|
||||||
dotnet --info >/dev/null 2>&1 && install_ok=1
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$install_ok" -ne 1 ]]; then
|
|
||||||
echo "Could not auto-install dependencies for '$OS_ID'. Make sure these are available:"
|
|
||||||
echo "dotnet-loongarch SDK, curl, unzip, tar, rsync, git, gcc, make, dpkg-deb, fakeroot, libicu-dev, libssl-dev"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
prepare_workspace() {
|
|
||||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
|
||||||
cd "$SCRIPT_DIR"
|
|
||||||
|
|
||||||
if [[ -f .gitmodules ]]; then
|
|
||||||
git submodule sync --recursive || true
|
|
||||||
git submodule update --init --recursive || true
|
|
||||||
fi
|
|
||||||
|
|
||||||
PROJECT="$PROJECT_HINT"
|
|
||||||
[[ -f "$PROJECT" ]] || PROJECT="$(find . -maxdepth 3 -name 'v2rayN.Desktop.csproj' | head -n1 || true)"
|
|
||||||
[[ -f "$PROJECT" ]] || die "v2rayN.Desktop.csproj not found"
|
|
||||||
}
|
|
||||||
|
|
||||||
choose_channel() {
|
|
||||||
local ch="latest"
|
|
||||||
local sel=""
|
|
||||||
|
|
||||||
if [[ -n "${BUILD_FROM:-}" ]]; then
|
|
||||||
case "$BUILD_FROM" in
|
|
||||||
1) echo "latest"; return 0 ;;
|
|
||||||
2) echo "prerelease"; return 0 ;;
|
|
||||||
3) echo "keep"; return 0 ;;
|
|
||||||
*) die "[ERROR] Invalid --buildfrom value: ${BUILD_FROM}. Use 1|2|3." ;;
|
|
||||||
esac
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ -t 0 ]]; then
|
|
||||||
echo "[?] Choose v2rayN release channel:" >&2
|
|
||||||
echo " 1) Latest (stable) [default]" >&2
|
|
||||||
echo " 2) Pre-release (preview)" >&2
|
|
||||||
echo " 3) Keep current (do nothing)" >&2
|
|
||||||
printf "Enter 1, 2 or 3 [default 1]: " >&2
|
|
||||||
|
|
||||||
if read -r sel </dev/tty; then
|
|
||||||
case "${sel:-}" in
|
|
||||||
2) ch="prerelease" ;;
|
|
||||||
3) ch="keep" ;;
|
|
||||||
esac
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "$ch"
|
|
||||||
}
|
|
||||||
|
|
||||||
get_latest_tag_latest() {
|
|
||||||
curl -fsSL "https://api.github.com/repos/2dust/v2rayN/releases/latest" \
|
|
||||||
| jq -re '.tag_name' \
|
|
||||||
| sed 's/^v//'
|
|
||||||
}
|
|
||||||
|
|
||||||
get_latest_tag_prerelease() {
|
|
||||||
curl -fsSL "https://api.github.com/repos/2dust/v2rayN/releases?per_page=20" \
|
|
||||||
| jq -re 'first(.[] | select(.prerelease == true) | .tag_name)' \
|
|
||||||
| sed 's/^v//'
|
|
||||||
}
|
|
||||||
|
|
||||||
sync_submodules() {
|
|
||||||
if [[ -f .gitmodules ]]; then
|
|
||||||
git submodule sync --recursive || true
|
|
||||||
git submodule update --init --recursive || true
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
git_try_checkout() {
|
|
||||||
local want="$1"
|
|
||||||
local ref=""
|
|
||||||
|
|
||||||
if git rev-parse --git-dir >/dev/null 2>&1; then
|
|
||||||
git fetch --tags --force --prune --depth=1 || true
|
|
||||||
git rev-parse "refs/tags/${want}" >/dev/null 2>&1 && ref="$want"
|
|
||||||
|
|
||||||
if [[ -n "$ref" ]]; then
|
|
||||||
echo "[OK] Found ref '${ref}', checking out..."
|
|
||||||
git checkout -f "$ref"
|
|
||||||
sync_submodules
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
apply_channel_or_keep() {
|
|
||||||
local ch="$1"
|
|
||||||
local tag=""
|
|
||||||
|
|
||||||
if [[ "$ch" == "keep" ]]; then
|
|
||||||
echo "[*] Keep current repository state (no checkout)."
|
|
||||||
VERSION="$(git describe --tags --abbrev=0 2>/dev/null || echo '0.0.0+git')"
|
|
||||||
VERSION="${VERSION#v}"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "[*] Resolving ${ch} tag from GitHub releases..."
|
|
||||||
|
|
||||||
case "$ch" in
|
|
||||||
latest) tag="$(get_latest_tag_latest || true)" ;;
|
|
||||||
prerelease) tag="$(get_latest_tag_prerelease || true)" ;;
|
|
||||||
*) die "Failed to resolve latest tag for channel '${ch}'." ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
[[ -n "$tag" ]] || die "Failed to resolve latest tag for channel '${ch}'."
|
|
||||||
|
|
||||||
echo "[*] Latest tag for '${ch}': ${tag}"
|
|
||||||
git_try_checkout "$tag" || die "Failed to checkout '${tag}'."
|
|
||||||
VERSION="${tag#v}"
|
|
||||||
}
|
|
||||||
|
|
||||||
resolve_version() {
|
|
||||||
if git rev-parse --git-dir >/dev/null 2>&1; then
|
|
||||||
if [[ -n "${VERSION_ARG:-}" ]]; then
|
|
||||||
local clean_ver="${VERSION_ARG#v}"
|
|
||||||
|
|
||||||
if git_try_checkout "$clean_ver"; then
|
|
||||||
VERSION="$clean_ver"
|
|
||||||
else
|
|
||||||
echo "[WARN] Tag '${VERSION_ARG}' not found."
|
|
||||||
apply_channel_or_keep "$(choose_channel)"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
apply_channel_or_keep "$(choose_channel)"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
echo "Current directory is not a git repo; proceeding on current tree."
|
|
||||||
VERSION="${VERSION_ARG:-0.0.0}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
VERSION="${VERSION#v}"
|
|
||||||
echo "[*] GUI version resolved as: ${VERSION}"
|
|
||||||
}
|
|
||||||
|
|
||||||
xray_url_for_rid() {
|
|
||||||
local rid="$1"
|
|
||||||
local ver="$2"
|
|
||||||
|
|
||||||
case "$rid" in
|
|
||||||
linux-loongarch64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-loong64.zip" ;;
|
|
||||||
*) return 1 ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
singbox_url_for_rid() {
|
|
||||||
local rid="$1"
|
|
||||||
local ver="$2"
|
|
||||||
|
|
||||||
case "$rid" in
|
|
||||||
linux-loongarch64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-loong64.tar.gz" ;;
|
|
||||||
*) return 1 ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
bundle_url_for_rid() {
|
|
||||||
local rid="$1"
|
|
||||||
|
|
||||||
case "$rid" in
|
|
||||||
linux-loongarch64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-loong64.zip" ;;
|
|
||||||
*) return 1 ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
download_xray() {
|
|
||||||
local outdir="$1"
|
|
||||||
local rid="$2"
|
|
||||||
local ver="${XRAY_VER:-}"
|
|
||||||
local url=""
|
|
||||||
local tmp=""
|
|
||||||
|
|
||||||
mkdir -p "$outdir"
|
|
||||||
|
|
||||||
if [[ -z "$ver" ]]; then
|
|
||||||
ver="$(curl -fsSL https://api.github.com/repos/XTLS/Xray-core/releases/latest \
|
|
||||||
| grep -Eo '"tag_name":\s*"v[^"]+"' \
|
|
||||||
| sed -E 's/.*"v([^"]+)".*/\1/' \
|
|
||||||
| head -n1)" || true
|
|
||||||
fi
|
|
||||||
|
|
||||||
[[ -n "$ver" ]] || { echo "[xray] Failed to get version"; return 1; }
|
|
||||||
url="$(xray_url_for_rid "$rid" "$ver")" || { echo "[xray] Unsupported RID: $rid"; return 1; }
|
|
||||||
|
|
||||||
echo "[+] Download xray: $url"
|
|
||||||
|
|
||||||
tmp="$(mktemp -d)"
|
|
||||||
curl -fL "$url" -o "$tmp/xray.zip" || { rm -rf "$tmp"; return 1; }
|
|
||||||
unzip -q "$tmp/xray.zip" -d "$tmp" || { rm -rf "$tmp"; return 1; }
|
|
||||||
install -m 755 "$tmp/xray" "$outdir/xray" || { rm -rf "$tmp"; return 1; }
|
|
||||||
rm -rf "$tmp"
|
|
||||||
}
|
|
||||||
|
|
||||||
download_singbox() {
|
|
||||||
local outdir="$1"
|
|
||||||
local rid="$2"
|
|
||||||
local ver="${SING_VER:-}"
|
|
||||||
local url=""
|
|
||||||
local tmp=""
|
|
||||||
local bin=""
|
|
||||||
local cronet=""
|
|
||||||
|
|
||||||
mkdir -p "$outdir"
|
|
||||||
|
|
||||||
if [[ -z "$ver" ]]; then
|
|
||||||
ver="$(curl -fsSL https://api.github.com/repos/SagerNet/sing-box/releases/latest \
|
|
||||||
| grep -Eo '"tag_name":\s*"v[^"]+"' \
|
|
||||||
| sed -E 's/.*"v([^"]+)".*/\1/' \
|
|
||||||
| head -n1)" || true
|
|
||||||
fi
|
|
||||||
|
|
||||||
[[ -n "$ver" ]] || { echo "[sing-box] Failed to get version"; return 1; }
|
|
||||||
url="$(singbox_url_for_rid "$rid" "$ver")" || { echo "[sing-box] Unsupported RID: $rid"; return 1; }
|
|
||||||
|
|
||||||
echo "[+] Download sing-box: $url"
|
|
||||||
|
|
||||||
tmp="$(mktemp -d)"
|
|
||||||
curl -fL "$url" -o "$tmp/singbox.tar.gz" || { rm -rf "$tmp"; return 1; }
|
|
||||||
tar -C "$tmp" -xzf "$tmp/singbox.tar.gz" || { rm -rf "$tmp"; return 1; }
|
|
||||||
|
|
||||||
bin="$(find "$tmp" -type f -name 'sing-box' | head -n1 || true)"
|
|
||||||
[[ -n "$bin" ]] || { echo "[!] sing-box unpack failed"; rm -rf "$tmp"; return 1; }
|
|
||||||
|
|
||||||
install -m 755 "$bin" "$outdir/sing-box" || { rm -rf "$tmp"; return 1; }
|
|
||||||
|
|
||||||
cronet="$(find "$tmp" -type f -name 'libcronet*.so*' | head -n1 || true)"
|
|
||||||
[[ -n "$cronet" ]] && install -m 644 "$cronet" "$outdir/libcronet.so" || true
|
|
||||||
|
|
||||||
rm -rf "$tmp"
|
|
||||||
}
|
|
||||||
|
|
||||||
unify_geo_layout() {
|
|
||||||
local outroot="$1"
|
|
||||||
local n
|
|
||||||
local names=(
|
|
||||||
geosite.dat
|
|
||||||
geoip.dat
|
|
||||||
geoip-only-cn-private.dat
|
|
||||||
Country.mmdb
|
|
||||||
geoip.metadb
|
|
||||||
)
|
|
||||||
|
|
||||||
mkdir -p "$outroot/bin"
|
|
||||||
|
|
||||||
for n in "${names[@]}"; do
|
|
||||||
if [[ -f "$outroot/bin/xray/$n" ]]; then
|
|
||||||
mv -f "$outroot/bin/xray/$n" "$outroot/bin/$n"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
download_geo_assets() {
|
|
||||||
local outroot="$1"
|
|
||||||
local bin_dir="$outroot/bin"
|
|
||||||
local srss_dir="$bin_dir/srss"
|
|
||||||
local f=""
|
|
||||||
|
|
||||||
mkdir -p "$bin_dir" "$srss_dir"
|
|
||||||
|
|
||||||
echo "[+] Download Xray Geo to ${bin_dir}"
|
|
||||||
curl -fsSL -o "$bin_dir/geosite.dat" "https://github.com/Loyalsoldier/V2ray-rules-dat/releases/latest/download/geosite.dat"
|
|
||||||
curl -fsSL -o "$bin_dir/geoip.dat" "https://github.com/Loyalsoldier/V2ray-rules-dat/releases/latest/download/geoip.dat"
|
|
||||||
curl -fsSL -o "$bin_dir/geoip-only-cn-private.dat" "https://raw.githubusercontent.com/Loyalsoldier/geoip/release/geoip-only-cn-private.dat"
|
|
||||||
curl -fsSL -o "$bin_dir/Country.mmdb" "https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb"
|
|
||||||
|
|
||||||
echo "[+] Download sing-box rule DB & rule-sets"
|
|
||||||
curl -fsSL -o "$bin_dir/geoip.metadb" "https://github.com/MetaCubeX/meta-rules-dat/releases/latest/download/geoip.metadb"
|
|
||||||
|
|
||||||
for f in geoip-private.srs geoip-cn.srs geoip-facebook.srs geoip-fastly.srs geoip-google.srs geoip-netflix.srs geoip-telegram.srs geoip-twitter.srs; do
|
|
||||||
curl -fsSL -o "$srss_dir/$f" "https://raw.githubusercontent.com/2dust/sing-box-rules/refs/heads/rule-set-geoip/$f"
|
|
||||||
done
|
|
||||||
|
|
||||||
for f in geosite-cn.srs geosite-gfw.srs geosite-google.srs geosite-greatfire.srs geosite-geolocation-cn.srs geosite-category-ads-all.srs geosite-private.srs; do
|
|
||||||
curl -fsSL -o "$srss_dir/$f" "https://raw.githubusercontent.com/2dust/sing-box-rules/refs/heads/rule-set-geosite/$f"
|
|
||||||
done
|
|
||||||
|
|
||||||
unify_geo_layout "$outroot"
|
|
||||||
}
|
|
||||||
|
|
||||||
populate_assets_zip_mode() {
|
|
||||||
local outroot="$1"
|
|
||||||
local rid="$2"
|
|
||||||
local url=""
|
|
||||||
local tmp=""
|
|
||||||
local nested_dir=""
|
|
||||||
|
|
||||||
url="$(bundle_url_for_rid "$rid")" || { echo "[!] Bundle unsupported RID: $rid"; return 1; }
|
|
||||||
|
|
||||||
echo "[+] Try v2rayN bundle archive: $url"
|
|
||||||
|
|
||||||
tmp="$(mktemp -d)"
|
|
||||||
curl -fL "$url" -o "$tmp/v2rayn.zip" || { echo "[!] Bundle download failed"; rm -rf "$tmp"; return 1; }
|
|
||||||
unzip -q "$tmp/v2rayn.zip" -d "$tmp" || { echo "[!] Bundle unzip failed"; rm -rf "$tmp"; return 1; }
|
|
||||||
|
|
||||||
if [[ -d "$tmp/bin" ]]; then
|
|
||||||
mkdir -p "$outroot/bin"
|
|
||||||
rsync -a "$tmp/bin/" "$outroot/bin/"
|
|
||||||
else
|
|
||||||
rsync -a "$tmp/" "$outroot/"
|
|
||||||
fi
|
|
||||||
|
|
||||||
rm -f "$outroot/v2rayn.zip" 2>/dev/null || true
|
|
||||||
find "$outroot" -type d -name "mihomo" -prune -exec rm -rf {} + 2>/dev/null || true
|
|
||||||
|
|
||||||
nested_dir="$(find "$outroot" -maxdepth 1 -type d -name 'v2rayN-linux-*' | head -n1 || true)"
|
|
||||||
if [[ -n "$nested_dir" && -d "$nested_dir/bin" ]]; then
|
|
||||||
mkdir -p "$outroot/bin"
|
|
||||||
rsync -a "$nested_dir/bin/" "$outroot/bin/"
|
|
||||||
rm -rf "$nested_dir"
|
|
||||||
fi
|
|
||||||
|
|
||||||
unify_geo_layout "$outroot"
|
|
||||||
rm -rf "$tmp"
|
|
||||||
|
|
||||||
echo "[+] Bundle extracted to $outroot"
|
|
||||||
}
|
|
||||||
|
|
||||||
populate_assets_netcore_mode() {
|
|
||||||
local outroot="$1"
|
|
||||||
local rid="$2"
|
|
||||||
|
|
||||||
mkdir -p "$outroot/bin/xray" "$outroot/bin/sing_box"
|
|
||||||
|
|
||||||
if [[ "$WITH_CORE" == "xray" || "$WITH_CORE" == "both" ]]; then
|
|
||||||
download_xray "$outroot/bin/xray" "$rid" || echo "[!] xray download failed (skipped)"
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ "$WITH_CORE" == "sing-box" || "$WITH_CORE" == "both" ]]; then
|
|
||||||
download_singbox "$outroot/bin/sing_box" "$rid" || echo "[!] sing-box download failed (skipped)"
|
|
||||||
fi
|
|
||||||
|
|
||||||
download_geo_assets "$outroot" || echo "[!] Geo rules download failed (skipped)"
|
|
||||||
}
|
|
||||||
|
|
||||||
stage_runtime_assets() {
|
|
||||||
local outroot="$1"
|
|
||||||
local rid="$2"
|
|
||||||
|
|
||||||
mkdir -p "$outroot/bin/xray" "$outroot/bin/sing_box"
|
|
||||||
|
|
||||||
if [[ "$FORCE_NETCORE" -eq 0 ]]; then
|
|
||||||
if populate_assets_zip_mode "$outroot" "$rid"; then
|
|
||||||
echo "[*] Using v2rayN bundle archive."
|
|
||||||
else
|
|
||||||
echo "[*] Bundle failed, fallback to separate core + rules."
|
|
||||||
populate_assets_netcore_mode "$outroot" "$rid"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
echo "[*] --netcore specified: use separate core + rules."
|
|
||||||
populate_assets_netcore_mode "$outroot" "$rid"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
describe_target() {
|
|
||||||
local short="$1"
|
|
||||||
|
|
||||||
case "$short" in
|
|
||||||
loongarch64) printf '%s\n%s\n' "linux-loongarch64" "loong64" ;;
|
|
||||||
*) echo "Unknown arch '$short' (use loongarch64)" >&2; return 1 ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
publish_binary() {
|
|
||||||
local rid="$1"
|
|
||||||
|
|
||||||
dotnet clean "$PROJECT" -c Release
|
|
||||||
rm -rf "$(dirname "$PROJECT")/bin/Release/net10.0" || true
|
|
||||||
dotnet restore "$PROJECT"
|
|
||||||
dotnet publish "$PROJECT" -c Release -r "$rid" -p:PublishSingleFile=false -p:SelfContained=true
|
|
||||||
}
|
|
||||||
|
|
||||||
write_launcher_file() {
|
|
||||||
local stage="$1"
|
|
||||||
|
|
||||||
install -m 755 /dev/stdin "$stage/usr/bin/v2rayn" <<'EOF'
|
|
||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
DIR="/opt/v2rayN"
|
|
||||||
cd "$DIR"
|
|
||||||
|
|
||||||
if [[ -x "$DIR/v2rayN" ]]; then
|
|
||||||
exec "$DIR/v2rayN" "$@"
|
|
||||||
fi
|
|
||||||
|
|
||||||
for dll in v2rayN.Desktop.dll v2rayN.dll; do
|
|
||||||
if [[ -f "$DIR/$dll" ]]; then
|
|
||||||
exec /usr/bin/dotnet "$DIR/$dll" "$@"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "v2rayN launcher: no executable found in $DIR" >&2
|
|
||||||
ls -l "$DIR" >&2 || true
|
|
||||||
exit 1
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
write_desktop_file() {
|
|
||||||
local stage="$1"
|
|
||||||
|
|
||||||
install -m 644 /dev/stdin "$stage/usr/share/applications/v2rayn.desktop" <<'EOF'
|
|
||||||
[Desktop Entry]
|
|
||||||
Type=Application
|
|
||||||
Name=v2rayN
|
|
||||||
Comment=v2rayN for Debian GNU Linux
|
|
||||||
Exec=v2rayn
|
|
||||||
Icon=v2rayn
|
|
||||||
Terminal=false
|
|
||||||
Categories=Network;
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
write_maintainer_scripts() {
|
|
||||||
local debian_dir="$1"
|
|
||||||
|
|
||||||
install -m 755 /dev/stdin "$debian_dir/postinst" <<'EOF'
|
|
||||||
#!/bin/sh
|
|
||||||
set -e
|
|
||||||
update-desktop-database /usr/share/applications >/dev/null 2>&1 || true
|
|
||||||
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
|
|
||||||
gtk-update-icon-cache -f /usr/share/icons/hicolor >/dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
exit 0
|
|
||||||
EOF
|
|
||||||
|
|
||||||
install -m 755 /dev/stdin "$debian_dir/postrm" <<'EOF'
|
|
||||||
#!/bin/sh
|
|
||||||
set -e
|
|
||||||
update-desktop-database /usr/share/applications >/dev/null 2>&1 || true
|
|
||||||
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
|
|
||||||
gtk-update-icon-cache -f /usr/share/icons/hicolor >/dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
exit 0
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
package_binary() {
|
|
||||||
local short="$1"
|
|
||||||
local rid="$2"
|
|
||||||
local deb_arch="$3"
|
|
||||||
local pubdir=""
|
|
||||||
local workdir=""
|
|
||||||
local stage=""
|
|
||||||
local debian_dir=""
|
|
||||||
local project_dir=""
|
|
||||||
local icon_candidate=""
|
|
||||||
local shlibs_depends=""
|
|
||||||
local extra_depends=""
|
|
||||||
local final_depends=""
|
|
||||||
local multiarch=""
|
|
||||||
local sys_libdir=""
|
|
||||||
local sys_usrlibdir=""
|
|
||||||
local deb_out=""
|
|
||||||
|
|
||||||
pubdir="$(dirname "$PROJECT")/bin/Release/net10.0/${rid}/publish"
|
|
||||||
[[ -d "$pubdir" ]] || { echo "Publish directory not found: $pubdir"; return 1; }
|
|
||||||
|
|
||||||
workdir="$(mktemp -d)"
|
|
||||||
trap '[[ -n "${workdir:-}" ]] && rm -rf "$workdir"' RETURN
|
|
||||||
|
|
||||||
stage="$workdir/${PKGROOT}_${VERSION}_${deb_arch}"
|
|
||||||
debian_dir="$stage/DEBIAN"
|
|
||||||
|
|
||||||
mkdir -p "$stage/opt/v2rayN" "$stage/usr/bin" "$stage/usr/share/applications" "$stage/usr/share/icons/hicolor/256x256/apps" "$debian_dir"
|
|
||||||
cp -a "$pubdir/." "$stage/opt/v2rayN/"
|
|
||||||
|
|
||||||
project_dir="$(cd "$(dirname "$PROJECT")" && pwd)"
|
|
||||||
icon_candidate="$project_dir/v2rayN.png"
|
|
||||||
[[ -f "$icon_candidate" ]] && cp "$icon_candidate" "$stage/usr/share/icons/hicolor/256x256/apps/v2rayn.png" || true
|
|
||||||
|
|
||||||
stage_runtime_assets "$stage/opt/v2rayN" "$rid"
|
|
||||||
write_launcher_file "$stage"
|
|
||||||
write_desktop_file "$stage"
|
|
||||||
write_maintainer_scripts "$debian_dir"
|
|
||||||
|
|
||||||
extra_depends="libc6 (>= 2.34), fontconfig (>= 2.13.1), desktop-file-utils (>= 0.26), xdg-utils (>= 1.1.3), coreutils (>= 8.32), bash (>= 5.1), libfreetype6 (>= 2.11)"
|
|
||||||
|
|
||||||
mkdir -p "$workdir/debian"
|
|
||||||
cat > "$workdir/debian/control" <<EOF
|
|
||||||
Source: v2rayn
|
|
||||||
Section: net
|
|
||||||
Priority: optional
|
|
||||||
Maintainer: 2dust <noreply@github.com>
|
|
||||||
Standards-Version: 4.7.0
|
|
||||||
|
|
||||||
Package: v2rayn
|
|
||||||
Architecture: ${deb_arch}
|
|
||||||
Description: v2rayN
|
|
||||||
EOF
|
|
||||||
|
|
||||||
multiarch="$(dpkg-architecture -a"$deb_arch" -qDEB_HOST_MULTIARCH)"
|
|
||||||
sys_libdir="/lib/$multiarch"
|
|
||||||
sys_usrlibdir="/usr/lib/$multiarch"
|
|
||||||
|
|
||||||
: > "$debian_dir/substvars"
|
|
||||||
|
|
||||||
mapfile -t ELF_FILES < <(
|
|
||||||
find "$stage/opt/v2rayN" -type f \( -name "*.so*" -o -perm -111 \) ! -name 'libcoreclrtraceptprovider.so'
|
|
||||||
)
|
|
||||||
|
|
||||||
if [[ "${#ELF_FILES[@]}" -gt 0 ]]; then
|
|
||||||
(
|
|
||||||
cd "$workdir"
|
|
||||||
dpkg-shlibdeps \
|
|
||||||
-l"$stage/opt/v2rayN" \
|
|
||||||
-l"$sys_libdir" \
|
|
||||||
-l"$sys_usrlibdir" \
|
|
||||||
-T"$debian_dir/substvars" \
|
|
||||||
"${ELF_FILES[@]}"
|
|
||||||
) >/dev/null 2>&1 || true
|
|
||||||
fi
|
|
||||||
|
|
||||||
shlibs_depends="$(sed -n 's/^shlibs:Depends=//p' "$debian_dir/substvars" | head -n1 || true)"
|
|
||||||
|
|
||||||
if [[ -n "$shlibs_depends" ]]; then
|
|
||||||
shlibs_depends="$(echo "$shlibs_depends" \
|
|
||||||
| sed -E 's/ *\([^)]*\)//g' \
|
|
||||||
| sed -E 's/ *, */, /g' \
|
|
||||||
| sed -E 's/^, *//; s/, *$//')"
|
|
||||||
final_depends="${shlibs_depends}, ${extra_depends}"
|
|
||||||
else
|
|
||||||
final_depends="${extra_depends}"
|
|
||||||
fi
|
|
||||||
|
|
||||||
cat > "$debian_dir/control" <<EOF
|
|
||||||
Package: v2rayn
|
|
||||||
Version: ${VERSION}
|
|
||||||
Architecture: ${deb_arch}
|
|
||||||
Maintainer: 2dust <noreply@github.com>
|
|
||||||
Homepage: https://github.com/2dust/v2rayN
|
|
||||||
Section: net
|
|
||||||
Priority: optional
|
|
||||||
Depends: ${final_depends}
|
|
||||||
Description: v2rayN (Avalonia) GUI client for Linux
|
|
||||||
Support vless / vmess / Trojan / http / socks / Anytls / Hysteria2 /
|
|
||||||
Shadowsocks / tuic / WireGuard.
|
|
||||||
EOF
|
|
||||||
|
|
||||||
find "$stage/opt/v2rayN" -type d -exec chmod 0755 {} +
|
|
||||||
find "$stage/opt/v2rayN" -type f -exec chmod 0644 {} +
|
|
||||||
[[ -f "$stage/opt/v2rayN/v2rayN" ]] && chmod 0755 "$stage/opt/v2rayN/v2rayN" || true
|
|
||||||
|
|
||||||
deb_out="$OUTPUT_DIR/v2rayn_${VERSION}_${deb_arch}.deb"
|
|
||||||
dpkg-deb --root-owner-group --build "$stage" "$deb_out"
|
|
||||||
|
|
||||||
echo "Build done for $short. DEB at:"
|
|
||||||
echo " $deb_out"
|
|
||||||
BUILT_DEBS+=("$deb_out")
|
|
||||||
}
|
|
||||||
|
|
||||||
select_targets() {
|
|
||||||
printf '%s\n' loongarch64
|
|
||||||
}
|
|
||||||
|
|
||||||
build_one_target() {
|
|
||||||
local short="$1"
|
|
||||||
local meta=()
|
|
||||||
local rid=""
|
|
||||||
local deb_arch=""
|
|
||||||
|
|
||||||
mapfile -t meta < <(describe_target "$short") || return 1
|
|
||||||
rid="${meta[0]}"
|
|
||||||
deb_arch="${meta[1]}"
|
|
||||||
|
|
||||||
echo "[*] Building for target: $short (RID=$rid, DEB arch=$deb_arch)"
|
|
||||||
publish_binary "$rid"
|
|
||||||
package_binary "$short" "$rid" "$deb_arch"
|
|
||||||
}
|
|
||||||
|
|
||||||
print_summary() {
|
|
||||||
local pkg=""
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "================ Build Summary ================="
|
|
||||||
if [[ "${#BUILT_DEBS[@]}" -gt 0 ]]; then
|
|
||||||
echo "Output directory: $OUTPUT_DIR"
|
|
||||||
for pkg in "${BUILT_DEBS[@]}"; do
|
|
||||||
echo "$pkg"
|
|
||||||
done
|
|
||||||
else
|
|
||||||
echo "No DEBs detected in summary (check build logs above)."
|
|
||||||
fi
|
|
||||||
echo "==============================================="
|
|
||||||
}
|
|
||||||
|
|
||||||
main() {
|
|
||||||
local targets=()
|
|
||||||
local arch=""
|
|
||||||
|
|
||||||
parse_args "$@"
|
|
||||||
detect_environment
|
|
||||||
install_dependencies
|
|
||||||
prepare_workspace
|
|
||||||
resolve_version
|
|
||||||
|
|
||||||
mapfile -t targets < <(select_targets)
|
|
||||||
|
|
||||||
for arch in "${targets[@]}"; do
|
|
||||||
build_one_target "$arch"
|
|
||||||
done
|
|
||||||
|
|
||||||
print_summary
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -8,14 +8,21 @@ BUILD_FROM=""
|
|||||||
XRAY_VER="${XRAY_VER:-}"
|
XRAY_VER="${XRAY_VER:-}"
|
||||||
SING_VER="${SING_VER:-}"
|
SING_VER="${SING_VER:-}"
|
||||||
|
|
||||||
MIN_KERNEL="5.10"
|
MIN_KERNEL="6.12"
|
||||||
PKGROOT="v2rayN-publish"
|
PKGROOT="v2rayN-publish"
|
||||||
PROJECT_HINT="v2rayN.Desktop/v2rayN.Desktop.csproj"
|
PROJECT_HINT="v2rayN.Desktop/v2rayN.Desktop.csproj"
|
||||||
OUTPUT_DIR="${HOME}/debbuild"
|
OUTPUT_DIR="${HOME}/debbuild"
|
||||||
DOTNET_RISCV_VERSION="10.0.108"
|
|
||||||
DOTNET_RISCV_BASE="https://github.com/xujiegb/dotnet-riscv/releases/download"
|
NUGET_CACHE_DIR=""
|
||||||
DOTNET_RISCV_FILE="dotnet-sdk-${DOTNET_RISCV_VERSION}-linux-riscv64.tar.gz"
|
DOTNET_SDK_DIR=""
|
||||||
DOTNET_SDK_URL="${DOTNET_RISCV_BASE}/${DOTNET_RISCV_VERSION}/${DOTNET_RISCV_FILE}"
|
|
||||||
|
DOTNET_NUPKG_BASE="${DOTNET_NUPKG_BASE:-https://github.com/autorepobot/dotnet-nupkg-prebuild/releases/download}"
|
||||||
|
SKIASHARP_BASE="${SKIASHARP_BASE:-https://github.com/autorepobot/SkiaSharp-ppc64le/releases/download}"
|
||||||
|
SkiaSharp_VERSION="${SkiaSharp_VERSION:-3.119.4}"
|
||||||
|
HarfBuzzSharp_VERSION="${HarfBuzzSharp_VERSION:-8.3.1.5}"
|
||||||
|
|
||||||
|
DOTNET_SDK_VERSION="${DOTNET_SDK_VERSION:-10.0.114}"
|
||||||
|
DOTNET_X86_VERSION="${DOTNET_X86_VERSION:-10.0.114}"
|
||||||
|
|
||||||
OS_ID=""
|
OS_ID=""
|
||||||
OS_NAME=""
|
OS_NAME=""
|
||||||
@@ -24,6 +31,10 @@ HOST_ARCH=""
|
|||||||
SCRIPT_DIR=""
|
SCRIPT_DIR=""
|
||||||
PROJECT=""
|
PROJECT=""
|
||||||
VERSION=""
|
VERSION=""
|
||||||
|
BUILT_ALL=0
|
||||||
|
|
||||||
|
X86_RID="linux-x86"
|
||||||
|
X86_DEB_ARCH="i386"
|
||||||
|
|
||||||
declare -a BUILT_DEBS=()
|
declare -a BUILT_DEBS=()
|
||||||
|
|
||||||
@@ -32,6 +43,13 @@ die() {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get_runtime_version() {
|
||||||
|
local sdk_ver="$1"
|
||||||
|
local prefix="${sdk_ver%.*}"
|
||||||
|
local patch="${sdk_ver##*.}"
|
||||||
|
echo "${prefix}.${patch#1}"
|
||||||
|
}
|
||||||
|
|
||||||
parse_args() {
|
parse_args() {
|
||||||
local first_arg="${1:-}"
|
local first_arg="${1:-}"
|
||||||
|
|
||||||
@@ -82,8 +100,8 @@ This script only supports: Debian."
|
|||||||
esac
|
esac
|
||||||
|
|
||||||
case "$HOST_ARCH" in
|
case "$HOST_ARCH" in
|
||||||
riscv64) ;;
|
x86_64|aarch64) ;;
|
||||||
*) die "Only supports riscv64" ;;
|
*) die "This script cross-compiles linux-x86 from x86_64 or aarch64 only." ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
current_kernel="$(uname -r)"
|
current_kernel="$(uname -r)"
|
||||||
@@ -91,11 +109,12 @@ This script only supports: Debian."
|
|||||||
|
|
||||||
[[ "$lowest" == "$MIN_KERNEL" ]] || die "Kernel $current_kernel is below $MIN_KERNEL"
|
[[ "$lowest" == "$MIN_KERNEL" ]] || die "Kernel $current_kernel is below $MIN_KERNEL"
|
||||||
echo "[OK] Kernel $current_kernel verified."
|
echo "[OK] Kernel $current_kernel verified."
|
||||||
|
echo "[OK] Host architecture: $HOST_ARCH"
|
||||||
|
echo "[OK] Target: $X86_RID (Debian $X86_DEB_ARCH)"
|
||||||
}
|
}
|
||||||
|
|
||||||
install_dependencies() {
|
install_dependencies() {
|
||||||
local install_ok=0
|
local install_ok=0
|
||||||
local tmp_dotnet=""
|
|
||||||
|
|
||||||
mkdir -p "$OUTPUT_DIR"
|
mkdir -p "$OUTPUT_DIR"
|
||||||
|
|
||||||
@@ -103,14 +122,21 @@ install_dependencies() {
|
|||||||
sudo apt-get update
|
sudo apt-get update
|
||||||
sudo apt-get -y install \
|
sudo apt-get -y install \
|
||||||
curl unzip tar jq rsync ca-certificates git dpkg-dev fakeroot file \
|
curl unzip tar jq rsync ca-certificates git dpkg-dev fakeroot file \
|
||||||
desktop-file-utils xdg-utils wget gcc make pkg-config \
|
desktop-file-utils xdg-utils wget python3
|
||||||
libicu-dev libssl-dev libfontconfig1 libfreetype6 zlib1g
|
|
||||||
|
|
||||||
mkdir -p "$HOME/.dotnet"
|
sudo dpkg --add-architecture "$X86_DEB_ARCH" || true
|
||||||
tmp_dotnet="$(mktemp -d)"
|
sudo apt-get update
|
||||||
curl -fL "$DOTNET_SDK_URL" -o "$tmp_dotnet/$DOTNET_RISCV_FILE"
|
sudo apt-get -y install \
|
||||||
tar -C "$HOME/.dotnet" -xzf "$tmp_dotnet/$DOTNET_RISCV_FILE"
|
"libc6:${X86_DEB_ARCH}" \
|
||||||
rm -rf "$tmp_dotnet"
|
"libgcc-s1:${X86_DEB_ARCH}" \
|
||||||
|
"libstdc++6:${X86_DEB_ARCH}" \
|
||||||
|
"zlib1g:${X86_DEB_ARCH}" \
|
||||||
|
"libfontconfig1:${X86_DEB_ARCH}" \
|
||||||
|
"libfreetype6:${X86_DEB_ARCH}"
|
||||||
|
|
||||||
|
wget -q https://dot.net/v1/dotnet-install.sh
|
||||||
|
chmod +x dotnet-install.sh
|
||||||
|
./dotnet-install.sh --version "$DOTNET_SDK_VERSION" --install-dir "$HOME/.dotnet"
|
||||||
|
|
||||||
export PATH="$HOME/.dotnet:$PATH"
|
export PATH="$HOME/.dotnet:$PATH"
|
||||||
export DOTNET_ROOT="$HOME/.dotnet"
|
export DOTNET_ROOT="$HOME/.dotnet"
|
||||||
@@ -120,11 +146,30 @@ install_dependencies() {
|
|||||||
|
|
||||||
if [[ "$install_ok" -ne 1 ]]; then
|
if [[ "$install_ok" -ne 1 ]]; then
|
||||||
echo "Could not auto-install dependencies for '$OS_ID'. Make sure these are available:"
|
echo "Could not auto-install dependencies for '$OS_ID'. Make sure these are available:"
|
||||||
echo "dotnet-riscv SDK, curl, unzip, tar, rsync, git, gcc, make, dpkg-deb, fakeroot, libicu-dev, libssl-dev"
|
echo "dotnet-sdk 10.x, i386 runtime libraries (libc6, libgcc-s1, libstdc++6, zlib1g, libfontconfig1, libfreetype6)"
|
||||||
|
echo "curl, unzip, tar, rsync, git, dpkg-deb, desktop-file-utils, xdg-utils"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
prepare_deb_target_arch() {
|
||||||
|
local target_arch="$X86_DEB_ARCH"
|
||||||
|
|
||||||
|
echo "[+] Prepare Debian multiarch environment for $X86_RID: $target_arch"
|
||||||
|
|
||||||
|
sudo dpkg --add-architecture "$target_arch" || true
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get -y install \
|
||||||
|
"libc6:${target_arch}" \
|
||||||
|
"libgcc-s1:${target_arch}" \
|
||||||
|
"libstdc++6:${target_arch}" \
|
||||||
|
"zlib1g:${target_arch}" \
|
||||||
|
"libfontconfig1:${target_arch}" \
|
||||||
|
"libfreetype6:${target_arch}"
|
||||||
|
|
||||||
|
echo "[OK] Debian target libraries prepared for $target_arch"
|
||||||
|
}
|
||||||
|
|
||||||
prepare_workspace() {
|
prepare_workspace() {
|
||||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
cd "$SCRIPT_DIR"
|
cd "$SCRIPT_DIR"
|
||||||
@@ -257,13 +302,122 @@ resolve_version() {
|
|||||||
echo "[*] GUI version resolved as: ${VERSION}"
|
echo "[*] GUI version resolved as: ${VERSION}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
download_nuget_packages() {
|
||||||
|
NUGET_CACHE_DIR="$(mktemp -d)"
|
||||||
|
|
||||||
|
local x86_rt
|
||||||
|
x86_rt="$(get_runtime_version "$DOTNET_X86_VERSION")"
|
||||||
|
|
||||||
|
local urls=(
|
||||||
|
"${DOTNET_NUPKG_BASE}/${x86_rt}/Microsoft.AspNetCore.App.Runtime.linux-x86.${x86_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${x86_rt}/Microsoft.NETCore.App.Host.linux-x86.${x86_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${x86_rt}/Microsoft.NETCore.App.Runtime.linux-x86.${x86_rt}.nupkg"
|
||||||
|
"${SKIASHARP_BASE}/v${SkiaSharp_VERSION}/SkiaSharp.NativeAssets.Linux.${SkiaSharp_VERSION}.nupkg"
|
||||||
|
"${SKIASHARP_BASE}/v${SkiaSharp_VERSION}/HarfBuzzSharp.NativeAssets.Linux.${HarfBuzzSharp_VERSION}.nupkg"
|
||||||
|
)
|
||||||
|
|
||||||
|
echo "[+] Downloading prebuilt NuGet packages to: $NUGET_CACHE_DIR"
|
||||||
|
local u pkg_name
|
||||||
|
for u in "${urls[@]}"; do
|
||||||
|
pkg_name="${u##*/}"
|
||||||
|
echo " -> $pkg_name"
|
||||||
|
curl -fL "$u" -o "$NUGET_CACHE_DIR/$pkg_name" || {
|
||||||
|
echo "[!] Failed to download $u" >&2
|
||||||
|
rm -rf "$NUGET_CACHE_DIR"
|
||||||
|
NUGET_CACHE_DIR=""
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "[OK] Prebuilt NuGet packages ready in $NUGET_CACHE_DIR"
|
||||||
|
}
|
||||||
|
|
||||||
|
prepare_dotnet_sdk() {
|
||||||
|
echo "[+] Using host .NET SDK for cross-target $X86_RID"
|
||||||
|
dotnet --info
|
||||||
|
DOTNET_SDK_DIR="${DOTNET_ROOT:-$(dirname "$(command -v dotnet)")}"
|
||||||
|
}
|
||||||
|
|
||||||
|
patch_x86_sdk() {
|
||||||
|
local sdk_props=""
|
||||||
|
local sdk_version=""
|
||||||
|
|
||||||
|
sdk_version="$(dotnet --version)"
|
||||||
|
sdk_props="$DOTNET_ROOT/sdk/${sdk_version}/Microsoft.NETCoreSdk.BundledVersions.props"
|
||||||
|
|
||||||
|
[[ -f "$sdk_props" ]] || die "SDK props file not found: $sdk_props"
|
||||||
|
|
||||||
|
echo "[+] Patching SDK: $sdk_props"
|
||||||
|
|
||||||
|
python3 - "$sdk_props" <<'PY'
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
path = Path(sys.argv[1])
|
||||||
|
text = path.read_text()
|
||||||
|
old = text
|
||||||
|
|
||||||
|
|
||||||
|
def add_attr_to_known_blocks(text, marker, attr):
|
||||||
|
start = 0
|
||||||
|
while True:
|
||||||
|
start = text.find(marker, start)
|
||||||
|
if start == -1:
|
||||||
|
break
|
||||||
|
|
||||||
|
end = text.find('/>', start)
|
||||||
|
if end == -1:
|
||||||
|
break
|
||||||
|
|
||||||
|
block = text[start:end]
|
||||||
|
attr_pos = block.find(attr)
|
||||||
|
if attr_pos != -1:
|
||||||
|
value_start = attr_pos + len(attr)
|
||||||
|
value_end = block.find('"', value_start)
|
||||||
|
if value_end != -1:
|
||||||
|
value = block[value_start:value_end]
|
||||||
|
values = value.split(';')
|
||||||
|
if 'linux-x86' not in values:
|
||||||
|
value = value + ';linux-x86'
|
||||||
|
block = block[:value_start] + value + block[value_end:]
|
||||||
|
text = text[:start] + block + text[end:]
|
||||||
|
end = start + len(block)
|
||||||
|
start = end + 2
|
||||||
|
return text
|
||||||
|
|
||||||
|
for framework in ('Microsoft.NETCore.App', 'Microsoft.AspNetCore.App'):
|
||||||
|
text = add_attr_to_known_blocks(
|
||||||
|
text,
|
||||||
|
f'<KnownFrameworkReference Include="{framework}"',
|
||||||
|
'RuntimePackRuntimeIdentifiers="',
|
||||||
|
)
|
||||||
|
|
||||||
|
text = add_attr_to_known_blocks(
|
||||||
|
text,
|
||||||
|
'<KnownAppHostPack',
|
||||||
|
'AppHostRuntimeIdentifiers="',
|
||||||
|
)
|
||||||
|
|
||||||
|
if text == old:
|
||||||
|
raise SystemExit('ERROR: No SDK RuntimePack/AppHost mapping was patched')
|
||||||
|
|
||||||
|
path.write_text(text)
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "===== Verify RuntimePackRuntimeIdentifiers ====="
|
||||||
|
grep -n 'RuntimePackRuntimeIdentifiers=' "$sdk_props" | grep 'linux-x86'
|
||||||
|
|
||||||
|
echo "===== Verify AppHostRuntimeIdentifiers ====="
|
||||||
|
grep -n 'AppHostRuntimeIdentifiers=' "$sdk_props" | grep 'linux-x86'
|
||||||
|
}
|
||||||
|
|
||||||
xray_url_for_rid() {
|
xray_url_for_rid() {
|
||||||
local rid="$1"
|
local rid="$1"
|
||||||
local ver="$2"
|
local ver="$2"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-riscv64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-riscv64.zip" ;;
|
linux-x86) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-32.zip" ;;
|
||||||
*) return 1 ;;
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -272,8 +426,8 @@ singbox_url_for_rid() {
|
|||||||
local ver="$2"
|
local ver="$2"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-riscv64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-riscv64.tar.gz" ;;
|
linux-x86) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-386.tar.gz" ;;
|
||||||
*) return 1 ;;
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,8 +435,8 @@ bundle_url_for_rid() {
|
|||||||
local rid="$1"
|
local rid="$1"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-riscv64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-riscv64.zip" ;;
|
linux-x86) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-86.zip" ;;
|
||||||
*) return 1 ;;
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -303,7 +457,7 @@ download_xray() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
[[ -n "$ver" ]] || { echo "[xray] Failed to get version"; return 1; }
|
[[ -n "$ver" ]] || { echo "[xray] Failed to get version"; return 1; }
|
||||||
url="$(xray_url_for_rid "$rid" "$ver")" || { echo "[xray] Unsupported RID: $rid"; return 1; }
|
url="$(xray_url_for_rid "$rid" "$ver")" || { echo "[xray] Unsupported RID for upstream Xray: $rid (skipped)"; return 0; }
|
||||||
|
|
||||||
echo "[+] Download xray: $url"
|
echo "[+] Download xray: $url"
|
||||||
|
|
||||||
@@ -475,27 +629,38 @@ stage_runtime_assets() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe_target() {
|
describe_target() {
|
||||||
local short="$1"
|
printf '%s\n%s\n' "$X86_RID" "$X86_DEB_ARCH"
|
||||||
|
|
||||||
case "$short" in
|
|
||||||
riscv64) printf '%s\n%s\n' "linux-riscv64" "riscv64" ;;
|
|
||||||
*) echo "Unknown arch '$short' (use riscv64)" >&2; return 1 ;;
|
|
||||||
esac
|
|
||||||
}
|
}
|
||||||
|
|
||||||
publish_binary() {
|
publish_binary() {
|
||||||
local rid="$1"
|
local rid="$1"
|
||||||
|
|
||||||
|
patch_x86_sdk
|
||||||
dotnet clean "$PROJECT" -c Release
|
dotnet clean "$PROJECT" -c Release
|
||||||
rm -rf "$(dirname "$PROJECT")/bin/Release/net10.0" || true
|
rm -rf "$(dirname "$PROJECT")/bin/Release/net10.0" || true
|
||||||
dotnet restore "$PROJECT"
|
|
||||||
dotnet publish "$PROJECT" -c Release -r "$rid" -p:PublishSingleFile=false -p:SelfContained=true
|
dotnet restore "$PROJECT" \
|
||||||
|
-r "$rid" \
|
||||||
|
--source "$NUGET_CACHE_DIR" \
|
||||||
|
--source "https://api.nuget.org/v3/index.json" \
|
||||||
|
-p:SelfContained=true \
|
||||||
|
-p:EnableWindowsTargeting=true \
|
||||||
|
--force-evaluate
|
||||||
|
|
||||||
|
dotnet publish "$PROJECT" \
|
||||||
|
-c Release \
|
||||||
|
-r "$rid" \
|
||||||
|
--source "$NUGET_CACHE_DIR" \
|
||||||
|
--source "https://api.nuget.org/v3/index.json" \
|
||||||
|
-p:PublishSingleFile=false \
|
||||||
|
-p:SelfContained=true \
|
||||||
|
--no-restore
|
||||||
}
|
}
|
||||||
|
|
||||||
write_launcher_file() {
|
write_launcher_file() {
|
||||||
local stage="$1"
|
local stage="$1"
|
||||||
|
|
||||||
install -m 755 /dev/stdin "$stage/usr/bin/v2rayn" <<'EOF'
|
install -m 755 /dev/stdin "$stage/usr/bin/v2rayn" <<'EOF_LAUNCHER'
|
||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
DIR="/opt/v2rayN"
|
DIR="/opt/v2rayN"
|
||||||
@@ -514,13 +679,13 @@ done
|
|||||||
echo "v2rayN launcher: no executable found in $DIR" >&2
|
echo "v2rayN launcher: no executable found in $DIR" >&2
|
||||||
ls -l "$DIR" >&2 || true
|
ls -l "$DIR" >&2 || true
|
||||||
exit 1
|
exit 1
|
||||||
EOF
|
EOF_LAUNCHER
|
||||||
}
|
}
|
||||||
|
|
||||||
write_desktop_file() {
|
write_desktop_file() {
|
||||||
local stage="$1"
|
local stage="$1"
|
||||||
|
|
||||||
install -m 644 /dev/stdin "$stage/usr/share/applications/v2rayn.desktop" <<'EOF'
|
install -m 644 /dev/stdin "$stage/usr/share/applications/v2rayn.desktop" <<'EOF_DESKTOP'
|
||||||
[Desktop Entry]
|
[Desktop Entry]
|
||||||
Type=Application
|
Type=Application
|
||||||
Name=v2rayN
|
Name=v2rayN
|
||||||
@@ -529,13 +694,13 @@ Exec=v2rayn
|
|||||||
Icon=v2rayn
|
Icon=v2rayn
|
||||||
Terminal=false
|
Terminal=false
|
||||||
Categories=Network;
|
Categories=Network;
|
||||||
EOF
|
EOF_DESKTOP
|
||||||
}
|
}
|
||||||
|
|
||||||
write_maintainer_scripts() {
|
write_maintainer_scripts() {
|
||||||
local debian_dir="$1"
|
local debian_dir="$1"
|
||||||
|
|
||||||
install -m 755 /dev/stdin "$debian_dir/postinst" <<'EOF'
|
install -m 755 /dev/stdin "$debian_dir/postinst" <<'EOF_POSTINST'
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -e
|
set -e
|
||||||
update-desktop-database /usr/share/applications >/dev/null 2>&1 || true
|
update-desktop-database /usr/share/applications >/dev/null 2>&1 || true
|
||||||
@@ -543,9 +708,9 @@ if command -v gtk-update-icon-cache >/dev/null 2>&1; then
|
|||||||
gtk-update-icon-cache -f /usr/share/icons/hicolor >/dev/null 2>&1 || true
|
gtk-update-icon-cache -f /usr/share/icons/hicolor >/dev/null 2>&1 || true
|
||||||
fi
|
fi
|
||||||
exit 0
|
exit 0
|
||||||
EOF
|
EOF_POSTINST
|
||||||
|
|
||||||
install -m 755 /dev/stdin "$debian_dir/postrm" <<'EOF'
|
install -m 755 /dev/stdin "$debian_dir/postrm" <<'EOF_POSTRM'
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
set -e
|
set -e
|
||||||
update-desktop-database /usr/share/applications >/dev/null 2>&1 || true
|
update-desktop-database /usr/share/applications >/dev/null 2>&1 || true
|
||||||
@@ -553,7 +718,7 @@ if command -v gtk-update-icon-cache >/dev/null 2>&1; then
|
|||||||
gtk-update-icon-cache -f /usr/share/icons/hicolor >/dev/null 2>&1 || true
|
gtk-update-icon-cache -f /usr/share/icons/hicolor >/dev/null 2>&1 || true
|
||||||
fi
|
fi
|
||||||
exit 0
|
exit 0
|
||||||
EOF
|
EOF_POSTRM
|
||||||
}
|
}
|
||||||
|
|
||||||
package_binary() {
|
package_binary() {
|
||||||
@@ -595,10 +760,12 @@ package_binary() {
|
|||||||
write_desktop_file "$stage"
|
write_desktop_file "$stage"
|
||||||
write_maintainer_scripts "$debian_dir"
|
write_maintainer_scripts "$debian_dir"
|
||||||
|
|
||||||
extra_depends="libc6 (>= 2.34), fontconfig (>= 2.13.1), desktop-file-utils (>= 0.26), xdg-utils (>= 1.1.3), coreutils (>= 8.32), bash (>= 5.1), libfreetype6 (>= 2.11)"
|
prepare_deb_target_arch
|
||||||
|
|
||||||
|
extra_depends="libc6 (>= 2.36), fontconfig (>= 2.14.1), desktop-file-utils (>= 0.26), xdg-utils (>= 1.1.3), coreutils (>= 9.1), bash (>= 5.2.15), libfreetype6 (>= 2.12)"
|
||||||
|
|
||||||
mkdir -p "$workdir/debian"
|
mkdir -p "$workdir/debian"
|
||||||
cat > "$workdir/debian/control" <<EOF
|
cat > "$workdir/debian/control" <<EOF_CONTROL
|
||||||
Source: v2rayn
|
Source: v2rayn
|
||||||
Section: net
|
Section: net
|
||||||
Priority: optional
|
Priority: optional
|
||||||
@@ -608,7 +775,7 @@ Standards-Version: 4.7.0
|
|||||||
Package: v2rayn
|
Package: v2rayn
|
||||||
Architecture: ${deb_arch}
|
Architecture: ${deb_arch}
|
||||||
Description: v2rayN
|
Description: v2rayN
|
||||||
EOF
|
EOF_CONTROL
|
||||||
|
|
||||||
multiarch="$(dpkg-architecture -a"$deb_arch" -qDEB_HOST_MULTIARCH)"
|
multiarch="$(dpkg-architecture -a"$deb_arch" -qDEB_HOST_MULTIARCH)"
|
||||||
sys_libdir="/lib/$multiarch"
|
sys_libdir="/lib/$multiarch"
|
||||||
@@ -629,7 +796,7 @@ EOF
|
|||||||
-l"$sys_usrlibdir" \
|
-l"$sys_usrlibdir" \
|
||||||
-T"$debian_dir/substvars" \
|
-T"$debian_dir/substvars" \
|
||||||
"${ELF_FILES[@]}"
|
"${ELF_FILES[@]}"
|
||||||
) >/dev/null 2>&1 || true
|
) || true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
shlibs_depends="$(sed -n 's/^shlibs:Depends=//p' "$debian_dir/substvars" | head -n1 || true)"
|
shlibs_depends="$(sed -n 's/^shlibs:Depends=//p' "$debian_dir/substvars" | head -n1 || true)"
|
||||||
@@ -644,7 +811,7 @@ EOF
|
|||||||
final_depends="${extra_depends}"
|
final_depends="${extra_depends}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
cat > "$debian_dir/control" <<EOF
|
cat > "$debian_dir/control" <<EOF_CONTROL2
|
||||||
Package: v2rayn
|
Package: v2rayn
|
||||||
Version: ${VERSION}
|
Version: ${VERSION}
|
||||||
Architecture: ${deb_arch}
|
Architecture: ${deb_arch}
|
||||||
@@ -656,7 +823,7 @@ Depends: ${final_depends}
|
|||||||
Description: v2rayN (Avalonia) GUI client for Linux
|
Description: v2rayN (Avalonia) GUI client for Linux
|
||||||
Support vless / vmess / Trojan / http / socks / Anytls / Hysteria2 /
|
Support vless / vmess / Trojan / http / socks / Anytls / Hysteria2 /
|
||||||
Shadowsocks / tuic / WireGuard.
|
Shadowsocks / tuic / WireGuard.
|
||||||
EOF
|
EOF_CONTROL2
|
||||||
|
|
||||||
find "$stage/opt/v2rayN" -type d -exec chmod 0755 {} +
|
find "$stage/opt/v2rayN" -type d -exec chmod 0755 {} +
|
||||||
find "$stage/opt/v2rayN" -type f -exec chmod 0644 {} +
|
find "$stage/opt/v2rayN" -type f -exec chmod 0644 {} +
|
||||||
@@ -670,21 +837,13 @@ EOF
|
|||||||
BUILT_DEBS+=("$deb_out")
|
BUILT_DEBS+=("$deb_out")
|
||||||
}
|
}
|
||||||
|
|
||||||
select_targets() {
|
|
||||||
printf '%s\n' riscv64
|
|
||||||
}
|
|
||||||
|
|
||||||
build_one_target() {
|
build_one_target() {
|
||||||
local short="$1"
|
local short="x86"
|
||||||
local meta=()
|
local rid="$X86_RID"
|
||||||
local rid=""
|
local deb_arch="$X86_DEB_ARCH"
|
||||||
local deb_arch=""
|
|
||||||
|
|
||||||
mapfile -t meta < <(describe_target "$short") || return 1
|
|
||||||
rid="${meta[0]}"
|
|
||||||
deb_arch="${meta[1]}"
|
|
||||||
|
|
||||||
echo "[*] Building for target: $short (RID=$rid, DEB arch=$deb_arch)"
|
echo "[*] Building for target: $short (RID=$rid, DEB arch=$deb_arch)"
|
||||||
|
prepare_dotnet_sdk
|
||||||
publish_binary "$rid"
|
publish_binary "$rid"
|
||||||
package_binary "$short" "$rid" "$deb_arch"
|
package_binary "$short" "$rid" "$deb_arch"
|
||||||
}
|
}
|
||||||
@@ -706,20 +865,17 @@ print_summary() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
local targets=()
|
|
||||||
local arch=""
|
|
||||||
|
|
||||||
parse_args "$@"
|
parse_args "$@"
|
||||||
detect_environment
|
detect_environment
|
||||||
install_dependencies
|
install_dependencies
|
||||||
prepare_workspace
|
prepare_workspace
|
||||||
resolve_version
|
resolve_version
|
||||||
|
|
||||||
mapfile -t targets < <(select_targets)
|
download_nuget_packages || die "Failed to download prebuilt NuGet packages."
|
||||||
|
|
||||||
for arch in "${targets[@]}"; do
|
build_one_target
|
||||||
build_one_target "$arch"
|
|
||||||
done
|
rm -rf "${NUGET_CACHE_DIR:-}" || true
|
||||||
|
|
||||||
print_summary
|
print_summary
|
||||||
}
|
}
|
||||||
Regular → Executable
+271
-40
@@ -14,6 +14,30 @@ PKGROOT="v2rayN-publish"
|
|||||||
PROJECT_HINT="v2rayN.Desktop/v2rayN.Desktop.csproj"
|
PROJECT_HINT="v2rayN.Desktop/v2rayN.Desktop.csproj"
|
||||||
OUTPUT_DIR="${HOME}/debbuild"
|
OUTPUT_DIR="${HOME}/debbuild"
|
||||||
|
|
||||||
|
NUGET_CACHE_DIR=""
|
||||||
|
DOTNET_NUPKG_BASE="${DOTNET_NUPKG_BASE:-https://github.com/autorepobot/dotnet-nupkg-prebuild/releases/download}"
|
||||||
|
SKIASHARP_BASE="${SKIASHARP_BASE:-https://github.com/autorepobot/SkiaSharp-ppc64le/releases/download}"
|
||||||
|
SkiaSharp_VERSION="${SkiaSharp_VERSION:-3.119.4}"
|
||||||
|
HarfBuzzSharp_VERSION="${HarfBuzzSharp_VERSION:-8.3.1.5}"
|
||||||
|
|
||||||
|
DOTNET_SDK_VERSION="${DOTNET_SDK_VERSION:-10.0.114}"
|
||||||
|
|
||||||
|
DOTNET_RISCV_VERSION="${DOTNET_RISCV_VERSION:-10.0.114}"
|
||||||
|
DOTNET_RISCV_BASE="${DOTNET_RISCV_BASE:-https://github.com/autorepobot/dotnet-riscv/releases/download}"
|
||||||
|
DOTNET_RISCV_FILE="dotnet-sdk-${DOTNET_RISCV_VERSION}-linux-riscv64.tar.gz"
|
||||||
|
DOTNET_RISCV_SDK_URL="${DOTNET_RISCV_SDK_URL:-${DOTNET_RISCV_BASE}/${DOTNET_RISCV_VERSION}/${DOTNET_RISCV_FILE}}"
|
||||||
|
|
||||||
|
DOTNET_PPC64LE_VERSION="${DOTNET_PPC64LE_VERSION:-10.0.114}"
|
||||||
|
DOTNET_PPC64LE_BASE="${DOTNET_PPC64LE_BASE:-https://github.com/IBM/dotnet-s390x/releases/download}"
|
||||||
|
DOTNET_PPC64LE_FILE="dotnet-sdk-${DOTNET_PPC64LE_VERSION}-linux-ppc64le.tar.gz"
|
||||||
|
DOTNET_PPC64LE_SDK_URL="${DOTNET_PPC64LE_SDK_URL:-${DOTNET_PPC64LE_BASE}/v${DOTNET_PPC64LE_VERSION}/${DOTNET_PPC64LE_FILE}}"
|
||||||
|
|
||||||
|
DOTNET_LOONGARCH_VERSION="${DOTNET_LOONGARCH_VERSION:-10.0.114}"
|
||||||
|
DOTNET_LOONGARCH_TAG="${DOTNET_LOONGARCH_TAG:-v10.0.114-loongarch64}"
|
||||||
|
DOTNET_LOONGARCH_BASE="${DOTNET_LOONGARCH_BASE:-https://github.com/loongson/dotnet/releases/download}"
|
||||||
|
DOTNET_LOONGARCH_FILE="dotnet-sdk-${DOTNET_LOONGARCH_VERSION}-linux-loongarch64.tar.gz"
|
||||||
|
DOTNET_LOONGARCH_SDK_URL="${DOTNET_LOONGARCH_SDK_URL:-${DOTNET_LOONGARCH_BASE}/${DOTNET_LOONGARCH_TAG}/${DOTNET_LOONGARCH_FILE}}"
|
||||||
|
|
||||||
OS_ID=""
|
OS_ID=""
|
||||||
OS_NAME=""
|
OS_NAME=""
|
||||||
OS_VERSION_ID=""
|
OS_VERSION_ID=""
|
||||||
@@ -21,6 +45,7 @@ HOST_ARCH=""
|
|||||||
SCRIPT_DIR=""
|
SCRIPT_DIR=""
|
||||||
PROJECT=""
|
PROJECT=""
|
||||||
VERSION=""
|
VERSION=""
|
||||||
|
BUILT_ALL=0
|
||||||
|
|
||||||
declare -a BUILT_DEBS=()
|
declare -a BUILT_DEBS=()
|
||||||
|
|
||||||
@@ -29,6 +54,13 @@ die() {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get_runtime_version() {
|
||||||
|
local sdk_ver="$1"
|
||||||
|
local prefix="${sdk_ver%.*}"
|
||||||
|
local patch="${sdk_ver##*.}"
|
||||||
|
echo "${prefix}.${patch#1}"
|
||||||
|
}
|
||||||
|
|
||||||
parse_args() {
|
parse_args() {
|
||||||
local first_arg="${1:-}"
|
local first_arg="${1:-}"
|
||||||
|
|
||||||
@@ -80,8 +112,8 @@ This script only supports: Debian."
|
|||||||
esac
|
esac
|
||||||
|
|
||||||
case "$HOST_ARCH" in
|
case "$HOST_ARCH" in
|
||||||
x86_64|aarch64) ;;
|
x86_64|aarch64|riscv64|ppc64le|loongarch64) ;;
|
||||||
*) die "Only supports aarch64 / x86_64" ;;
|
*) die "Only supports x86_64 / aarch64 / riscv64 / ppc64le / loongarch64" ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
current_kernel="$(uname -r)"
|
current_kernel="$(uname -r)"
|
||||||
@@ -106,26 +138,38 @@ install_dependencies() {
|
|||||||
case "$HOST_ARCH" in
|
case "$HOST_ARCH" in
|
||||||
aarch64) foreign_arch="amd64" ;;
|
aarch64) foreign_arch="amd64" ;;
|
||||||
x86_64) foreign_arch="arm64" ;;
|
x86_64) foreign_arch="arm64" ;;
|
||||||
*) die "Only supports aarch64 / x86_64" ;;
|
riscv64|ppc64le|loongarch64)
|
||||||
|
foreign_arch=""
|
||||||
|
;;
|
||||||
|
*) die "Only supports x86_64 / aarch64 / riscv64 / ppc64le / loongarch64" ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
sudo dpkg --add-architecture "$foreign_arch" || true
|
if [[ -n "$foreign_arch" ]]; then
|
||||||
sudo apt-get update
|
sudo dpkg --add-architecture "$foreign_arch" || true
|
||||||
sudo apt-get -y install \
|
sudo apt-get update
|
||||||
"libc6:${foreign_arch}" \
|
sudo apt-get -y install \
|
||||||
"libgcc-s1:${foreign_arch}" \
|
"libc6:${foreign_arch}" \
|
||||||
"libstdc++6:${foreign_arch}" \
|
"libgcc-s1:${foreign_arch}" \
|
||||||
"zlib1g:${foreign_arch}" \
|
"libstdc++6:${foreign_arch}" \
|
||||||
"libfontconfig1:${foreign_arch}"
|
"zlib1g:${foreign_arch}" \
|
||||||
|
"libfontconfig1:${foreign_arch}"
|
||||||
|
fi
|
||||||
|
|
||||||
wget -q https://dot.net/v1/dotnet-install.sh
|
case "$HOST_ARCH" in
|
||||||
chmod +x dotnet-install.sh
|
x86_64|aarch64)
|
||||||
./dotnet-install.sh --channel 10.0.1xx --install-dir "$HOME/.dotnet"
|
wget -q https://dot.net/v1/dotnet-install.sh
|
||||||
|
chmod +x dotnet-install.sh
|
||||||
|
./dotnet-install.sh --version "$DOTNET_SDK_VERSION" --install-dir "$HOME/.dotnet"
|
||||||
|
|
||||||
export PATH="$HOME/.dotnet:$PATH"
|
export PATH="$HOME/.dotnet:$PATH"
|
||||||
export DOTNET_ROOT="$HOME/.dotnet"
|
export DOTNET_ROOT="$HOME/.dotnet"
|
||||||
|
|
||||||
dotnet --info >/dev/null 2>&1 && install_ok=1
|
dotnet --info >/dev/null 2>&1 && install_ok=1
|
||||||
|
;;
|
||||||
|
riscv64|ppc64le|loongarch64)
|
||||||
|
install_ok=1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "$install_ok" -ne 1 ]]; then
|
if [[ "$install_ok" -ne 1 ]]; then
|
||||||
@@ -135,6 +179,61 @@ install_dependencies() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
prepare_deb_target_arch() {
|
||||||
|
local short="$1"
|
||||||
|
local target_arch=""
|
||||||
|
|
||||||
|
case "$HOST_ARCH:$short" in
|
||||||
|
x86_64:ppc64le|aarch64:ppc64le)
|
||||||
|
target_arch="ppc64el"
|
||||||
|
;;
|
||||||
|
x86_64:riscv64|aarch64:riscv64)
|
||||||
|
target_arch="riscv64"
|
||||||
|
;;
|
||||||
|
x86_64:loong64|aarch64:loong64)
|
||||||
|
target_arch="loong64"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
echo "[+] Prepare Debian multiarch environment for $short: $target_arch"
|
||||||
|
|
||||||
|
sudo dpkg --add-architecture "$target_arch" || true
|
||||||
|
|
||||||
|
if [[ "$target_arch" == "loong64" ]]; then
|
||||||
|
echo "[+] Add Loong13 Debian Trixie source for loong64"
|
||||||
|
|
||||||
|
cat <<'EOF' | sudo tee /etc/apt/sources.list.d/loong64-loong13.list >/dev/null
|
||||||
|
deb [arch=loong64] http://loong13.debian.net/debian-loong64/ trixie main contrib non-free non-free-firmware
|
||||||
|
deb [arch=loong64] http://loong13.debian.net/debian-loong64-security/ trixie-security main contrib non-free non-free-firmware
|
||||||
|
EOF
|
||||||
|
|
||||||
|
echo "[+] Install Loong13 archive keyring"
|
||||||
|
|
||||||
|
tmp_keyring="$(mktemp -d)"
|
||||||
|
curl -fL \
|
||||||
|
"http://loong13.debian.net/debian-loong64/pool/main/d/debian-loong64-non-official-archive-keyring/debian-loong64-non-official-archive-keyring_2025.12.22_all.deb" \
|
||||||
|
-o "$tmp_keyring/loong13-keyring.deb"
|
||||||
|
|
||||||
|
sudo dpkg -i "$tmp_keyring/loong13-keyring.deb"
|
||||||
|
rm -rf "$tmp_keyring"
|
||||||
|
fi
|
||||||
|
|
||||||
|
sudo apt-get update
|
||||||
|
|
||||||
|
sudo apt-get -y install \
|
||||||
|
"libc6:${target_arch}" \
|
||||||
|
"libgcc-s1:${target_arch}" \
|
||||||
|
"libstdc++6:${target_arch}" \
|
||||||
|
"zlib1g:${target_arch}" \
|
||||||
|
"libfontconfig1:${target_arch}" \
|
||||||
|
"libfreetype6:${target_arch}"
|
||||||
|
|
||||||
|
echo "[OK] Debian target libraries prepared for $target_arch"
|
||||||
|
}
|
||||||
|
|
||||||
prepare_workspace() {
|
prepare_workspace() {
|
||||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
cd "$SCRIPT_DIR"
|
cd "$SCRIPT_DIR"
|
||||||
@@ -267,14 +366,115 @@ resolve_version() {
|
|||||||
echo "[*] GUI version resolved as: ${VERSION}"
|
echo "[*] GUI version resolved as: ${VERSION}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
download_nuget_packages() {
|
||||||
|
NUGET_CACHE_DIR="$(mktemp -d)"
|
||||||
|
|
||||||
|
local riscv_rt ppc64le_rt loong_rt
|
||||||
|
riscv_rt="$(get_runtime_version "$DOTNET_RISCV_VERSION")"
|
||||||
|
ppc64le_rt="$(get_runtime_version "$DOTNET_PPC64LE_VERSION")"
|
||||||
|
loong_rt="$(get_runtime_version "$DOTNET_LOONGARCH_VERSION")"
|
||||||
|
|
||||||
|
local urls=(
|
||||||
|
"${DOTNET_NUPKG_BASE}/${loong_rt}/Microsoft.AspNetCore.App.Runtime.linux-loongarch64.${loong_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${ppc64le_rt}/Microsoft.AspNetCore.App.Runtime.linux-ppc64le.${ppc64le_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${riscv_rt}/Microsoft.AspNetCore.App.Runtime.linux-riscv64.${riscv_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${loong_rt}/Microsoft.NETCore.App.Host.linux-loongarch64.${loong_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${ppc64le_rt}/Microsoft.NETCore.App.Host.linux-ppc64le.${ppc64le_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${riscv_rt}/Microsoft.NETCore.App.Host.linux-riscv64.${riscv_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${loong_rt}/Microsoft.NETCore.App.Runtime.linux-loongarch64.${loong_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${ppc64le_rt}/Microsoft.NETCore.App.Runtime.linux-ppc64le.${ppc64le_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${riscv_rt}/Microsoft.NETCore.App.Runtime.linux-riscv64.${riscv_rt}.nupkg"
|
||||||
|
"${SKIASHARP_BASE}/v${SkiaSharp_VERSION}/SkiaSharp.NativeAssets.Linux.${SkiaSharp_VERSION}.nupkg"
|
||||||
|
"${SKIASHARP_BASE}/v${SkiaSharp_VERSION}/HarfBuzzSharp.NativeAssets.Linux.${HarfBuzzSharp_VERSION}.nupkg"
|
||||||
|
)
|
||||||
|
|
||||||
|
echo "[+] Downloading prebuilt NuGet packages to: $NUGET_CACHE_DIR"
|
||||||
|
local u pkg_name
|
||||||
|
for u in "${urls[@]}"; do
|
||||||
|
pkg_name="${u##*/}"
|
||||||
|
echo " -> $pkg_name"
|
||||||
|
curl -fL "$u" -o "$NUGET_CACHE_DIR/$pkg_name" || {
|
||||||
|
echo "[!] Failed to download $u" >&2
|
||||||
|
rm -rf "$NUGET_CACHE_DIR"
|
||||||
|
NUGET_CACHE_DIR=""
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "[OK] Prebuilt NuGet packages ready in $NUGET_CACHE_DIR"
|
||||||
|
}
|
||||||
|
|
||||||
|
prepare_dotnet_sdk() {
|
||||||
|
local short="$1"
|
||||||
|
local sdk_url=""
|
||||||
|
local sdk_file=""
|
||||||
|
local sdk_dir=""
|
||||||
|
local tmp=""
|
||||||
|
|
||||||
|
case "$HOST_ARCH:$short" in
|
||||||
|
x86_64:x64|aarch64:arm64)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
riscv64:riscv64)
|
||||||
|
sdk_url="$DOTNET_RISCV_SDK_URL"
|
||||||
|
sdk_file="$DOTNET_RISCV_FILE"
|
||||||
|
;;
|
||||||
|
ppc64le:ppc64le)
|
||||||
|
sdk_url="$DOTNET_PPC64LE_SDK_URL"
|
||||||
|
sdk_file="$DOTNET_PPC64LE_FILE"
|
||||||
|
;;
|
||||||
|
loongarch64:loong64)
|
||||||
|
sdk_url="$DOTNET_LOONGARCH_SDK_URL"
|
||||||
|
sdk_file="$DOTNET_LOONGARCH_FILE"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
sdk_dir="$(mktemp -d)"
|
||||||
|
tmp="$(mktemp -d)"
|
||||||
|
|
||||||
|
echo "[+] Download .NET SDK for $short: $sdk_url"
|
||||||
|
|
||||||
|
curl -fL "$sdk_url" -o "$tmp/$sdk_file" || {
|
||||||
|
rm -rf "$tmp" "$sdk_dir"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
tar -C "$sdk_dir" -xzf "$tmp/$sdk_file" || {
|
||||||
|
rm -rf "$tmp" "$sdk_dir"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
rm -rf "$tmp"
|
||||||
|
|
||||||
|
[[ -x "$sdk_dir/dotnet" ]] || {
|
||||||
|
rm -rf "$sdk_dir"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
export DOTNET_ROOT="$sdk_dir"
|
||||||
|
export PATH="$DOTNET_ROOT:$PATH"
|
||||||
|
hash -r
|
||||||
|
|
||||||
|
echo "[OK] .NET SDK for $short extracted to: $sdk_dir"
|
||||||
|
dotnet --info
|
||||||
|
|
||||||
|
DOTNET_SDK_DIR="$sdk_dir"
|
||||||
|
}
|
||||||
|
|
||||||
xray_url_for_rid() {
|
xray_url_for_rid() {
|
||||||
local rid="$1"
|
local rid="$1"
|
||||||
local ver="$2"
|
local ver="$2"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-x64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-64.zip" ;;
|
linux-x64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-64.zip" ;;
|
||||||
linux-arm64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-arm64-v8a.zip" ;;
|
linux-arm64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-arm64-v8a.zip" ;;
|
||||||
*) return 1 ;;
|
linux-riscv64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-riscv64.zip" ;;
|
||||||
|
linux-ppc64le) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-ppc64le.zip" ;;
|
||||||
|
linux-loongarch64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-loong64.zip" ;;
|
||||||
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,9 +483,12 @@ singbox_url_for_rid() {
|
|||||||
local ver="$2"
|
local ver="$2"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-x64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-amd64.tar.gz" ;;
|
linux-x64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-amd64.tar.gz" ;;
|
||||||
linux-arm64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-arm64.tar.gz" ;;
|
linux-arm64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-arm64.tar.gz" ;;
|
||||||
*) return 1 ;;
|
linux-riscv64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-riscv64.tar.gz" ;;
|
||||||
|
linux-ppc64le) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-ppc64le.tar.gz" ;;
|
||||||
|
linux-loongarch64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-loong64.tar.gz" ;;
|
||||||
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,9 +496,12 @@ bundle_url_for_rid() {
|
|||||||
local rid="$1"
|
local rid="$1"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-x64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-64.zip" ;;
|
linux-x64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-64.zip" ;;
|
||||||
linux-arm64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-arm64.zip" ;;
|
linux-arm64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-arm64.zip" ;;
|
||||||
*) return 1 ;;
|
linux-riscv64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-riscv64.zip" ;;
|
||||||
|
linux-ppc64le) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-ppc64le.zip" ;;
|
||||||
|
linux-loongarch64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-loong64.zip" ;;
|
||||||
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,7 +522,7 @@ download_xray() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
[[ -n "$ver" ]] || { echo "[xray] Failed to get version"; return 1; }
|
[[ -n "$ver" ]] || { echo "[xray] Failed to get version"; return 1; }
|
||||||
url="$(xray_url_for_rid "$rid" "$ver")" || { echo "[xray] Unsupported RID: $rid"; return 1; }
|
url="$(xray_url_for_rid "$rid" "$ver")" || { echo "[xray] Unsupported RID for upstream Xray: $rid (skipped)"; return 0; }
|
||||||
|
|
||||||
echo "[+] Download xray: $url"
|
echo "[+] Download xray: $url"
|
||||||
|
|
||||||
@@ -476,7 +682,7 @@ stage_runtime_assets() {
|
|||||||
|
|
||||||
if [[ "$FORCE_NETCORE" -eq 0 ]]; then
|
if [[ "$FORCE_NETCORE" -eq 0 ]]; then
|
||||||
if populate_assets_zip_mode "$outroot" "$rid"; then
|
if populate_assets_zip_mode "$outroot" "$rid"; then
|
||||||
echo "[*] Using v2rayN bundle bin assets."
|
echo "[*] Using v2rayN bundle archive."
|
||||||
else
|
else
|
||||||
echo "[*] Bundle failed, fallback to separate core + rules."
|
echo "[*] Bundle failed, fallback to separate core + rules."
|
||||||
populate_assets_netcore_mode "$outroot" "$rid"
|
populate_assets_netcore_mode "$outroot" "$rid"
|
||||||
@@ -491,9 +697,12 @@ describe_target() {
|
|||||||
local short="$1"
|
local short="$1"
|
||||||
|
|
||||||
case "$short" in
|
case "$short" in
|
||||||
x64) printf '%s\n%s\n' "linux-x64" "amd64" ;;
|
x64) printf '%s\n%s\n' "linux-x64" "amd64" ;;
|
||||||
arm64) printf '%s\n%s\n' "linux-arm64" "arm64" ;;
|
arm64) printf '%s\n%s\n' "linux-arm64" "arm64" ;;
|
||||||
*) echo "Unknown arch '$short' (use x64|arm64)" >&2; return 1 ;;
|
riscv64) printf '%s\n%s\n' "linux-riscv64" "riscv64" ;;
|
||||||
|
ppc64le) printf '%s\n%s\n' "linux-ppc64le" "ppc64el" ;;
|
||||||
|
loong64) printf '%s\n%s\n' "linux-loongarch64" "loong64" ;;
|
||||||
|
*) echo "Unknown arch '$short' (use x64|arm64|riscv64|ppc64le|loong64)" >&2; return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -502,8 +711,18 @@ publish_binary() {
|
|||||||
|
|
||||||
dotnet clean "$PROJECT" -c Release
|
dotnet clean "$PROJECT" -c Release
|
||||||
rm -rf "$(dirname "$PROJECT")/bin/Release/net10.0" || true
|
rm -rf "$(dirname "$PROJECT")/bin/Release/net10.0" || true
|
||||||
dotnet restore "$PROJECT"
|
dotnet restore "$PROJECT" \
|
||||||
dotnet publish "$PROJECT" -c Release -r "$rid" -p:PublishSingleFile=false -p:SelfContained=true
|
-r "$rid" \
|
||||||
|
--source "$NUGET_CACHE_DIR" \
|
||||||
|
--source "https://api.nuget.org/v3/index.json"
|
||||||
|
dotnet publish "$PROJECT" \
|
||||||
|
-c Release \
|
||||||
|
-r "$rid" \
|
||||||
|
--source "$NUGET_CACHE_DIR" \
|
||||||
|
--source "https://api.nuget.org/v3/index.json" \
|
||||||
|
-p:PublishSingleFile=false \
|
||||||
|
-p:SelfContained=true \
|
||||||
|
--no-restore
|
||||||
}
|
}
|
||||||
|
|
||||||
write_launcher_file() {
|
write_launcher_file() {
|
||||||
@@ -609,7 +828,9 @@ package_binary() {
|
|||||||
write_desktop_file "$stage"
|
write_desktop_file "$stage"
|
||||||
write_maintainer_scripts "$debian_dir"
|
write_maintainer_scripts "$debian_dir"
|
||||||
|
|
||||||
extra_depends="libc6 (>= 2.34), fontconfig (>= 2.13.1), desktop-file-utils (>= 0.26), xdg-utils (>= 1.1.3), coreutils (>= 8.32), bash (>= 5.1), libfreetype6 (>= 2.11)"
|
prepare_deb_target_arch "$short"
|
||||||
|
|
||||||
|
extra_depends="libc6 (>= 2.39), fontconfig (>= 2.15.0), desktop-file-utils (>= 0.26), xdg-utils (>= 1.1.3), coreutils (>= 9.4), bash (>= 5.2.21), libfreetype6 (>= 2.13)"
|
||||||
|
|
||||||
mkdir -p "$workdir/debian"
|
mkdir -p "$workdir/debian"
|
||||||
cat > "$workdir/debian/control" <<EOF
|
cat > "$workdir/debian/control" <<EOF
|
||||||
@@ -643,7 +864,7 @@ EOF
|
|||||||
-l"$sys_usrlibdir" \
|
-l"$sys_usrlibdir" \
|
||||||
-T"$debian_dir/substvars" \
|
-T"$debian_dir/substvars" \
|
||||||
"${ELF_FILES[@]}"
|
"${ELF_FILES[@]}"
|
||||||
) >/dev/null 2>&1 || true
|
) || true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
shlibs_depends="$(sed -n 's/^shlibs:Depends=//p' "$debian_dir/substvars" | head -n1 || true)"
|
shlibs_depends="$(sed -n 's/^shlibs:Depends=//p' "$debian_dir/substvars" | head -n1 || true)"
|
||||||
@@ -686,9 +907,12 @@ EOF
|
|||||||
|
|
||||||
select_targets() {
|
select_targets() {
|
||||||
case "${ARCH_OVERRIDE:-}" in
|
case "${ARCH_OVERRIDE:-}" in
|
||||||
all) printf '%s\n' x64 arm64 ;;
|
all) printf '%s\n' x64 arm64 riscv64 ppc64le loong64 ;;
|
||||||
x64|amd64) printf '%s\n' x64 ;;
|
x64|amd64) printf '%s\n' x64 ;;
|
||||||
arm64|aarch64) printf '%s\n' arm64 ;;
|
arm64|aarch64) printf '%s\n' arm64 ;;
|
||||||
|
riscv64) printf '%s\n' riscv64 ;;
|
||||||
|
ppc64le|ppc64el) printf '%s\n' ppc64le ;;
|
||||||
|
loong64|loongarch64) printf '%s\n' loong64 ;;
|
||||||
"")
|
"")
|
||||||
case "$HOST_ARCH" in
|
case "$HOST_ARCH" in
|
||||||
x86_64) printf '%s\n' x64 ;;
|
x86_64) printf '%s\n' x64 ;;
|
||||||
@@ -697,7 +921,7 @@ select_targets() {
|
|||||||
esac
|
esac
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "Unknown --arch '${ARCH_OVERRIDE}'. Use x64|arm64|all." >&2
|
echo "Unknown --arch '${ARCH_OVERRIDE}'. Use x64|arm64|riscv64|ppc64le|loong64|all." >&2
|
||||||
return 1
|
return 1
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
@@ -714,6 +938,7 @@ build_one_target() {
|
|||||||
deb_arch="${meta[1]}"
|
deb_arch="${meta[1]}"
|
||||||
|
|
||||||
echo "[*] Building for target: $short (RID=$rid, DEB arch=$deb_arch)"
|
echo "[*] Building for target: $short (RID=$rid, DEB arch=$deb_arch)"
|
||||||
|
prepare_dotnet_sdk "$short" || die "Failed to prepare .NET SDK for $short."
|
||||||
publish_binary "$rid"
|
publish_binary "$rid"
|
||||||
package_binary "$short" "$rid" "$deb_arch"
|
package_binary "$short" "$rid" "$deb_arch"
|
||||||
}
|
}
|
||||||
@@ -744,13 +969,19 @@ main() {
|
|||||||
prepare_workspace
|
prepare_workspace
|
||||||
resolve_version
|
resolve_version
|
||||||
|
|
||||||
|
download_nuget_packages || die "Failed to download prebuilt NuGet packages."
|
||||||
|
|
||||||
mapfile -t targets < <(select_targets)
|
mapfile -t targets < <(select_targets)
|
||||||
|
[[ "${ARCH_OVERRIDE:-}" == "all" ]] && BUILT_ALL=1 || BUILT_ALL=0
|
||||||
|
|
||||||
for arch in "${targets[@]}"; do
|
for arch in "${targets[@]}"; do
|
||||||
build_one_target "$arch"
|
build_one_target "$arch"
|
||||||
done
|
done
|
||||||
|
|
||||||
|
rm -rf "${NUGET_CACHE_DIR:-}" || true
|
||||||
|
rm -rf "${DOTNET_SDK_DIR:-}" || true
|
||||||
|
|
||||||
print_summary
|
print_summary
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
+1
-1
@@ -54,7 +54,7 @@ cat >"$PackagePath/v2rayN.app/Contents/Info.plist" <<-EOF
|
|||||||
<key>NSHighResolutionCapable</key>
|
<key>NSHighResolutionCapable</key>
|
||||||
<true/>
|
<true/>
|
||||||
<key>LSMinimumSystemVersion</key>
|
<key>LSMinimumSystemVersion</key>
|
||||||
<string>12.7</string>
|
<string>13.6</string>
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
EOF
|
EOF
|
||||||
|
|||||||
@@ -8,14 +8,19 @@ BUILD_FROM=""
|
|||||||
XRAY_VER="${XRAY_VER:-}"
|
XRAY_VER="${XRAY_VER:-}"
|
||||||
SING_VER="${SING_VER:-}"
|
SING_VER="${SING_VER:-}"
|
||||||
|
|
||||||
MIN_KERNEL="5.10"
|
MIN_KERNEL="6.12"
|
||||||
PKGROOT="v2rayN-publish"
|
PKGROOT="v2rayN-publish"
|
||||||
PROJECT_HINT="v2rayN.Desktop/v2rayN.Desktop.csproj"
|
PROJECT_HINT="v2rayN.Desktop/v2rayN.Desktop.csproj"
|
||||||
RPM_TOPDIR="${HOME}/rpmbuild"
|
RPM_TOPDIR="${HOME}/rpmbuild"
|
||||||
DOTNET_RISCV_VERSION="10.0.108"
|
|
||||||
DOTNET_RISCV_BASE="https://github.com/xujiegb/dotnet-riscv/releases/download"
|
NUGET_CACHE_DIR=""
|
||||||
DOTNET_RISCV_FILE="dotnet-sdk-${DOTNET_RISCV_VERSION}-linux-riscv64.tar.gz"
|
DOTNET_NUPKG_BASE="${DOTNET_NUPKG_BASE:-https://github.com/autorepobot/dotnet-nupkg-prebuild/releases/download}"
|
||||||
DOTNET_SDK_URL="${DOTNET_RISCV_BASE}/${DOTNET_RISCV_VERSION}/${DOTNET_RISCV_FILE}"
|
SKIASHARP_BASE="${SKIASHARP_BASE:-https://github.com/autorepobot/SkiaSharp-ppc64le/releases/download}"
|
||||||
|
SkiaSharp_VERSION="${SkiaSharp_VERSION:-3.119.4}"
|
||||||
|
HarfBuzzSharp_VERSION="${HarfBuzzSharp_VERSION:-8.3.1.5}"
|
||||||
|
|
||||||
|
DOTNET_SDK_VERSION="${DOTNET_SDK_VERSION:-10.0.114}"
|
||||||
|
DOTNET_X86_VERSION="${DOTNET_X86_VERSION:-10.0.114}"
|
||||||
|
|
||||||
OS_ID=""
|
OS_ID=""
|
||||||
OS_NAME=""
|
OS_NAME=""
|
||||||
@@ -24,6 +29,13 @@ HOST_ARCH=""
|
|||||||
SCRIPT_DIR=""
|
SCRIPT_DIR=""
|
||||||
PROJECT=""
|
PROJECT=""
|
||||||
VERSION=""
|
VERSION=""
|
||||||
|
BUILT_ALL=0
|
||||||
|
|
||||||
|
X86_RID="linux-x86"
|
||||||
|
X86_RPM_ARCH="i686"
|
||||||
|
|
||||||
|
RPM_STRIP=""
|
||||||
|
RPM_OBJDUMP=""
|
||||||
|
|
||||||
declare -a BUILT_RPMS=()
|
declare -a BUILT_RPMS=()
|
||||||
|
|
||||||
@@ -32,6 +44,13 @@ die() {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get_runtime_version() {
|
||||||
|
local sdk_ver="$1"
|
||||||
|
local prefix="${sdk_ver%.*}"
|
||||||
|
local patch="${sdk_ver##*.}"
|
||||||
|
echo "${prefix}.${patch#1}"
|
||||||
|
}
|
||||||
|
|
||||||
parse_args() {
|
parse_args() {
|
||||||
local first_arg="${1:-}"
|
local first_arg="${1:-}"
|
||||||
|
|
||||||
@@ -82,8 +101,8 @@ This script only supports: RHEL / Rocky / AlmaLinux / Fedora / CentOS."
|
|||||||
esac
|
esac
|
||||||
|
|
||||||
case "$HOST_ARCH" in
|
case "$HOST_ARCH" in
|
||||||
riscv64) ;;
|
x86_64|aarch64) ;;
|
||||||
*) die "Only supports riscv64" ;;
|
*) die "This script cross-builds linux-x86/i686 from x86_64 or aarch64 only." ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
current_kernel="$(uname -r)"
|
current_kernel="$(uname -r)"
|
||||||
@@ -91,37 +110,68 @@ This script only supports: RHEL / Rocky / AlmaLinux / Fedora / CentOS."
|
|||||||
|
|
||||||
[[ "$lowest" == "$MIN_KERNEL" ]] || die "Kernel $current_kernel is below $MIN_KERNEL"
|
[[ "$lowest" == "$MIN_KERNEL" ]] || die "Kernel $current_kernel is below $MIN_KERNEL"
|
||||||
echo "[OK] Kernel $current_kernel verified."
|
echo "[OK] Kernel $current_kernel verified."
|
||||||
|
echo "[OK] Host architecture: $HOST_ARCH"
|
||||||
|
echo "[OK] Target: $X86_RID (RPM $X86_RPM_ARCH)"
|
||||||
}
|
}
|
||||||
|
|
||||||
install_dependencies() {
|
install_dependencies() {
|
||||||
local install_ok=0
|
local install_ok=0
|
||||||
local tmp_dotnet=""
|
|
||||||
|
|
||||||
if command -v dnf >/dev/null 2>&1; then
|
if command -v dnf >/dev/null 2>&1; then
|
||||||
sudo dnf -y install \
|
sudo dnf -y install \
|
||||||
rpm-build rpmdevtools curl unzip tar jq rsync git python3 \
|
rpm-build rpmdevtools curl unzip tar jq rsync \
|
||||||
glibc-devel kernel-headers libatomic file ca-certificates libicu \
|
python3 binutils wget libicu \
|
||||||
&& install_ok=1
|
&& install_ok=1
|
||||||
|
|
||||||
mkdir -p "$HOME/.dotnet"
|
case "$HOST_ARCH" in
|
||||||
tmp_dotnet="$(mktemp -d)"
|
x86_64|aarch64)
|
||||||
curl -fL "$DOTNET_SDK_URL" -o "$tmp_dotnet/$DOTNET_RISCV_FILE"
|
wget -q https://dot.net/v1/dotnet-install.sh
|
||||||
tar -C "$HOME/.dotnet" -xzf "$tmp_dotnet/$DOTNET_RISCV_FILE"
|
chmod +x dotnet-install.sh
|
||||||
rm -rf "$tmp_dotnet"
|
./dotnet-install.sh --version "$DOTNET_SDK_VERSION" --install-dir "$HOME/.dotnet"
|
||||||
|
|
||||||
export PATH="$HOME/.dotnet:$PATH"
|
export PATH="$HOME/.dotnet:$PATH"
|
||||||
export DOTNET_ROOT="$HOME/.dotnet"
|
export DOTNET_ROOT="$HOME/.dotnet"
|
||||||
|
|
||||||
dotnet --info >/dev/null 2>&1 || install_ok=0
|
dotnet --info >/dev/null 2>&1 && install_ok=1
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
die "This script cross-builds linux-x86/i686 from x86_64 or aarch64 only."
|
||||||
|
;;
|
||||||
|
esac
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "$install_ok" -ne 1 ]]; then
|
if [[ "$install_ok" -ne 1 ]]; then
|
||||||
echo "Could not auto-install dependencies for '$OS_ID'. Make sure these are available:"
|
echo "Could not auto-install dependencies for '$OS_ID'. Make sure these are available:"
|
||||||
echo "dotnet-riscv SDK, curl, unzip, tar, rsync, git, python3, rpm, rpmdevtools, rpm-build (on Red Hat branch)"
|
echo "dotnet 10.x, python3, rpm, rpmdevtools, rpm-build, binutils"
|
||||||
|
echo "curl, unzip, tar, rsync, jq, wget"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
prepare_cross_rpm_tools() {
|
||||||
|
local target="$1"
|
||||||
|
|
||||||
|
case "$HOST_ARCH:$target" in
|
||||||
|
x86_64:i686|aarch64:i686)
|
||||||
|
echo "[+] Prepare host RPM binutils for $target"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
RPM_STRIP=""
|
||||||
|
RPM_OBJDUMP=""
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
command -v strip >/dev/null 2>&1 || die "strip tool not found"
|
||||||
|
command -v objdump >/dev/null 2>&1 || die "objdump tool not found"
|
||||||
|
|
||||||
|
RPM_STRIP="$(command -v strip)"
|
||||||
|
RPM_OBJDUMP="$(command -v objdump)"
|
||||||
|
|
||||||
|
echo "[OK] RPM strip: $RPM_STRIP"
|
||||||
|
echo "[OK] RPM objdump: $RPM_OBJDUMP"
|
||||||
|
}
|
||||||
|
|
||||||
prepare_workspace() {
|
prepare_workspace() {
|
||||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
cd "$SCRIPT_DIR"
|
cd "$SCRIPT_DIR"
|
||||||
@@ -254,13 +304,156 @@ resolve_version() {
|
|||||||
echo "[*] GUI version resolved as: ${VERSION}"
|
echo "[*] GUI version resolved as: ${VERSION}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
download_nuget_packages() {
|
||||||
|
NUGET_CACHE_DIR="$(mktemp -d)"
|
||||||
|
|
||||||
|
local x86_rt
|
||||||
|
x86_rt="$(get_runtime_version "$DOTNET_X86_VERSION")"
|
||||||
|
|
||||||
|
local urls=(
|
||||||
|
"${DOTNET_NUPKG_BASE}/${x86_rt}/Microsoft.AspNetCore.App.Runtime.linux-x86.${x86_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${x86_rt}/Microsoft.NETCore.App.Host.linux-x86.${x86_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${x86_rt}/Microsoft.NETCore.App.Runtime.linux-x86.${x86_rt}.nupkg"
|
||||||
|
"${SKIASHARP_BASE}/v${SkiaSharp_VERSION}/SkiaSharp.NativeAssets.Linux.${SkiaSharp_VERSION}.nupkg"
|
||||||
|
"${SKIASHARP_BASE}/v${SkiaSharp_VERSION}/HarfBuzzSharp.NativeAssets.Linux.${HarfBuzzSharp_VERSION}.nupkg"
|
||||||
|
)
|
||||||
|
|
||||||
|
echo "[+] Downloading prebuilt NuGet packages to: $NUGET_CACHE_DIR"
|
||||||
|
local u pkg_name
|
||||||
|
for u in "${urls[@]}"; do
|
||||||
|
pkg_name="${u##*/}"
|
||||||
|
echo " -> $pkg_name"
|
||||||
|
curl -fL "$u" -o "$NUGET_CACHE_DIR/$pkg_name" || {
|
||||||
|
echo "[!] Failed to download $u" >&2
|
||||||
|
rm -rf "$NUGET_CACHE_DIR"
|
||||||
|
NUGET_CACHE_DIR=""
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "[OK] Prebuilt NuGet packages ready in $NUGET_CACHE_DIR"
|
||||||
|
}
|
||||||
|
|
||||||
|
prepare_dotnet_sdk() {
|
||||||
|
echo "[+] Using host .NET SDK for cross-target $X86_RID"
|
||||||
|
|
||||||
|
dotnet --info
|
||||||
|
|
||||||
|
if [[ -z "${DOTNET_ROOT:-}" ]]; then
|
||||||
|
local dotnet_bin=""
|
||||||
|
dotnet_bin="$(readlink -f "$(command -v dotnet)")"
|
||||||
|
DOTNET_ROOT="$(dirname "$dotnet_bin")"
|
||||||
|
export DOTNET_ROOT
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[OK] DOTNET_ROOT: $DOTNET_ROOT"
|
||||||
|
}
|
||||||
|
|
||||||
|
patch_x86_sdk() {
|
||||||
|
local sdk_props=""
|
||||||
|
local sdk_version=""
|
||||||
|
local dotnet_root=""
|
||||||
|
|
||||||
|
sdk_version="$(dotnet --version)"
|
||||||
|
|
||||||
|
dotnet_root="${DOTNET_ROOT:-}"
|
||||||
|
if [[ -z "$dotnet_root" ]]; then
|
||||||
|
local dotnet_bin=""
|
||||||
|
dotnet_bin="$(readlink -f "$(command -v dotnet)")"
|
||||||
|
dotnet_root="$(dirname "$dotnet_bin")"
|
||||||
|
fi
|
||||||
|
|
||||||
|
sdk_props="$dotnet_root/sdk/${sdk_version}/Microsoft.NETCoreSdk.BundledVersions.props"
|
||||||
|
|
||||||
|
[[ -f "$sdk_props" ]] || die "SDK props file not found: $sdk_props"
|
||||||
|
|
||||||
|
echo "[+] Patching SDK: $sdk_props"
|
||||||
|
|
||||||
|
python3 - "$sdk_props" <<'PY'
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
path = Path(sys.argv[1])
|
||||||
|
text = path.read_text()
|
||||||
|
old = text
|
||||||
|
|
||||||
|
|
||||||
|
def add_attr_to_known_blocks(text, marker, attr):
|
||||||
|
start = 0
|
||||||
|
while True:
|
||||||
|
start = text.find(marker, start)
|
||||||
|
if start == -1:
|
||||||
|
break
|
||||||
|
|
||||||
|
end = text.find('/>', start)
|
||||||
|
if end == -1:
|
||||||
|
break
|
||||||
|
|
||||||
|
block = text[start:end]
|
||||||
|
attr_pos = block.find(attr)
|
||||||
|
|
||||||
|
if attr_pos != -1:
|
||||||
|
value_start = attr_pos + len(attr)
|
||||||
|
value_end = block.find('"', value_start)
|
||||||
|
|
||||||
|
if value_end != -1:
|
||||||
|
value = block[value_start:value_end]
|
||||||
|
values = value.split(';')
|
||||||
|
|
||||||
|
if 'linux-x86' not in values:
|
||||||
|
value = value + ';linux-x86'
|
||||||
|
block = (
|
||||||
|
block[:value_start]
|
||||||
|
+ value
|
||||||
|
+ block[value_end:]
|
||||||
|
)
|
||||||
|
text = text[:start] + block + text[end:]
|
||||||
|
end = start + len(block)
|
||||||
|
|
||||||
|
start = end + 2
|
||||||
|
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
for framework in ('Microsoft.NETCore.App', 'Microsoft.AspNetCore.App'):
|
||||||
|
text = add_attr_to_known_blocks(
|
||||||
|
text,
|
||||||
|
f'<KnownFrameworkReference Include="{framework}"',
|
||||||
|
'RuntimePackRuntimeIdentifiers="',
|
||||||
|
)
|
||||||
|
|
||||||
|
text = add_attr_to_known_blocks(
|
||||||
|
text,
|
||||||
|
'<KnownAppHostPack',
|
||||||
|
'AppHostRuntimeIdentifiers="',
|
||||||
|
)
|
||||||
|
|
||||||
|
if text == old:
|
||||||
|
raise SystemExit(
|
||||||
|
'ERROR: No SDK RuntimePack/AppHost mapping was patched'
|
||||||
|
)
|
||||||
|
|
||||||
|
path.write_text(text)
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "===== Verify RuntimePackRuntimeIdentifiers ====="
|
||||||
|
grep -n 'RuntimePackRuntimeIdentifiers=' "$sdk_props" | grep 'linux-x86'
|
||||||
|
|
||||||
|
echo "===== Verify AppHostRuntimeIdentifiers ====="
|
||||||
|
grep -n 'AppHostRuntimeIdentifiers=' "$sdk_props" | grep 'linux-x86'
|
||||||
|
}
|
||||||
|
|
||||||
xray_url_for_rid() {
|
xray_url_for_rid() {
|
||||||
local rid="$1"
|
local rid="$1"
|
||||||
local ver="$2"
|
local ver="$2"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-riscv64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-riscv64.zip" ;;
|
linux-x86)
|
||||||
*) return 1 ;;
|
echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-32.zip"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
return 1
|
||||||
|
;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -269,8 +462,12 @@ singbox_url_for_rid() {
|
|||||||
local ver="$2"
|
local ver="$2"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-riscv64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-riscv64.tar.gz" ;;
|
linux-x86)
|
||||||
*) return 1 ;;
|
echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-386.tar.gz"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
return 1
|
||||||
|
;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,8 +475,12 @@ bundle_url_for_rid() {
|
|||||||
local rid="$1"
|
local rid="$1"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-riscv64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-riscv64.zip" ;;
|
linux-x86)
|
||||||
*) return 1 ;;
|
echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-86.zip"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
return 1
|
||||||
|
;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,15 +500,34 @@ download_xray() {
|
|||||||
| head -n1)" || true
|
| head -n1)" || true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
[[ -n "$ver" ]] || { echo "[xray] Failed to get version"; return 1; }
|
[[ -n "$ver" ]] || {
|
||||||
url="$(xray_url_for_rid "$rid" "$ver")" || { echo "[xray] Unsupported RID: $rid"; return 1; }
|
echo "[xray] Failed to get version"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
url="$(xray_url_for_rid "$rid" "$ver")" || {
|
||||||
|
echo "[xray] Unsupported RID for upstream Xray: $rid (skipped)"
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
echo "[+] Download xray: $url"
|
echo "[+] Download xray: $url"
|
||||||
|
|
||||||
tmp="$(mktemp -d)"
|
tmp="$(mktemp -d)"
|
||||||
curl -fL "$url" -o "$tmp/xray.zip" || { rm -rf "$tmp"; return 1; }
|
curl -fL "$url" -o "$tmp/xray.zip" || {
|
||||||
unzip -q "$tmp/xray.zip" -d "$tmp" || { rm -rf "$tmp"; return 1; }
|
rm -rf "$tmp"
|
||||||
install -m 755 "$tmp/xray" "$outdir/xray" || { rm -rf "$tmp"; return 1; }
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
unzip -q "$tmp/xray.zip" -d "$tmp" || {
|
||||||
|
rm -rf "$tmp"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
install -m 755 "$tmp/xray" "$outdir/xray" || {
|
||||||
|
rm -rf "$tmp"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
rm -rf "$tmp"
|
rm -rf "$tmp"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,19 +549,40 @@ download_singbox() {
|
|||||||
| head -n1)" || true
|
| head -n1)" || true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
[[ -n "$ver" ]] || { echo "[sing-box] Failed to get version"; return 1; }
|
[[ -n "$ver" ]] || {
|
||||||
url="$(singbox_url_for_rid "$rid" "$ver")" || { echo "[sing-box] Unsupported RID: $rid"; return 1; }
|
echo "[sing-box] Failed to get version"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
url="$(singbox_url_for_rid "$rid" "$ver")" || {
|
||||||
|
echo "[sing-box] Unsupported RID: $rid"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
echo "[+] Download sing-box: $url"
|
echo "[+] Download sing-box: $url"
|
||||||
|
|
||||||
tmp="$(mktemp -d)"
|
tmp="$(mktemp -d)"
|
||||||
curl -fL "$url" -o "$tmp/singbox.tar.gz" || { rm -rf "$tmp"; return 1; }
|
curl -fL "$url" -o "$tmp/singbox.tar.gz" || {
|
||||||
tar -C "$tmp" -xzf "$tmp/singbox.tar.gz" || { rm -rf "$tmp"; return 1; }
|
rm -rf "$tmp"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
tar -C "$tmp" -xzf "$tmp/singbox.tar.gz" || {
|
||||||
|
rm -rf "$tmp"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
bin="$(find "$tmp" -type f -name 'sing-box' | head -n1 || true)"
|
bin="$(find "$tmp" -type f -name 'sing-box' | head -n1 || true)"
|
||||||
[[ -n "$bin" ]] || { echo "[!] sing-box unpack failed"; rm -rf "$tmp"; return 1; }
|
[[ -n "$bin" ]] || {
|
||||||
|
echo "[!] sing-box unpack failed"
|
||||||
|
rm -rf "$tmp"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
install -m 755 "$bin" "$outdir/sing-box" || { rm -rf "$tmp"; return 1; }
|
install -m 755 "$bin" "$outdir/sing-box" || {
|
||||||
|
rm -rf "$tmp"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
cronet="$(find "$tmp" -type f -name 'libcronet*.so*' | head -n1 || true)"
|
cronet="$(find "$tmp" -type f -name 'libcronet*.so*' | head -n1 || true)"
|
||||||
[[ -n "$cronet" ]] && install -m 644 "$cronet" "$outdir/libcronet.so" || true
|
[[ -n "$cronet" ]] && install -m 644 "$cronet" "$outdir/libcronet.so" || true
|
||||||
@@ -378,20 +619,44 @@ download_geo_assets() {
|
|||||||
mkdir -p "$bin_dir" "$srss_dir"
|
mkdir -p "$bin_dir" "$srss_dir"
|
||||||
|
|
||||||
echo "[+] Download Xray Geo to ${bin_dir}"
|
echo "[+] Download Xray Geo to ${bin_dir}"
|
||||||
curl -fsSL -o "$bin_dir/geosite.dat" "https://github.com/Loyalsoldier/V2ray-rules-dat/releases/latest/download/geosite.dat"
|
curl -fsSL -o "$bin_dir/geosite.dat" \
|
||||||
curl -fsSL -o "$bin_dir/geoip.dat" "https://github.com/Loyalsoldier/V2ray-rules-dat/releases/latest/download/geoip.dat"
|
"https://github.com/Loyalsoldier/V2ray-rules-dat/releases/latest/download/geosite.dat"
|
||||||
curl -fsSL -o "$bin_dir/geoip-only-cn-private.dat" "https://raw.githubusercontent.com/Loyalsoldier/geoip/release/geoip-only-cn-private.dat"
|
curl -fsSL -o "$bin_dir/geoip.dat" \
|
||||||
curl -fsSL -o "$bin_dir/Country.mmdb" "https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb"
|
"https://github.com/Loyalsoldier/V2ray-rules-dat/releases/latest/download/geoip.dat"
|
||||||
|
curl -fsSL -o "$bin_dir/geoip-only-cn-private.dat" \
|
||||||
|
"https://raw.githubusercontent.com/Loyalsoldier/geoip/release/geoip-only-cn-private.dat"
|
||||||
|
curl -fsSL -o "$bin_dir/Country.mmdb" \
|
||||||
|
"https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb"
|
||||||
|
|
||||||
echo "[+] Download sing-box rule DB & rule-sets"
|
echo "[+] Download sing-box rule DB & rule-sets"
|
||||||
curl -fsSL -o "$bin_dir/geoip.metadb" "https://github.com/MetaCubeX/meta-rules-dat/releases/latest/download/geoip.metadb"
|
curl -fsSL -o "$bin_dir/geoip.metadb" \
|
||||||
|
"https://github.com/MetaCubeX/meta-rules-dat/releases/latest/download/geoip.metadb"
|
||||||
|
|
||||||
for f in geoip-private.srs geoip-cn.srs geoip-facebook.srs geoip-fastly.srs geoip-google.srs geoip-netflix.srs geoip-telegram.srs geoip-twitter.srs; do
|
for f in \
|
||||||
curl -fsSL -o "$srss_dir/$f" "https://raw.githubusercontent.com/2dust/sing-box-rules/refs/heads/rule-set-geoip/$f"
|
geoip-private.srs \
|
||||||
|
geoip-cn.srs \
|
||||||
|
geoip-facebook.srs \
|
||||||
|
geoip-fastly.srs \
|
||||||
|
geoip-google.srs \
|
||||||
|
geoip-netflix.srs \
|
||||||
|
geoip-telegram.srs \
|
||||||
|
geoip-twitter.srs
|
||||||
|
do
|
||||||
|
curl -fsSL -o "$srss_dir/$f" \
|
||||||
|
"https://raw.githubusercontent.com/2dust/sing-box-rules/refs/heads/rule-set-geoip/$f"
|
||||||
done
|
done
|
||||||
|
|
||||||
for f in geosite-cn.srs geosite-gfw.srs geosite-google.srs geosite-greatfire.srs geosite-geolocation-cn.srs geosite-category-ads-all.srs geosite-private.srs; do
|
for f in \
|
||||||
curl -fsSL -o "$srss_dir/$f" "https://raw.githubusercontent.com/2dust/sing-box-rules/refs/heads/rule-set-geosite/$f"
|
geosite-cn.srs \
|
||||||
|
geosite-gfw.srs \
|
||||||
|
geosite-google.srs \
|
||||||
|
geosite-greatfire.srs \
|
||||||
|
geosite-geolocation-cn.srs \
|
||||||
|
geosite-category-ads-all.srs \
|
||||||
|
geosite-private.srs
|
||||||
|
do
|
||||||
|
curl -fsSL -o "$srss_dir/$f" \
|
||||||
|
"https://raw.githubusercontent.com/2dust/sing-box-rules/refs/heads/rule-set-geosite/$f"
|
||||||
done
|
done
|
||||||
|
|
||||||
unify_geo_layout "$outroot"
|
unify_geo_layout "$outroot"
|
||||||
@@ -404,13 +669,26 @@ populate_assets_zip_mode() {
|
|||||||
local tmp=""
|
local tmp=""
|
||||||
local nested_dir=""
|
local nested_dir=""
|
||||||
|
|
||||||
url="$(bundle_url_for_rid "$rid")" || { echo "[!] Bundle unsupported RID: $rid"; return 1; }
|
url="$(bundle_url_for_rid "$rid")" || {
|
||||||
|
echo "[!] Bundle unsupported RID: $rid"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
echo "[+] Try v2rayN bundle archive: $url"
|
echo "[+] Try v2rayN bundle archive: $url"
|
||||||
|
|
||||||
tmp="$(mktemp -d)"
|
tmp="$(mktemp -d)"
|
||||||
curl -fL "$url" -o "$tmp/v2rayn.zip" || { echo "[!] Bundle download failed"; rm -rf "$tmp"; return 1; }
|
|
||||||
unzip -q "$tmp/v2rayn.zip" -d "$tmp" || { echo "[!] Bundle unzip failed"; rm -rf "$tmp"; return 1; }
|
curl -fL "$url" -o "$tmp/v2rayn.zip" || {
|
||||||
|
echo "[!] Bundle download failed"
|
||||||
|
rm -rf "$tmp"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
unzip -q "$tmp/v2rayn.zip" -d "$tmp" || {
|
||||||
|
echo "[!] Bundle unzip failed"
|
||||||
|
rm -rf "$tmp"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
if [[ -d "$tmp/bin" ]]; then
|
if [[ -d "$tmp/bin" ]]; then
|
||||||
mkdir -p "$outroot/bin"
|
mkdir -p "$outroot/bin"
|
||||||
@@ -423,6 +701,7 @@ populate_assets_zip_mode() {
|
|||||||
find "$outroot" -type d -name "mihomo" -prune -exec rm -rf {} + 2>/dev/null || true
|
find "$outroot" -type d -name "mihomo" -prune -exec rm -rf {} + 2>/dev/null || true
|
||||||
|
|
||||||
nested_dir="$(find "$outroot" -maxdepth 1 -type d -name 'v2rayN-linux-*' | head -n1 || true)"
|
nested_dir="$(find "$outroot" -maxdepth 1 -type d -name 'v2rayN-linux-*' | head -n1 || true)"
|
||||||
|
|
||||||
if [[ -n "$nested_dir" && -d "$nested_dir/bin" ]]; then
|
if [[ -n "$nested_dir" && -d "$nested_dir/bin" ]]; then
|
||||||
mkdir -p "$outroot/bin"
|
mkdir -p "$outroot/bin"
|
||||||
rsync -a "$nested_dir/bin/" "$outroot/bin/"
|
rsync -a "$nested_dir/bin/" "$outroot/bin/"
|
||||||
@@ -442,14 +721,17 @@ populate_assets_netcore_mode() {
|
|||||||
mkdir -p "$outroot/bin/xray" "$outroot/bin/sing_box"
|
mkdir -p "$outroot/bin/xray" "$outroot/bin/sing_box"
|
||||||
|
|
||||||
if [[ "$WITH_CORE" == "xray" || "$WITH_CORE" == "both" ]]; then
|
if [[ "$WITH_CORE" == "xray" || "$WITH_CORE" == "both" ]]; then
|
||||||
download_xray "$outroot/bin/xray" "$rid" || echo "[!] xray download failed (skipped)"
|
download_xray "$outroot/bin/xray" "$rid" \
|
||||||
|
|| echo "[!] xray download failed (skipped)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "$WITH_CORE" == "sing-box" || "$WITH_CORE" == "both" ]]; then
|
if [[ "$WITH_CORE" == "sing-box" || "$WITH_CORE" == "both" ]]; then
|
||||||
download_singbox "$outroot/bin/sing_box" "$rid" || echo "[!] sing-box download failed (skipped)"
|
download_singbox "$outroot/bin/sing_box" "$rid" \
|
||||||
|
|| echo "[!] sing-box download failed (skipped)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
download_geo_assets "$outroot" || echo "[!] Geo rules download failed (skipped)"
|
download_geo_assets "$outroot" \
|
||||||
|
|| echo "[!] Geo rules download failed (skipped)"
|
||||||
}
|
}
|
||||||
|
|
||||||
stage_runtime_assets() {
|
stage_runtime_assets() {
|
||||||
@@ -472,21 +754,36 @@ stage_runtime_assets() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe_target() {
|
describe_target() {
|
||||||
local short="$1"
|
printf '%s\n%s\n%s\n' \
|
||||||
|
"$X86_RID" \
|
||||||
case "$short" in
|
"$X86_RPM_ARCH" \
|
||||||
riscv64) printf '%s\n%s\n%s\n' "linux-riscv64" "riscv64" "riscv64" ;;
|
"$X86_RPM_ARCH"
|
||||||
*) echo "Unknown arch '$short' (use riscv64)" >&2; return 1 ;;
|
|
||||||
esac
|
|
||||||
}
|
}
|
||||||
|
|
||||||
publish_binary() {
|
publish_binary() {
|
||||||
local rid="$1"
|
local rid="$1"
|
||||||
|
|
||||||
|
patch_x86_sdk
|
||||||
|
|
||||||
dotnet clean "$PROJECT" -c Release
|
dotnet clean "$PROJECT" -c Release
|
||||||
rm -rf "$(dirname "$PROJECT")/bin/Release/net10.0" || true
|
rm -rf "$(dirname "$PROJECT")/bin/Release/net10.0" || true
|
||||||
dotnet restore "$PROJECT"
|
|
||||||
dotnet publish "$PROJECT" -c Release -r "$rid" -p:PublishSingleFile=false -p:SelfContained=true
|
dotnet restore "$PROJECT" \
|
||||||
|
-r "$rid" \
|
||||||
|
--source "$NUGET_CACHE_DIR" \
|
||||||
|
--source "https://api.nuget.org/v3/index.json" \
|
||||||
|
-p:SelfContained=true \
|
||||||
|
-p:EnableWindowsTargeting=true \
|
||||||
|
--force-evaluate
|
||||||
|
|
||||||
|
dotnet publish "$PROJECT" \
|
||||||
|
-c Release \
|
||||||
|
-r "$rid" \
|
||||||
|
--source "$NUGET_CACHE_DIR" \
|
||||||
|
--source "https://api.nuget.org/v3/index.json" \
|
||||||
|
-p:PublishSingleFile=false \
|
||||||
|
-p:SelfContained=true \
|
||||||
|
--no-restore
|
||||||
}
|
}
|
||||||
|
|
||||||
write_spec_file() {
|
write_spec_file() {
|
||||||
@@ -501,21 +798,21 @@ write_spec_file() {
|
|||||||
Name: v2rayN
|
Name: v2rayN
|
||||||
Version: __VERSION__
|
Version: __VERSION__
|
||||||
Release: 1%{?dist}
|
Release: 1%{?dist}
|
||||||
Summary: v2rayN (Avalonia) GUI client for Linux (riscv64)
|
Summary: v2rayN (Avalonia) GUI client for Linux
|
||||||
License: GPL-3.0-only
|
License: GPL-3.0-only
|
||||||
URL: https://github.com/2dust/v2rayN
|
URL: https://github.com/2dust/v2rayN
|
||||||
BugURL: https://github.com/2dust/v2rayN/issues
|
BugURL: https://github.com/2dust/v2rayN/issues
|
||||||
ExclusiveArch: riscv64
|
ExclusiveArch: i686
|
||||||
Source0: __PKGROOT__.tar.gz
|
Source0: __PKGROOT__.tar.gz
|
||||||
|
|
||||||
Requires: cairo, pango, openssl, mesa-libEGL, mesa-libGL
|
Requires: cairo, pango, openssl, mesa-libEGL, mesa-libGL
|
||||||
Requires: glibc >= 2.34
|
Requires: glibc >= 2.39
|
||||||
Requires: fontconfig >= 2.13.1
|
Requires: fontconfig >= 2.15.0
|
||||||
Requires: desktop-file-utils >= 0.26
|
Requires: desktop-file-utils >= 0.26
|
||||||
Requires: xdg-utils >= 1.1.3
|
Requires: xdg-utils >= 1.1.3
|
||||||
Requires: coreutils >= 8.32
|
Requires: coreutils >= 9.4
|
||||||
Requires: bash >= 5.1
|
Requires: bash >= 5.2.21
|
||||||
Requires: freetype >= 2.10
|
Requires: freetype >= 2.13
|
||||||
|
|
||||||
%description
|
%description
|
||||||
v2rayN Linux for Red Hat Enterprise Linux
|
v2rayN Linux for Red Hat Enterprise Linux
|
||||||
@@ -603,7 +900,10 @@ package_binary() {
|
|||||||
local f=""
|
local f=""
|
||||||
|
|
||||||
pubdir="$(dirname "$PROJECT")/bin/Release/net10.0/${rid}/publish"
|
pubdir="$(dirname "$PROJECT")/bin/Release/net10.0/${rid}/publish"
|
||||||
[[ -d "$pubdir" ]] || { echo "Publish directory not found: $pubdir"; return 1; }
|
[[ -d "$pubdir" ]] || {
|
||||||
|
echo "Publish directory not found: $pubdir"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
workdir="$(mktemp -d)"
|
workdir="$(mktemp -d)"
|
||||||
trap '[[ -n "${workdir:-}" ]] && rm -rf "$workdir"' RETURN
|
trap '[[ -n "${workdir:-}" ]] && rm -rf "$workdir"' RETURN
|
||||||
@@ -613,23 +913,41 @@ package_binary() {
|
|||||||
|
|
||||||
project_dir="$(cd "$(dirname "$PROJECT")" && pwd)"
|
project_dir="$(cd "$(dirname "$PROJECT")" && pwd)"
|
||||||
icon_candidate="$project_dir/v2rayN.png"
|
icon_candidate="$project_dir/v2rayN.png"
|
||||||
[[ -f "$icon_candidate" ]] || { echo "Required icon not found: $icon_candidate"; return 1; }
|
|
||||||
|
[[ -f "$icon_candidate" ]] || {
|
||||||
|
echo "Required icon not found: $icon_candidate"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
cp "$icon_candidate" "$workdir/$PKGROOT/v2rayn.png"
|
cp "$icon_candidate" "$workdir/$PKGROOT/v2rayn.png"
|
||||||
|
|
||||||
stage_runtime_assets "$workdir/$PKGROOT" "$rid"
|
stage_runtime_assets "$workdir/$PKGROOT" "$rid"
|
||||||
|
|
||||||
rpmdev-setuptree
|
rpmdev-setuptree
|
||||||
|
|
||||||
sourcedir="${RPM_TOPDIR}/SOURCES"
|
sourcedir="${RPM_TOPDIR}/SOURCES"
|
||||||
specdir="${RPM_TOPDIR}/SPECS"
|
specdir="${RPM_TOPDIR}/SPECS"
|
||||||
specfile="${specdir}/v2rayN.spec"
|
specfile="${specdir}/v2rayN.spec"
|
||||||
|
|
||||||
mkdir -p "$sourcedir" "$specdir"
|
mkdir -p "$sourcedir" "$specdir"
|
||||||
tar -C "$workdir" -czf "$sourcedir/$PKGROOT.tar.gz" "$PKGROOT"
|
|
||||||
|
tar -C "$workdir" \
|
||||||
|
-czf "$sourcedir/$PKGROOT.tar.gz" \
|
||||||
|
"$PKGROOT"
|
||||||
|
|
||||||
write_spec_file "$specfile"
|
write_spec_file "$specfile"
|
||||||
rpmbuild -ba "$specfile" --target "$rpm_target"
|
|
||||||
|
if [[ -n "${RPM_STRIP:-}" ]]; then
|
||||||
|
rpmbuild -ba "$specfile" \
|
||||||
|
--target "$rpm_target" \
|
||||||
|
--define "__strip ${RPM_STRIP}" \
|
||||||
|
--define "__objdump ${RPM_OBJDUMP}"
|
||||||
|
else
|
||||||
|
rpmbuild -ba "$specfile" --target "$rpm_target"
|
||||||
|
fi
|
||||||
|
|
||||||
echo "Build done for $short. RPM at:"
|
echo "Build done for $short. RPM at:"
|
||||||
|
|
||||||
for f in "${RPM_TOPDIR}/RPMS/${archdir}/v2rayN-${VERSION}-1"*.rpm; do
|
for f in "${RPM_TOPDIR}/RPMS/${archdir}/v2rayN-${VERSION}-1"*.rpm; do
|
||||||
[[ -e "$f" ]] || continue
|
[[ -e "$f" ]] || continue
|
||||||
echo " $f"
|
echo " $f"
|
||||||
@@ -637,23 +955,16 @@ package_binary() {
|
|||||||
done
|
done
|
||||||
}
|
}
|
||||||
|
|
||||||
select_targets() {
|
|
||||||
printf '%s\n' riscv64
|
|
||||||
}
|
|
||||||
|
|
||||||
build_one_target() {
|
build_one_target() {
|
||||||
local short="$1"
|
local short="i686"
|
||||||
local meta=()
|
local rid="$X86_RID"
|
||||||
local rid=""
|
local rpm_target="$X86_RPM_ARCH"
|
||||||
local rpm_target=""
|
local archdir="$X86_RPM_ARCH"
|
||||||
local archdir=""
|
|
||||||
|
|
||||||
mapfile -t meta < <(describe_target "$short") || return 1
|
|
||||||
rid="${meta[0]}"
|
|
||||||
rpm_target="${meta[1]}"
|
|
||||||
archdir="${meta[2]}"
|
|
||||||
|
|
||||||
echo "[*] Building for target: $short (RID=$rid, RPM --target $rpm_target)"
|
echo "[*] Building for target: $short (RID=$rid, RPM --target $rpm_target)"
|
||||||
|
|
||||||
|
prepare_cross_rpm_tools "$short"
|
||||||
|
prepare_dotnet_sdk
|
||||||
publish_binary "$rid"
|
publish_binary "$rid"
|
||||||
package_binary "$short" "$rid" "$rpm_target" "$archdir"
|
package_binary "$short" "$rid" "$rpm_target" "$archdir"
|
||||||
}
|
}
|
||||||
@@ -662,32 +973,31 @@ print_summary() {
|
|||||||
local rp=""
|
local rp=""
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "================ Build Summary ================"
|
echo "================ Build Summary ================="
|
||||||
if [[ "${#BUILT_RPMS[@]}" -gt 0 ]]; then
|
if [[ "${#BUILT_RPMS[@]}" -gt 0 ]]; then
|
||||||
|
echo "Output directory: ${RPM_TOPDIR}"
|
||||||
for rp in "${BUILT_RPMS[@]}"; do
|
for rp in "${BUILT_RPMS[@]}"; do
|
||||||
echo "$rp"
|
echo "$rp"
|
||||||
done
|
done
|
||||||
else
|
else
|
||||||
echo "No RPMs detected in summary (check build logs above)."
|
echo "No RPMs detected in summary (check build logs above)."
|
||||||
fi
|
fi
|
||||||
echo "=============================================="
|
echo "==============================================="
|
||||||
}
|
}
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
local targets=()
|
|
||||||
local arch=""
|
|
||||||
|
|
||||||
parse_args "$@"
|
parse_args "$@"
|
||||||
detect_environment
|
detect_environment
|
||||||
install_dependencies
|
install_dependencies
|
||||||
prepare_workspace
|
prepare_workspace
|
||||||
resolve_version
|
resolve_version
|
||||||
|
|
||||||
mapfile -t targets < <(select_targets)
|
download_nuget_packages || die \
|
||||||
|
"Failed to download prebuilt NuGet packages."
|
||||||
|
|
||||||
for arch in "${targets[@]}"; do
|
build_one_target
|
||||||
build_one_target "$arch"
|
|
||||||
done
|
rm -rf "${NUGET_CACHE_DIR:-}" || true
|
||||||
|
|
||||||
print_summary
|
print_summary
|
||||||
}
|
}
|
||||||
Regular → Executable
+269
-32
@@ -14,6 +14,30 @@ PKGROOT="v2rayN-publish"
|
|||||||
PROJECT_HINT="v2rayN.Desktop/v2rayN.Desktop.csproj"
|
PROJECT_HINT="v2rayN.Desktop/v2rayN.Desktop.csproj"
|
||||||
RPM_TOPDIR="${HOME}/rpmbuild"
|
RPM_TOPDIR="${HOME}/rpmbuild"
|
||||||
|
|
||||||
|
NUGET_CACHE_DIR=""
|
||||||
|
DOTNET_NUPKG_BASE="${DOTNET_NUPKG_BASE:-https://github.com/autorepobot/dotnet-nupkg-prebuild/releases/download}"
|
||||||
|
SKIASHARP_BASE="${SKIASHARP_BASE:-https://github.com/autorepobot/SkiaSharp-ppc64le/releases/download}"
|
||||||
|
SkiaSharp_VERSION="${SkiaSharp_VERSION:-3.119.4}"
|
||||||
|
HarfBuzzSharp_VERSION="${HarfBuzzSharp_VERSION:-8.3.1.5}"
|
||||||
|
|
||||||
|
DOTNET_SDK_VERSION="${DOTNET_SDK_VERSION:-10.0.114}"
|
||||||
|
|
||||||
|
DOTNET_RISCV_VERSION="${DOTNET_RISCV_VERSION:-10.0.114}"
|
||||||
|
DOTNET_RISCV_BASE="${DOTNET_RISCV_BASE:-https://github.com/autorepobot/dotnet-riscv/releases/download}"
|
||||||
|
DOTNET_RISCV_FILE="dotnet-sdk-${DOTNET_RISCV_VERSION}-linux-riscv64.tar.gz"
|
||||||
|
DOTNET_RISCV_SDK_URL="${DOTNET_RISCV_SDK_URL:-${DOTNET_RISCV_BASE}/${DOTNET_RISCV_VERSION}/${DOTNET_RISCV_FILE}}"
|
||||||
|
|
||||||
|
DOTNET_PPC64LE_VERSION="${DOTNET_PPC64LE_VERSION:-10.0.114}"
|
||||||
|
DOTNET_PPC64LE_BASE="${DOTNET_PPC64LE_BASE:-https://github.com/IBM/dotnet-s390x/releases/download}"
|
||||||
|
DOTNET_PPC64LE_FILE="dotnet-sdk-${DOTNET_PPC64LE_VERSION}-linux-ppc64le.tar.gz"
|
||||||
|
DOTNET_PPC64LE_SDK_URL="${DOTNET_PPC64LE_SDK_URL:-${DOTNET_PPC64LE_BASE}/v${DOTNET_PPC64LE_VERSION}/${DOTNET_PPC64LE_FILE}}"
|
||||||
|
|
||||||
|
DOTNET_LOONGARCH_VERSION="${DOTNET_LOONGARCH_VERSION:-10.0.114}"
|
||||||
|
DOTNET_LOONGARCH_TAG="${DOTNET_LOONGARCH_TAG:-v10.0.114-loongarch64}"
|
||||||
|
DOTNET_LOONGARCH_BASE="${DOTNET_LOONGARCH_BASE:-https://github.com/loongson/dotnet/releases/download}"
|
||||||
|
DOTNET_LOONGARCH_FILE="dotnet-sdk-${DOTNET_LOONGARCH_VERSION}-linux-loongarch64.tar.gz"
|
||||||
|
DOTNET_LOONGARCH_SDK_URL="${DOTNET_LOONGARCH_SDK_URL:-${DOTNET_LOONGARCH_BASE}/${DOTNET_LOONGARCH_TAG}/${DOTNET_LOONGARCH_FILE}}"
|
||||||
|
|
||||||
OS_ID=""
|
OS_ID=""
|
||||||
OS_NAME=""
|
OS_NAME=""
|
||||||
OS_VERSION_ID=""
|
OS_VERSION_ID=""
|
||||||
@@ -23,6 +47,9 @@ PROJECT=""
|
|||||||
VERSION=""
|
VERSION=""
|
||||||
BUILT_ALL=0
|
BUILT_ALL=0
|
||||||
|
|
||||||
|
RPM_STRIP=""
|
||||||
|
RPM_OBJDUMP=""
|
||||||
|
|
||||||
declare -a BUILT_RPMS=()
|
declare -a BUILT_RPMS=()
|
||||||
|
|
||||||
die() {
|
die() {
|
||||||
@@ -30,6 +57,13 @@ die() {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get_runtime_version() {
|
||||||
|
local sdk_ver="$1"
|
||||||
|
local prefix="${sdk_ver%.*}"
|
||||||
|
local patch="${sdk_ver##*.}"
|
||||||
|
echo "${prefix}.${patch#1}"
|
||||||
|
}
|
||||||
|
|
||||||
parse_args() {
|
parse_args() {
|
||||||
local first_arg="${1:-}"
|
local first_arg="${1:-}"
|
||||||
|
|
||||||
@@ -81,8 +115,8 @@ This script only supports: RHEL / Rocky / AlmaLinux / Fedora / CentOS."
|
|||||||
esac
|
esac
|
||||||
|
|
||||||
case "$HOST_ARCH" in
|
case "$HOST_ARCH" in
|
||||||
x86_64|aarch64) ;;
|
x86_64|aarch64|riscv64|ppc64le|loongarch64) ;;
|
||||||
*) die "Only supports aarch64 / x86_64" ;;
|
*) die "Only supports x86_64 / aarch64 / riscv64 / ppc64le / loongarch64" ;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
current_kernel="$(uname -r)"
|
current_kernel="$(uname -r)"
|
||||||
@@ -96,8 +130,31 @@ install_dependencies() {
|
|||||||
local install_ok=0
|
local install_ok=0
|
||||||
|
|
||||||
if command -v dnf >/dev/null 2>&1; then
|
if command -v dnf >/dev/null 2>&1; then
|
||||||
sudo dnf -y install rpm-build rpmdevtools curl unzip tar jq rsync dotnet-sdk-10.0 \
|
sudo dnf -y install \
|
||||||
|
rpm-build rpmdevtools curl unzip tar jq rsync ca-certificates git \
|
||||||
|
desktop-file-utils wget libicu \
|
||||||
&& install_ok=1
|
&& install_ok=1
|
||||||
|
|
||||||
|
case "$HOST_ARCH" in
|
||||||
|
x86_64|aarch64)
|
||||||
|
wget -q https://dot.net/v1/dotnet-install.sh
|
||||||
|
chmod +x dotnet-install.sh
|
||||||
|
./dotnet-install.sh \
|
||||||
|
--version "$DOTNET_SDK_VERSION" \
|
||||||
|
--install-dir "$HOME/.dotnet"
|
||||||
|
|
||||||
|
export PATH="$HOME/.dotnet:$PATH"
|
||||||
|
export DOTNET_ROOT="$HOME/.dotnet"
|
||||||
|
|
||||||
|
dotnet --info >/dev/null 2>&1 && install_ok=1
|
||||||
|
;;
|
||||||
|
riscv64|ppc64le|loongarch64)
|
||||||
|
install_ok=1
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
die "Only supports x86_64 / aarch64 / riscv64 / ppc64le / loongarch64"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ "$install_ok" -ne 1 ]]; then
|
if [[ "$install_ok" -ne 1 ]]; then
|
||||||
@@ -107,6 +164,48 @@ install_dependencies() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
|
prepare_cross_rpm_tools() {
|
||||||
|
local target="$1"
|
||||||
|
local package=""
|
||||||
|
local strip_tool=""
|
||||||
|
local objdump_tool=""
|
||||||
|
|
||||||
|
case "$HOST_ARCH:$target" in
|
||||||
|
x86_64:ppc64le|aarch64:ppc64le)
|
||||||
|
package="gcc-powerpc64le-linux-gnu"
|
||||||
|
strip_tool="powerpc64le-linux-gnu-strip"
|
||||||
|
objdump_tool="powerpc64le-linux-gnu-objdump"
|
||||||
|
;;
|
||||||
|
x86_64:riscv64|aarch64:riscv64)
|
||||||
|
package="gcc-riscv64-linux-gnu"
|
||||||
|
strip_tool="riscv64-linux-gnu-strip"
|
||||||
|
objdump_tool="riscv64-linux-gnu-objdump"
|
||||||
|
;;
|
||||||
|
x86_64:loong64|aarch64:loong64)
|
||||||
|
package="gcc-loongarch64-linux-gnu"
|
||||||
|
strip_tool="loongarch64-linux-gnu-strip"
|
||||||
|
objdump_tool="loongarch64-linux-gnu-objdump"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
RPM_STRIP=""
|
||||||
|
RPM_OBJDUMP=""
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
echo "[+] Install cross RPM tools for $target: $package"
|
||||||
|
sudo dnf -y install "$package"
|
||||||
|
|
||||||
|
command -v "$strip_tool" >/dev/null 2>&1 || die "Cross strip tool not found: $strip_tool"
|
||||||
|
command -v "$objdump_tool" >/dev/null 2>&1 || die "Cross objdump tool not found: $objdump_tool"
|
||||||
|
|
||||||
|
RPM_STRIP="$(command -v "$strip_tool")"
|
||||||
|
RPM_OBJDUMP="$(command -v "$objdump_tool")"
|
||||||
|
|
||||||
|
echo "[OK] RPM strip: $RPM_STRIP"
|
||||||
|
echo "[OK] RPM objdump: $RPM_OBJDUMP"
|
||||||
|
}
|
||||||
|
|
||||||
prepare_workspace() {
|
prepare_workspace() {
|
||||||
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
cd "$SCRIPT_DIR"
|
cd "$SCRIPT_DIR"
|
||||||
@@ -239,14 +338,115 @@ resolve_version() {
|
|||||||
echo "[*] GUI version resolved as: ${VERSION}"
|
echo "[*] GUI version resolved as: ${VERSION}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
download_nuget_packages() {
|
||||||
|
NUGET_CACHE_DIR="$(mktemp -d)"
|
||||||
|
|
||||||
|
local riscv_rt ppc64le_rt loong_rt
|
||||||
|
riscv_rt="$(get_runtime_version "$DOTNET_RISCV_VERSION")"
|
||||||
|
ppc64le_rt="$(get_runtime_version "$DOTNET_PPC64LE_VERSION")"
|
||||||
|
loong_rt="$(get_runtime_version "$DOTNET_LOONGARCH_VERSION")"
|
||||||
|
|
||||||
|
local urls=(
|
||||||
|
"${DOTNET_NUPKG_BASE}/${loong_rt}/Microsoft.AspNetCore.App.Runtime.linux-loongarch64.${loong_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${ppc64le_rt}/Microsoft.AspNetCore.App.Runtime.linux-ppc64le.${ppc64le_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${riscv_rt}/Microsoft.AspNetCore.App.Runtime.linux-riscv64.${riscv_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${loong_rt}/Microsoft.NETCore.App.Host.linux-loongarch64.${loong_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${ppc64le_rt}/Microsoft.NETCore.App.Host.linux-ppc64le.${ppc64le_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${riscv_rt}/Microsoft.NETCore.App.Host.linux-riscv64.${riscv_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${loong_rt}/Microsoft.NETCore.App.Runtime.linux-loongarch64.${loong_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${ppc64le_rt}/Microsoft.NETCore.App.Runtime.linux-ppc64le.${ppc64le_rt}.nupkg"
|
||||||
|
"${DOTNET_NUPKG_BASE}/${riscv_rt}/Microsoft.NETCore.App.Runtime.linux-riscv64.${riscv_rt}.nupkg"
|
||||||
|
"${SKIASHARP_BASE}/v${SkiaSharp_VERSION}/SkiaSharp.NativeAssets.Linux.${SkiaSharp_VERSION}.nupkg"
|
||||||
|
"${SKIASHARP_BASE}/v${SkiaSharp_VERSION}/HarfBuzzSharp.NativeAssets.Linux.${HarfBuzzSharp_VERSION}.nupkg"
|
||||||
|
)
|
||||||
|
|
||||||
|
echo "[+] Downloading prebuilt NuGet packages to: $NUGET_CACHE_DIR"
|
||||||
|
local u pkg_name
|
||||||
|
for u in "${urls[@]}"; do
|
||||||
|
pkg_name="${u##*/}"
|
||||||
|
echo " -> $pkg_name"
|
||||||
|
curl -fL "$u" -o "$NUGET_CACHE_DIR/$pkg_name" || {
|
||||||
|
echo "[!] Failed to download $u" >&2
|
||||||
|
rm -rf "$NUGET_CACHE_DIR"
|
||||||
|
NUGET_CACHE_DIR=""
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "[OK] Prebuilt NuGet packages ready in $NUGET_CACHE_DIR"
|
||||||
|
}
|
||||||
|
|
||||||
|
prepare_dotnet_sdk() {
|
||||||
|
local short="$1"
|
||||||
|
local sdk_url=""
|
||||||
|
local sdk_file=""
|
||||||
|
local sdk_dir=""
|
||||||
|
local tmp=""
|
||||||
|
|
||||||
|
case "$HOST_ARCH:$short" in
|
||||||
|
x86_64:x64|aarch64:arm64)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
riscv64:riscv64)
|
||||||
|
sdk_url="$DOTNET_RISCV_SDK_URL"
|
||||||
|
sdk_file="$DOTNET_RISCV_FILE"
|
||||||
|
;;
|
||||||
|
ppc64le:ppc64le)
|
||||||
|
sdk_url="$DOTNET_PPC64LE_SDK_URL"
|
||||||
|
sdk_file="$DOTNET_PPC64LE_FILE"
|
||||||
|
;;
|
||||||
|
loongarch64:loong64)
|
||||||
|
sdk_url="$DOTNET_LOONGARCH_SDK_URL"
|
||||||
|
sdk_file="$DOTNET_LOONGARCH_FILE"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
sdk_dir="$(mktemp -d)"
|
||||||
|
tmp="$(mktemp -d)"
|
||||||
|
|
||||||
|
echo "[+] Download .NET SDK for $short: $sdk_url"
|
||||||
|
|
||||||
|
curl -fL "$sdk_url" -o "$tmp/$sdk_file" || {
|
||||||
|
rm -rf "$tmp" "$sdk_dir"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
tar -C "$sdk_dir" -xzf "$tmp/$sdk_file" || {
|
||||||
|
rm -rf "$tmp" "$sdk_dir"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
rm -rf "$tmp"
|
||||||
|
|
||||||
|
[[ -x "$sdk_dir/dotnet" ]] || {
|
||||||
|
rm -rf "$sdk_dir"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
export DOTNET_ROOT="$sdk_dir"
|
||||||
|
export PATH="$DOTNET_ROOT:$PATH"
|
||||||
|
hash -r
|
||||||
|
|
||||||
|
echo "[OK] .NET SDK for $short extracted to: $sdk_dir"
|
||||||
|
dotnet --info
|
||||||
|
|
||||||
|
DOTNET_SDK_DIR="$sdk_dir"
|
||||||
|
}
|
||||||
|
|
||||||
xray_url_for_rid() {
|
xray_url_for_rid() {
|
||||||
local rid="$1"
|
local rid="$1"
|
||||||
local ver="$2"
|
local ver="$2"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-x64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-64.zip" ;;
|
linux-x64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-64.zip" ;;
|
||||||
linux-arm64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-arm64-v8a.zip" ;;
|
linux-arm64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-arm64-v8a.zip" ;;
|
||||||
*) return 1 ;;
|
linux-riscv64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-riscv64.zip" ;;
|
||||||
|
linux-ppc64le) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-ppc64le.zip" ;;
|
||||||
|
linux-loongarch64) echo "https://github.com/XTLS/Xray-core/releases/download/v${ver}/Xray-linux-loong64.zip" ;;
|
||||||
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -255,9 +455,12 @@ singbox_url_for_rid() {
|
|||||||
local ver="$2"
|
local ver="$2"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-x64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-amd64.tar.gz" ;;
|
linux-x64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-amd64.tar.gz" ;;
|
||||||
linux-arm64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-arm64.tar.gz" ;;
|
linux-arm64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-arm64.tar.gz" ;;
|
||||||
*) return 1 ;;
|
linux-riscv64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-riscv64.tar.gz" ;;
|
||||||
|
linux-ppc64le) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-ppc64le.tar.gz" ;;
|
||||||
|
linux-loongarch64) echo "https://github.com/SagerNet/sing-box/releases/download/v${ver}/sing-box-${ver}-linux-loong64.tar.gz" ;;
|
||||||
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,9 +468,12 @@ bundle_url_for_rid() {
|
|||||||
local rid="$1"
|
local rid="$1"
|
||||||
|
|
||||||
case "$rid" in
|
case "$rid" in
|
||||||
linux-x64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-64.zip" ;;
|
linux-x64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-64.zip" ;;
|
||||||
linux-arm64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-arm64.zip" ;;
|
linux-arm64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-arm64.zip" ;;
|
||||||
*) return 1 ;;
|
linux-riscv64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-riscv64.zip" ;;
|
||||||
|
linux-ppc64le) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-ppc64le.zip" ;;
|
||||||
|
linux-loongarch64) echo "https://raw.githubusercontent.com/2dust/v2rayN-core-bin/refs/heads/master/v2rayN-linux-loong64.zip" ;;
|
||||||
|
*) return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,7 +494,7 @@ download_xray() {
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
[[ -n "$ver" ]] || { echo "[xray] Failed to get version"; return 1; }
|
[[ -n "$ver" ]] || { echo "[xray] Failed to get version"; return 1; }
|
||||||
url="$(xray_url_for_rid "$rid" "$ver")" || { echo "[xray] Unsupported RID: $rid"; return 1; }
|
url="$(xray_url_for_rid "$rid" "$ver")" || { echo "[xray] Unsupported RID for upstream Xray: $rid (skipped)"; return 0; }
|
||||||
|
|
||||||
echo "[+] Download xray: $url"
|
echo "[+] Download xray: $url"
|
||||||
|
|
||||||
@@ -463,9 +669,12 @@ describe_target() {
|
|||||||
local short="$1"
|
local short="$1"
|
||||||
|
|
||||||
case "$short" in
|
case "$short" in
|
||||||
x64) printf '%s\n%s\n%s\n' "linux-x64" "x86_64" "x86_64" ;;
|
x64) printf '%s\n%s\n%s\n' "linux-x64" "x86_64" "x86_64" ;;
|
||||||
arm64) printf '%s\n%s\n%s\n' "linux-arm64" "aarch64" "aarch64" ;;
|
arm64) printf '%s\n%s\n%s\n' "linux-arm64" "aarch64" "aarch64" ;;
|
||||||
*) echo "Unknown arch '$short' (use x64|arm64)" >&2; return 1 ;;
|
riscv64) printf '%s\n%s\n%s\n' "linux-riscv64" "riscv64" "riscv64" ;;
|
||||||
|
ppc64le) printf '%s\n%s\n%s\n' "linux-ppc64le" "ppc64le" "ppc64le" ;;
|
||||||
|
loong64) printf '%s\n%s\n%s\n' "linux-loongarch64" "loongarch64" "loongarch64" ;;
|
||||||
|
*) echo "Unknown arch '$short' (use x64|arm64|riscv64|ppc64le|loong64)" >&2; return 1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -474,8 +683,18 @@ publish_binary() {
|
|||||||
|
|
||||||
dotnet clean "$PROJECT" -c Release
|
dotnet clean "$PROJECT" -c Release
|
||||||
rm -rf "$(dirname "$PROJECT")/bin/Release/net10.0" || true
|
rm -rf "$(dirname "$PROJECT")/bin/Release/net10.0" || true
|
||||||
dotnet restore "$PROJECT"
|
dotnet restore "$PROJECT" \
|
||||||
dotnet publish "$PROJECT" -c Release -r "$rid" -p:PublishSingleFile=false -p:SelfContained=true
|
-r "$rid" \
|
||||||
|
--source "$NUGET_CACHE_DIR" \
|
||||||
|
--source "https://api.nuget.org/v3/index.json"
|
||||||
|
dotnet publish "$PROJECT" \
|
||||||
|
-c Release \
|
||||||
|
-r "$rid" \
|
||||||
|
--source "$NUGET_CACHE_DIR" \
|
||||||
|
--source "https://api.nuget.org/v3/index.json" \
|
||||||
|
-p:PublishSingleFile=false \
|
||||||
|
-p:SelfContained=true \
|
||||||
|
--no-restore
|
||||||
}
|
}
|
||||||
|
|
||||||
write_spec_file() {
|
write_spec_file() {
|
||||||
@@ -490,21 +709,21 @@ write_spec_file() {
|
|||||||
Name: v2rayN
|
Name: v2rayN
|
||||||
Version: __VERSION__
|
Version: __VERSION__
|
||||||
Release: 1%{?dist}
|
Release: 1%{?dist}
|
||||||
Summary: v2rayN (Avalonia) GUI client for Linux (x86_64/aarch64)
|
Summary: v2rayN (Avalonia) GUI client for Linux
|
||||||
License: GPL-3.0-only
|
License: GPL-3.0-only
|
||||||
URL: https://github.com/2dust/v2rayN
|
URL: https://github.com/2dust/v2rayN
|
||||||
BugURL: https://github.com/2dust/v2rayN/issues
|
BugURL: https://github.com/2dust/v2rayN/issues
|
||||||
ExclusiveArch: aarch64 x86_64
|
ExclusiveArch: aarch64 x86_64 riscv64 ppc64le loongarch64
|
||||||
Source0: __PKGROOT__.tar.gz
|
Source0: __PKGROOT__.tar.gz
|
||||||
|
|
||||||
Requires: cairo, pango, openssl, mesa-libEGL, mesa-libGL
|
Requires: cairo, pango, openssl, mesa-libEGL, mesa-libGL
|
||||||
Requires: glibc >= 2.34
|
Requires: glibc >= 2.39
|
||||||
Requires: fontconfig >= 2.13.1
|
Requires: fontconfig >= 2.15.0
|
||||||
Requires: desktop-file-utils >= 0.26
|
Requires: desktop-file-utils >= 0.26
|
||||||
Requires: xdg-utils >= 1.1.3
|
Requires: xdg-utils >= 1.1.3
|
||||||
Requires: coreutils >= 8.32
|
Requires: coreutils >= 9.4
|
||||||
Requires: bash >= 5.1
|
Requires: bash >= 5.2.21
|
||||||
Requires: freetype >= 2.10
|
Requires: freetype >= 2.13
|
||||||
|
|
||||||
%description
|
%description
|
||||||
v2rayN Linux for Red Hat Enterprise Linux
|
v2rayN Linux for Red Hat Enterprise Linux
|
||||||
@@ -616,7 +835,15 @@ package_binary() {
|
|||||||
tar -C "$workdir" -czf "$sourcedir/$PKGROOT.tar.gz" "$PKGROOT"
|
tar -C "$workdir" -czf "$sourcedir/$PKGROOT.tar.gz" "$PKGROOT"
|
||||||
|
|
||||||
write_spec_file "$specfile"
|
write_spec_file "$specfile"
|
||||||
rpmbuild -ba "$specfile" --target "$rpm_target"
|
|
||||||
|
if [[ -n "${RPM_STRIP:-}" ]]; then
|
||||||
|
rpmbuild -ba "$specfile" \
|
||||||
|
--target "$rpm_target" \
|
||||||
|
--define "__strip ${RPM_STRIP}" \
|
||||||
|
--define "__objdump ${RPM_OBJDUMP}"
|
||||||
|
else
|
||||||
|
rpmbuild -ba "$specfile" --target "$rpm_target"
|
||||||
|
fi
|
||||||
|
|
||||||
echo "Build done for $short. RPM at:"
|
echo "Build done for $short. RPM at:"
|
||||||
for f in "${RPM_TOPDIR}/RPMS/${archdir}/v2rayN-${VERSION}-1"*.rpm; do
|
for f in "${RPM_TOPDIR}/RPMS/${archdir}/v2rayN-${VERSION}-1"*.rpm; do
|
||||||
@@ -628,9 +855,12 @@ package_binary() {
|
|||||||
|
|
||||||
select_targets() {
|
select_targets() {
|
||||||
case "${ARCH_OVERRIDE:-}" in
|
case "${ARCH_OVERRIDE:-}" in
|
||||||
all) printf '%s\n' x64 arm64 ;;
|
all) printf '%s\n' x64 arm64 riscv64 ppc64le loong64 ;;
|
||||||
x64|amd64) printf '%s\n' x64 ;;
|
x64|amd64) printf '%s\n' x64 ;;
|
||||||
arm64|aarch64) printf '%s\n' arm64 ;;
|
arm64|aarch64) printf '%s\n' arm64 ;;
|
||||||
|
riscv64) printf '%s\n' riscv64 ;;
|
||||||
|
ppc64le|ppc64el) printf '%s\n' ppc64le ;;
|
||||||
|
loong64|loongarch64) printf '%s\n' loong64 ;;
|
||||||
"")
|
"")
|
||||||
case "$HOST_ARCH" in
|
case "$HOST_ARCH" in
|
||||||
x86_64) printf '%s\n' x64 ;;
|
x86_64) printf '%s\n' x64 ;;
|
||||||
@@ -639,7 +869,7 @@ select_targets() {
|
|||||||
esac
|
esac
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "Unknown --arch '${ARCH_OVERRIDE}'. Use x64|arm64|all." >&2
|
echo "Unknown --arch '${ARCH_OVERRIDE}'. Use x64|arm64|riscv64|ppc64le|loong64|all." >&2
|
||||||
return 1
|
return 1
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
@@ -658,6 +888,8 @@ build_one_target() {
|
|||||||
archdir="${meta[2]}"
|
archdir="${meta[2]}"
|
||||||
|
|
||||||
echo "[*] Building for target: $short (RID=$rid, RPM --target $rpm_target)"
|
echo "[*] Building for target: $short (RID=$rid, RPM --target $rpm_target)"
|
||||||
|
prepare_cross_rpm_tools "$short"
|
||||||
|
prepare_dotnet_sdk "$short" || die "Failed to prepare .NET SDK for $short."
|
||||||
publish_binary "$rid"
|
publish_binary "$rid"
|
||||||
package_binary "$short" "$rid" "$rpm_target" "$archdir"
|
package_binary "$short" "$rid" "$rpm_target" "$archdir"
|
||||||
}
|
}
|
||||||
@@ -666,7 +898,7 @@ print_summary() {
|
|||||||
if [[ "$BUILT_ALL" -eq 1 ]]; then
|
if [[ "$BUILT_ALL" -eq 1 ]]; then
|
||||||
local rp=""
|
local rp=""
|
||||||
echo ""
|
echo ""
|
||||||
echo "================ Build Summary (both architectures) ================"
|
echo "================ Build Summary (all architectures) ================"
|
||||||
if [[ "${#BUILT_RPMS[@]}" -gt 0 ]]; then
|
if [[ "${#BUILT_RPMS[@]}" -gt 0 ]]; then
|
||||||
for rp in "${BUILT_RPMS[@]}"; do
|
for rp in "${BUILT_RPMS[@]}"; do
|
||||||
echo "$rp"
|
echo "$rp"
|
||||||
@@ -688,6 +920,8 @@ main() {
|
|||||||
prepare_workspace
|
prepare_workspace
|
||||||
resolve_version
|
resolve_version
|
||||||
|
|
||||||
|
download_nuget_packages || die "Failed to download prebuilt NuGet packages."
|
||||||
|
|
||||||
mapfile -t targets < <(select_targets)
|
mapfile -t targets < <(select_targets)
|
||||||
[[ "${ARCH_OVERRIDE:-}" == "all" ]] && BUILT_ALL=1 || BUILT_ALL=0
|
[[ "${ARCH_OVERRIDE:-}" == "all" ]] && BUILT_ALL=1 || BUILT_ALL=0
|
||||||
|
|
||||||
@@ -695,7 +929,10 @@ main() {
|
|||||||
build_one_target "$arch"
|
build_one_target "$arch"
|
||||||
done
|
done
|
||||||
|
|
||||||
|
rm -rf "${NUGET_CACHE_DIR:-}" || true
|
||||||
|
rm -rf "${DOTNET_SDK_DIR:-}" || true
|
||||||
|
|
||||||
print_summary
|
print_summary
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
@@ -5,16 +5,31 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<EmbeddedResource Update="Resx\Resource.resx">
|
|
||||||
<Generator>ResXFileCodeGenerator</Generator>
|
|
||||||
<LastGenOutput>Resource.Designer.cs</LastGenOutput>
|
|
||||||
</EmbeddedResource>
|
|
||||||
|
|
||||||
<Compile Update="Resx\Resource.Designer.cs">
|
<Compile Update="Resx\Resource.Designer.cs">
|
||||||
<DesignTime>True</DesignTime>
|
<DesignTime>True</DesignTime>
|
||||||
<AutoGen>True</AutoGen>
|
<AutoGen>True</AutoGen>
|
||||||
<DependentUpon>Resource.resx</DependentUpon>
|
<DependentUpon>Resource.resx</DependentUpon>
|
||||||
</Compile>
|
</Compile>
|
||||||
|
<EmbeddedResource Update="Resx\Resource.resx">
|
||||||
|
<SubType>Designer</SubType>
|
||||||
|
<LastGenOutput>Resource.Designer.cs</LastGenOutput>
|
||||||
|
<Generator>ResXFileCodeGenerator</Generator>
|
||||||
|
</EmbeddedResource>
|
||||||
|
<EmbeddedResource Update="Resx\ResUI.zh-Hans.resx">
|
||||||
|
<SubType>Designer</SubType>
|
||||||
|
<Generator>ResXFileCodeGenerator</Generator>
|
||||||
|
</EmbeddedResource>
|
||||||
|
<EmbeddedResource Update="Resx\ResUI.zh-Hant.resx">
|
||||||
|
<SubType>Designer</SubType>
|
||||||
|
<Generator>ResXFileCodeGenerator</Generator>
|
||||||
|
</EmbeddedResource>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<Target Name="RemoveAotSatelliteOutputs" AfterTargets="ComputeFilesToPublish" Condition="'$(PublishAot)' == 'true'">
|
||||||
|
<ItemGroup>
|
||||||
|
<ResolvedFileToPublish Remove="@(ResolvedFileToPublish)"
|
||||||
|
Condition="$([System.String]::Copy('%(ResolvedFileToPublish.RelativePath)').Contains('resources.dll'))" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Target>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
+1
-1
@@ -19,7 +19,7 @@ namespace AmazTool.Resx {
|
|||||||
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
|
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
|
||||||
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
|
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
|
||||||
// (以 /str 作为命令选项),或重新生成 VS 项目。
|
// (以 /str 作为命令选项),或重新生成 VS 项目。
|
||||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
|
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "18.0.0.0")]
|
||||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||||
internal class Resource {
|
internal class Resource {
|
||||||
|
|||||||
@@ -45,6 +45,8 @@ internal class UpgradeApp
|
|||||||
var thisAppOldFile = $"{Utils.GetExePath()}.tmp";
|
var thisAppOldFile = $"{Utils.GetExePath()}.tmp";
|
||||||
File.Delete(thisAppOldFile);
|
File.Delete(thisAppOldFile);
|
||||||
var splitKey = "/";
|
var splitKey = "/";
|
||||||
|
var allowedBaseDir = Utils.StartupPath();
|
||||||
|
var pathComparison = Utils.GetPathComparison();
|
||||||
|
|
||||||
using var archive = ZipFile.OpenRead(fileName);
|
using var archive = ZipFile.OpenRead(fileName);
|
||||||
foreach (var entry in archive.Entries)
|
foreach (var entry in archive.Entries)
|
||||||
@@ -65,16 +67,21 @@ internal class UpgradeApp
|
|||||||
}
|
}
|
||||||
|
|
||||||
var fullName = string.Join(splitKey, lst[1..lst.Length]);
|
var fullName = string.Join(splitKey, lst[1..lst.Length]);
|
||||||
|
var entryOutputPath = Utils.GetPath(fullName);
|
||||||
|
if (!Utils.IsPathUnderDirectory(allowedBaseDir, entryOutputPath))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"{Resx.Resource.FailedUpgrade} blocked potential path traversal: {entry.FullName}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (string.Equals(Utils.GetExePath(), Utils.GetPath(fullName), StringComparison.OrdinalIgnoreCase))
|
if (string.Equals(Utils.GetExePath(), entryOutputPath, pathComparison))
|
||||||
{
|
{
|
||||||
File.Move(Utils.GetExePath(), thisAppOldFile);
|
File.Move(Utils.GetExePath(), thisAppOldFile);
|
||||||
}
|
}
|
||||||
|
|
||||||
var entryOutputPath = Utils.GetPath(fullName);
|
|
||||||
Directory.CreateDirectory(Path.GetDirectoryName(entryOutputPath)!);
|
Directory.CreateDirectory(Path.GetDirectoryName(entryOutputPath)!);
|
||||||
//In the bin folder, if the file already exists, it will be skipped
|
//In the bin folder, if the file already exists, it will be skipped
|
||||||
if (fullName.StartsWith("bin") && File.Exists(entryOutputPath))
|
if (fullName.StartsWith("bin", pathComparison) && File.Exists(entryOutputPath))
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,28 @@ internal class Utils
|
|||||||
return Path.Combine(startupPath, fileName);
|
return Path.Combine(startupPath, fileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static bool IsPathUnderDirectory(string baseDir, string targetPath)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(baseDir) || string.IsNullOrWhiteSpace(targetPath))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var baseFull = Path.GetFullPath(baseDir);
|
||||||
|
var targetFull = Path.GetFullPath(targetPath);
|
||||||
|
|
||||||
|
baseFull = baseFull.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
|
||||||
|
|
||||||
|
return targetFull.StartsWith(baseFull, GetPathComparison());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static StringComparison GetPathComparison()
|
||||||
|
{
|
||||||
|
return OperatingSystem.IsWindows()
|
||||||
|
? StringComparison.OrdinalIgnoreCase
|
||||||
|
: StringComparison.Ordinal;
|
||||||
|
}
|
||||||
|
|
||||||
public static string V2rayN => "v2rayN";
|
public static string V2rayN => "v2rayN";
|
||||||
|
|
||||||
public static void StartV2RayN()
|
public static void StartV2RayN()
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<Project>
|
<Project>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<Version>7.22.5</Version>
|
<Version>7.25.6</Version>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
@@ -29,4 +29,14 @@
|
|||||||
<PublishSingleFile>true</PublishSingleFile>
|
<PublishSingleFile>true</PublishSingleFile>
|
||||||
<PublishReadyToRun>false</PublishReadyToRun>
|
<PublishReadyToRun>false</PublishReadyToRun>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<IsAot Condition="'$(IsAot)' == ''">false</IsAot>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup Condition="'$(IsAot)' == 'true'">
|
||||||
|
<PublishAot>true</PublishAot>
|
||||||
|
<PublishTrimmed>true</PublishTrimmed>
|
||||||
|
<DefineConstants>$(DefineConstants);V2RAYN_IS_AOT</DefineConstants>
|
||||||
|
</PropertyGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,39 +1,36 @@
|
|||||||
<Project>
|
<Project>
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||||
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
|
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
|
||||||
<CentralPackageVersionOverrideEnabled>false</CentralPackageVersionOverrideEnabled>
|
<CentralPackageVersionOverrideEnabled>false</CentralPackageVersionOverrideEnabled>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageVersion Include="Avalonia.AvaloniaEdit" Version="11.4.1" />
|
<PackageVersion Include="Avalonia.AvaloniaEdit" Version="12.0.0" />
|
||||||
<PackageVersion Include="Avalonia.Controls.DataGrid" Version="11.3.13" />
|
<PackageVersion Include="Avalonia.Desktop" Version="12.1.6" />
|
||||||
<PackageVersion Include="Avalonia.Desktop" Version="11.3.17" />
|
<PackageVersion Include="AvaloniaUI.DiagnosticsSupport" Version="2.2.3" />
|
||||||
<PackageVersion Include="Avalonia.Diagnostics" Version="11.3.17" />
|
<PackageVersion Include="DialogHost.Avalonia" Version="0.12.3" />
|
||||||
<PackageVersion Include="AwesomeAssertions" Version="9.4.0" />
|
<PackageVersion Include="IPNetwork2" Version="5.0.1" />
|
||||||
<PackageVersion Include="DialogHost.Avalonia" Version="0.11.0" />
|
<PackageVersion Include="ProDataGrid" Version="12.1.5" />
|
||||||
<PackageVersion Include="IPNetwork2" Version="4.3.0" />
|
<PackageVersion Include="ReactiveUI.Avalonia" Version="12.1.6" />
|
||||||
<PackageVersion Include="ReactiveUI.Avalonia" Version="11.4.13" />
|
<PackageVersion Include="CliWrap" Version="3.10.5" />
|
||||||
<PackageVersion Include="CliWrap" Version="3.10.1" />
|
<PackageVersion Include="Downloader" Version="7.0.1" />
|
||||||
<PackageVersion Include="Downloader" Version="5.7.0" />
|
<PackageVersion Include="H.NotifyIcon.Wpf" Version="2.4.1" />
|
||||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
|
<PackageVersion Include="MaterialDesignThemes" Version="5.4.0" />
|
||||||
<PackageVersion Include="H.NotifyIcon.Wpf" Version="2.4.1" />
|
<PackageVersion Include="QRCoder" Version="1.8.1" />
|
||||||
<PackageVersion Include="MaterialDesignThemes" Version="5.3.2" />
|
<PackageVersion Include="ReactiveUI" Version="26.0.1" />
|
||||||
<PackageVersion Include="QRCoder" Version="1.8.0" />
|
<PackageVersion Include="ReactiveUI.WPF" Version="26.0.1" />
|
||||||
<PackageVersion Include="ReactiveUI" Version="23.2.28" />
|
<PackageVersion Include="Semi.Avalonia" Version="12.1.0.1" />
|
||||||
<PackageVersion Include="ReactiveUI.Fody" Version="19.5.41" />
|
<PackageVersion Include="Semi.Avalonia.AvaloniaEdit" Version="12.0.0" />
|
||||||
<PackageVersion Include="ReactiveUI.WPF" Version="23.2.28" />
|
<PackageVersion Include="Semi.Avalonia.DataGrid" Version="12.1.0.1" />
|
||||||
<PackageVersion Include="Semi.Avalonia" Version="11.3.14" />
|
<PackageVersion Include="NLog" Version="6.2.2" />
|
||||||
<PackageVersion Include="Semi.Avalonia.AvaloniaEdit" Version="11.2.0.2" />
|
<PackageVersion Include="sqlite-net-e" Version="1.11.285" />
|
||||||
<PackageVersion Include="Semi.Avalonia.DataGrid" Version="11.3.7.3" />
|
<PackageVersion Include="Repobot.SQLite.Unofficial" Version="3.54.1" />
|
||||||
<PackageVersion Include="NLog" Version="6.1.3" />
|
<PackageVersion Include="TUnit" Version="1.84.0" />
|
||||||
<PackageVersion Include="sqlite-net-e" Version="1.11.0" />
|
<PackageVersion Include="TUnit.Assertions.Should" Version="1.72.16-beta" />
|
||||||
<PackageVersion Include="Repobot.SQLite.Unofficial" Version="3.53.2" />
|
<PackageVersion Include="WebDav.Client" Version="2.9.0" />
|
||||||
<PackageVersion Include="TaskScheduler" Version="2.12.2" />
|
<PackageVersion Include="YamlDotNet" Version="18.1.0" />
|
||||||
<PackageVersion Include="WebDav.Client" Version="2.9.0" />
|
<PackageVersion Include="ZXing.Net.Bindings.SkiaSharp" Version="0.16.22" />
|
||||||
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
|
<PackageVersion Include="SkiaSharp.NativeAssets.Linux" Version="3.119.4" />
|
||||||
<PackageVersion Include="xunit.v3" Version="3.2.2" />
|
<PackageVersion Include="HarfBuzzSharp.NativeAssets.Linux" Version="8.3.1.5" />
|
||||||
<PackageVersion Include="YamlDotNet" Version="18.0.0" />
|
</ItemGroup>
|
||||||
<PackageVersion Include="ZXing.Net.Bindings.SkiaSharp" Version="0.16.22" />
|
|
||||||
<PackageVersion Include="SkiaSharp.NativeAssets.Linux" Version="3.119.4" />
|
|
||||||
</ItemGroup>
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
+1
-1
Submodule v2rayN/GlobalHotKeys updated: 569a95bb0f...e507a76804
@@ -0,0 +1,82 @@
|
|||||||
|
namespace ServiceLib.Tests.Common;
|
||||||
|
|
||||||
|
public class JsonUtilsMetadataTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments(false, false)]
|
||||||
|
[Arguments(false, true)]
|
||||||
|
[Arguments(true, false)]
|
||||||
|
[Arguments(true, true)]
|
||||||
|
public async Task Serialize_PreservesIndentationNullsAndUnicode(bool indented, bool nullValue)
|
||||||
|
{
|
||||||
|
var item = new WebDavItem { Url = "https://example.com/русский", UserName = "tester" };
|
||||||
|
|
||||||
|
var json = JsonUtils.Serialize(item, indented, nullValue);
|
||||||
|
var node = JsonUtils.ParseJson(json)!.AsObject();
|
||||||
|
|
||||||
|
await node["Url"]!.GetValue<string>().Should().BeEqualTo(item.Url);
|
||||||
|
await json.Contains("русский").Should().BeTrue();
|
||||||
|
await json.Contains(Environment.NewLine).Should().BeEqualTo(indented);
|
||||||
|
await node.ContainsKey("Password").Should().BeEqualTo(nullValue);
|
||||||
|
await node.ContainsKey("DirName").Should().BeEqualTo(nullValue);
|
||||||
|
await JsonUtils.Deserialize<WebDavItem>(json)!.UserName.Should().BeEqualTo("tester");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task Deserialize_AcceptsCommentsAndCaseInsensitiveNames()
|
||||||
|
{
|
||||||
|
const string json = "{/* existing configuration */ \"uRl\":\"https://example.com\",\"USERNAME\":\"tester\"}";
|
||||||
|
var item = JsonUtils.Deserialize<WebDavItem>(json)!;
|
||||||
|
|
||||||
|
await item.Url.Should().BeEqualTo("https://example.com");
|
||||||
|
await item.UserName.Should().BeEqualTo("tester");
|
||||||
|
await JsonUtils.Deserialize<WebDavItem>("invalid").Should().BeNull();
|
||||||
|
await JsonUtils.Deserialize<WebDavItem>(" ").Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task NodeAndCamelCaseSerialization_UseTheRequestedOptions()
|
||||||
|
{
|
||||||
|
var item = new WebDavItem { Url = "https://example.com" };
|
||||||
|
var node = JsonUtils.SerializeToNode(item, nullValue: true)!.AsObject();
|
||||||
|
var camelCase = JsonUtils.ParseJson(JsonUtils.SerializeCamelCase(item))!.AsObject();
|
||||||
|
|
||||||
|
await node.ContainsKey("Password").Should().BeTrue();
|
||||||
|
await JsonUtils.SerializeToNode(item)!.AsObject().ContainsKey("Password").Should().BeFalse();
|
||||||
|
await camelCase["url"]!.GetValue<string>().Should().BeEqualTo(item.Url);
|
||||||
|
await camelCase.ContainsKey("Url").Should().BeFalse();
|
||||||
|
await camelCase.ContainsKey("password").Should().BeFalse();
|
||||||
|
|
||||||
|
var values = JsonUtils.SerializeToArray(["first", "second"])!;
|
||||||
|
await values.Count.Should().BeEqualTo(2);
|
||||||
|
await values[0]!.GetValue<string>().Should().BeEqualTo("first");
|
||||||
|
await values[1]!.GetValue<string>().Should().BeEqualTo("second");
|
||||||
|
await JsonUtils.SerializeToArray(null).Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task DeepCopy_KeepsProfileDataAndCreatesAnIndependentModel()
|
||||||
|
{
|
||||||
|
var item = new ProfileItem { IndexId = "profile", Address = "example.com", Port = 443, Remarks = "Original" };
|
||||||
|
var copy = JsonUtils.DeepCopy(item)!;
|
||||||
|
|
||||||
|
await copy.IndexId.Should().BeEqualTo(item.IndexId);
|
||||||
|
await copy.Address.Should().BeEqualTo(item.Address);
|
||||||
|
await copy.Port.Should().BeEqualTo(443);
|
||||||
|
copy.Remarks = "Changed";
|
||||||
|
await item.Remarks.Should().BeEqualTo("Original");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task UnsupportedTypes_PreserveTheExistingFailureResults()
|
||||||
|
{
|
||||||
|
await JsonUtils.Serialize(new UnsupportedValue()).Should().BeEqualTo(string.Empty);
|
||||||
|
await JsonUtils.SerializeCamelCase(new UnsupportedValue()).Should().BeEqualTo(string.Empty);
|
||||||
|
await JsonUtils.Deserialize<UnsupportedValue>("{\"Name\":\"value\"}").Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class UnsupportedValue
|
||||||
|
{
|
||||||
|
public string Name { get; set; } = "value";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
namespace ServiceLib.Tests.Common;
|
||||||
|
|
||||||
|
public class UnixFileModeTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
public async Task AlreadyExecutableSystemBinary_ShouldNotRequireOwnership()
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// /bin/sh is executable but owned by root on the Unix CI runners.
|
||||||
|
// A regular user must not need chmod permission just to launch it.
|
||||||
|
var mode = File.GetUnixFileMode("/bin/sh");
|
||||||
|
await Utils.SetUnixFileMode("/bin/sh").Should().BeTrue();
|
||||||
|
await File.GetUnixFileMode("/bin/sh").Should().BeEqualTo(mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task NonExecutableOwnedFile_ShouldGainExecuteBitsWithoutLosingOtherPermissions()
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var path = Path.GetTempFileName();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var mode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead;
|
||||||
|
File.SetUnixFileMode(path, mode);
|
||||||
|
|
||||||
|
await Utils.SetUnixFileMode(path).Should().BeTrue();
|
||||||
|
await File.GetUnixFileMode(path).Should().BeEqualTo(mode | UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
File.Delete(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,8 @@
|
|||||||
using AwesomeAssertions;
|
|
||||||
using ServiceLib.Enums;
|
|
||||||
using ServiceLib.Handler.Builder;
|
|
||||||
using ServiceLib.Helper;
|
|
||||||
using ServiceLib.Models;
|
|
||||||
using Xunit;
|
|
||||||
|
|
||||||
namespace ServiceLib.Tests.CoreConfig.Context;
|
namespace ServiceLib.Tests.CoreConfig.Context;
|
||||||
|
|
||||||
public class CoreConfigContextBuilderTests
|
public class CoreConfigContextBuilderTests
|
||||||
{
|
{
|
||||||
[Fact]
|
[Test]
|
||||||
public async Task ResolveNodeAsync_DirectCycleDependency_ShouldFailWithCycleError()
|
public async Task ResolveNodeAsync_DirectCycleDependency_ShouldFailWithCycleError()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig();
|
var config = CoreConfigTestFactory.CreateConfig();
|
||||||
@@ -27,13 +20,13 @@ public class CoreConfigContextBuilderTests
|
|||||||
|
|
||||||
var (_, validatorResult) = await CoreConfigContextBuilder.ResolveNodeAsync(context, groupA, false);
|
var (_, validatorResult) = await CoreConfigContextBuilder.ResolveNodeAsync(context, groupA, false);
|
||||||
|
|
||||||
validatorResult.Success.Should().BeFalse();
|
await validatorResult.Success.Should().BeFalse();
|
||||||
validatorResult.Errors.Should().Contain(msg => ContainsCycleDependencyMessage(msg));
|
await validatorResult.Errors.Should().Contain(ContainsCycleDependencyMessage);
|
||||||
context.AllProxiesMap.Should().NotContainKey(groupA.IndexId);
|
await context.AllProxiesMap.Should().NotContainKey(groupA.IndexId);
|
||||||
context.AllProxiesMap.Should().NotContainKey(groupB.IndexId);
|
await context.AllProxiesMap.Should().NotContainKey(groupB.IndexId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public async Task ResolveNodeAsync_IndirectCycleDependency_ShouldFailWithCycleError()
|
public async Task ResolveNodeAsync_IndirectCycleDependency_ShouldFailWithCycleError()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig();
|
var config = CoreConfigTestFactory.CreateConfig();
|
||||||
@@ -53,14 +46,14 @@ public class CoreConfigContextBuilderTests
|
|||||||
|
|
||||||
var (_, validatorResult) = await CoreConfigContextBuilder.ResolveNodeAsync(context, groupA, false);
|
var (_, validatorResult) = await CoreConfigContextBuilder.ResolveNodeAsync(context, groupA, false);
|
||||||
|
|
||||||
validatorResult.Success.Should().BeFalse();
|
await validatorResult.Success.Should().BeFalse();
|
||||||
validatorResult.Errors.Should().Contain(msg => ContainsCycleDependencyMessage(msg));
|
await validatorResult.Errors.Should().Contain(ContainsCycleDependencyMessage);
|
||||||
context.AllProxiesMap.Should().NotContainKey(groupA.IndexId);
|
await context.AllProxiesMap.Should().NotContainKey(groupA.IndexId);
|
||||||
context.AllProxiesMap.Should().NotContainKey(groupB.IndexId);
|
await context.AllProxiesMap.Should().NotContainKey(groupB.IndexId);
|
||||||
context.AllProxiesMap.Should().NotContainKey(groupC.IndexId);
|
await context.AllProxiesMap.Should().NotContainKey(groupC.IndexId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public async Task ResolveNodeAsync_CycleWithValidBranch_ShouldSkipCycleAndKeepValidChild()
|
public async Task ResolveNodeAsync_CycleWithValidBranch_ShouldSkipCycleAndKeepValidChild()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig();
|
var config = CoreConfigTestFactory.CreateConfig();
|
||||||
@@ -80,14 +73,14 @@ public class CoreConfigContextBuilderTests
|
|||||||
|
|
||||||
var (_, validatorResult) = await CoreConfigContextBuilder.ResolveNodeAsync(context, groupA, false);
|
var (_, validatorResult) = await CoreConfigContextBuilder.ResolveNodeAsync(context, groupA, false);
|
||||||
|
|
||||||
validatorResult.Success.Should().BeTrue();
|
await validatorResult.Success.Should().BeTrue();
|
||||||
validatorResult.Errors.Should().BeEmpty();
|
await validatorResult.Errors.Should().BeEmpty();
|
||||||
validatorResult.Warnings.Should().Contain(msg => ContainsCycleDependencyMessage(msg));
|
await validatorResult.Warnings.Should().Contain(ContainsCycleDependencyMessage);
|
||||||
|
|
||||||
context.AllProxiesMap.Should().ContainKey(leaf.IndexId);
|
await context.AllProxiesMap.Should().ContainKey(leaf.IndexId);
|
||||||
context.AllProxiesMap.Should().ContainKey(groupA.IndexId);
|
await context.AllProxiesMap.Should().ContainKey(groupA.IndexId);
|
||||||
context.AllProxiesMap.Should().NotContainKey(groupB.IndexId);
|
await context.AllProxiesMap.Should().NotContainKey(groupB.IndexId);
|
||||||
groupA.GetProtocolExtra().ChildItems.Should().Be(leaf.IndexId);
|
await groupA.GetProtocolExtra().ChildItems.Should().BeEqualTo(leaf.IndexId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string NewId(string prefix)
|
private static string NewId(string prefix)
|
||||||
@@ -105,7 +98,7 @@ public class CoreConfigContextBuilderTests
|
|||||||
|
|
||||||
private static async Task UpsertProfilesAsync(params ProfileItem[] profiles)
|
private static async Task UpsertProfilesAsync(params ProfileItem[] profiles)
|
||||||
{
|
{
|
||||||
SQLiteHelper.Instance.CreateTable<ProfileItem>();
|
TestDatabase.Initialize();
|
||||||
foreach (var profile in profiles)
|
foreach (var profile in profiles)
|
||||||
{
|
{
|
||||||
await SQLiteHelper.Instance.ReplaceAsync(profile);
|
await SQLiteHelper.Instance.ReplaceAsync(profile);
|
||||||
|
|||||||
@@ -1,16 +1,11 @@
|
|||||||
using System.Reflection;
|
|
||||||
using ServiceLib.Enums;
|
|
||||||
using ServiceLib.Manager;
|
|
||||||
using ServiceLib.Models;
|
|
||||||
|
|
||||||
namespace ServiceLib.Tests.CoreConfig;
|
namespace ServiceLib.Tests.CoreConfig;
|
||||||
|
|
||||||
internal static class CoreConfigTestFactory
|
internal static class CoreConfigTestFactory
|
||||||
{
|
{
|
||||||
public static void BindAppManagerConfig(Config config)
|
public static void BindAppManagerConfig(Config config)
|
||||||
{
|
{
|
||||||
var field = typeof(AppManager).GetField("_config", BindingFlags.Instance | BindingFlags.NonPublic);
|
var field = typeof(ConfigState).GetField("_current", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||||
field?.SetValue(AppManager.Instance, config);
|
field?.SetValue(ConfigState.Instance, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Config CreateConfig(ECoreType vmessCoreType = ECoreType.Xray)
|
public static Config CreateConfig(ECoreType vmessCoreType = ECoreType.Xray)
|
||||||
@@ -59,7 +54,7 @@ internal static class CoreConfigTestFactory
|
|||||||
},
|
},
|
||||||
WebDavItem = new WebDavItem(),
|
WebDavItem = new WebDavItem(),
|
||||||
CheckUpdateItem = new CheckUpdateItem(),
|
CheckUpdateItem = new CheckUpdateItem(),
|
||||||
Fragment4RayItem = new Fragment4RayItem { Packets = "tlshello", Length = "100-200", Interval = "10-20" },
|
Fragment4RayItem = new Fragment4RayItem { Packets = "tlshello", Lengths = ["100-200"], Delays = ["10-20"] },
|
||||||
Inbound =
|
Inbound =
|
||||||
[
|
[
|
||||||
new InItem
|
new InItem
|
||||||
@@ -84,6 +79,7 @@ internal static class CoreConfigTestFactory
|
|||||||
ParallelQuery = false,
|
ParallelQuery = false,
|
||||||
Strategy4Freedom = Global.AsIs,
|
Strategy4Freedom = Global.AsIs,
|
||||||
Strategy4Proxy = Global.AsIs,
|
Strategy4Proxy = Global.AsIs,
|
||||||
|
Strategy4ProxyDial = Global.AsIs,
|
||||||
},
|
},
|
||||||
IndexId = string.Empty,
|
IndexId = string.Empty,
|
||||||
SubIndexId = string.Empty,
|
SubIndexId = string.Empty,
|
||||||
@@ -130,6 +126,42 @@ internal static class CoreConfigTestFactory
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static ProfileItem CreateHttpNode(ECoreType coreType, string indexId = "node-http-1",
|
||||||
|
string remarks = "demo-http")
|
||||||
|
{
|
||||||
|
return new ProfileItem
|
||||||
|
{
|
||||||
|
IndexId = indexId,
|
||||||
|
ConfigType = EConfigType.HTTP,
|
||||||
|
CoreType = coreType,
|
||||||
|
Remarks = remarks,
|
||||||
|
Address = "proxy.example.com",
|
||||||
|
Port = 8080,
|
||||||
|
Password = "pass",
|
||||||
|
Username = "user",
|
||||||
|
Network = nameof(ETransport.raw),
|
||||||
|
StreamSecurity = string.Empty,
|
||||||
|
Subid = string.Empty,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ProfileItem CreateCustomOutboundNode(ECoreType coreType, string indexId = "node-custom-1",
|
||||||
|
string remarks = "demo-custom-outbound", string address = "custom_outbound.json")
|
||||||
|
{
|
||||||
|
return new ProfileItem
|
||||||
|
{
|
||||||
|
IndexId = indexId,
|
||||||
|
ConfigType = EConfigType.Outbound,
|
||||||
|
CoreType = coreType,
|
||||||
|
Remarks = remarks,
|
||||||
|
Address = address,
|
||||||
|
Port = 0,
|
||||||
|
Network = nameof(ETransport.raw),
|
||||||
|
StreamSecurity = string.Empty,
|
||||||
|
Subid = string.Empty,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
public static ProfileItem CreatePolicyGroupNode(ECoreType coreType, string indexId, string remarks,
|
public static ProfileItem CreatePolicyGroupNode(ECoreType coreType, string indexId, string remarks,
|
||||||
IEnumerable<string> childIndexIds)
|
IEnumerable<string> childIndexIds)
|
||||||
{
|
{
|
||||||
@@ -168,7 +200,8 @@ internal static class CoreConfigTestFactory
|
|||||||
return node;
|
return node;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static CoreConfigContext CreateContext(Config config, ProfileItem node, ECoreType runCoreType)
|
public static CoreConfigContext CreateContext(Config config, ProfileItem node, ECoreType runCoreType,
|
||||||
|
bool hasGlobalIPv6Address = true)
|
||||||
{
|
{
|
||||||
return new CoreConfigContext
|
return new CoreConfigContext
|
||||||
{
|
{
|
||||||
@@ -189,6 +222,7 @@ internal static class CoreConfigTestFactory
|
|||||||
FullConfigTemplate = null,
|
FullConfigTemplate = null,
|
||||||
IsTunEnabled = config.TunModeItem.EnableTun,
|
IsTunEnabled = config.TunModeItem.EnableTun,
|
||||||
ProtectDomainList = [],
|
ProtectDomainList = [],
|
||||||
|
HasGlobalIPv6Address = hasGlobalIPv6Address,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,4 +248,12 @@ internal static class CoreConfigTestFactory
|
|||||||
config.TunModeItem.RouteExcludeAddress = ["10.0.0.1/32", "192.168.1.0/24", "fc00::/7"];
|
config.TunModeItem.RouteExcludeAddress = ["10.0.0.1/32", "192.168.1.0/24", "fc00::/7"];
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static Config CreateConfigWithTun(ECoreType coreType, bool enableIPv6Address)
|
||||||
|
{
|
||||||
|
var config = CreateConfig(coreType);
|
||||||
|
config.TunModeItem.EnableTun = true;
|
||||||
|
config.TunModeItem.EnableIPv6Address = enableIPv6Address;
|
||||||
|
return config;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,185 @@
|
|||||||
|
namespace ServiceLib.Tests.CoreConfig;
|
||||||
|
|
||||||
|
public class DualStackFakeIPTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments(null, "fc00::/18", 65535L)]
|
||||||
|
[Arguments(" 2001:2::/48 ", "2001:2::/48", 65535L)]
|
||||||
|
[Arguments("fc00::/120", "fc00::/120", 255L)]
|
||||||
|
[Arguments("fc00::/127", "fc00::/127", 1L)]
|
||||||
|
public async Task IPv6Range_ShouldUseAnXrayCompatiblePoolSize(string? input, string expectedRange, long expectedSize)
|
||||||
|
{
|
||||||
|
var valid = FakeIPUtils.TryParseIPv6Range(input, out var range, out var size);
|
||||||
|
|
||||||
|
await valid.Should().BeTrue();
|
||||||
|
await range.Should().BeEqualTo(expectedRange);
|
||||||
|
await size.Should().BeEqualTo(expectedSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments("198.18.0.0/15")]
|
||||||
|
[Arguments("not-a-network")]
|
||||||
|
[Arguments("fc00::/128")]
|
||||||
|
public async Task IPv6Range_ShouldRejectInvalidOrSingleAddressPools(string input)
|
||||||
|
{
|
||||||
|
await FakeIPUtils.TryParseIPv6Range(input, out _, out _).Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task OldDnsSettings_ShouldKeepIPv6FakeIPDisabled()
|
||||||
|
{
|
||||||
|
var settings = JsonUtils.Deserialize<SimpleDNSItem>("""
|
||||||
|
{ "FakeIP": true, "FakeIPRange": "198.18.0.0/15" }
|
||||||
|
""")!;
|
||||||
|
|
||||||
|
await (settings.FakeIPv6 == true).Should().BeFalse();
|
||||||
|
await settings.FakeIPRange.Should().BeEqualTo("198.18.0.0/15");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task DnsSettings_ShouldRoundTripBothAddressRanges()
|
||||||
|
{
|
||||||
|
var settings = new SimpleDNSItem
|
||||||
|
{
|
||||||
|
FakeIP = true,
|
||||||
|
FakeIPRange = "198.18.0.0/15",
|
||||||
|
FakeIPv6 = true,
|
||||||
|
FakeIPv6Range = "2001:2::/48",
|
||||||
|
};
|
||||||
|
|
||||||
|
var restored = JsonUtils.Deserialize<SimpleDNSItem>(JsonUtils.Serialize(settings))!;
|
||||||
|
|
||||||
|
await restored.FakeIP.Should().BeEqualTo(true);
|
||||||
|
await restored.FakeIPRange.Should().BeEqualTo(settings.FakeIPRange);
|
||||||
|
await restored.FakeIPv6.Should().BeEqualTo(true);
|
||||||
|
await restored.FakeIPv6Range.Should().BeEqualTo(settings.FakeIPv6Range);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AppConfig_ShouldRoundTripIPv6Settings()
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig();
|
||||||
|
config.SimpleDNSItem.FakeIPv6 = true;
|
||||||
|
config.SimpleDNSItem.FakeIPv6Range = "2001:2::/48";
|
||||||
|
|
||||||
|
var restored = JsonUtils.Deserialize<Config>(JsonUtils.Serialize(config))!;
|
||||||
|
|
||||||
|
await restored.Should().NotBeNull();
|
||||||
|
await restored.SimpleDNSItem.FakeIPv6.Should().BeEqualTo(true);
|
||||||
|
await restored.SimpleDNSItem.FakeIPv6Range.Should().BeEqualTo("2001:2::/48");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments(false)]
|
||||||
|
[Arguments(true)]
|
||||||
|
public async Task Xray_ShouldRoundTripSingleAndDualPools(bool enableIPv6)
|
||||||
|
{
|
||||||
|
var context = CreateContext(ECoreType.Xray, enableIPv6, false);
|
||||||
|
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue();
|
||||||
|
var restored = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
|
||||||
|
await restored.Should().NotBeNull();
|
||||||
|
var roundTrip = JsonUtils.ParseJson(JsonUtils.Serialize(restored))!;
|
||||||
|
var original = JsonUtils.ParseJson(result.Data!.ToString())!;
|
||||||
|
await JsonNode.DeepEquals(original["fakedns"], roundTrip["fakedns"]).Should().BeTrue();
|
||||||
|
await (restored.fakedns is JsonArray).Should().BeEqualTo(enableIPv6);
|
||||||
|
await restored.fakedns.Should().NotBeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments(false, false)]
|
||||||
|
[Arguments(true, false)]
|
||||||
|
[Arguments(true, true)]
|
||||||
|
public async Task Xray_ShouldAddIPv6OnlyWhenEnabledAndAAAAAllowed(bool enableIPv6, bool blockAAAA)
|
||||||
|
{
|
||||||
|
var context = CreateContext(ECoreType.Xray, enableIPv6, blockAAAA);
|
||||||
|
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue();
|
||||||
|
var root = JsonUtils.ParseJson(result.Data!.ToString())!;
|
||||||
|
var dualStack = enableIPv6 && !blockAAAA;
|
||||||
|
await (root["fakedns"] is JsonArray).Should().BeEqualTo(dualStack);
|
||||||
|
var pool = dualStack ? root["fakedns"]![0]! : root["fakedns"]!;
|
||||||
|
await pool["ipPool"]!.GetValue<string>().Should().BeEqualTo("198.18.0.0/15");
|
||||||
|
if (dualStack)
|
||||||
|
{
|
||||||
|
await root["fakedns"]!.AsArray().Count.Should().BeEqualTo(2);
|
||||||
|
await root["fakedns"]![1]!["ipPool"]!.GetValue<string>().Should().BeEqualTo("2001:2::/48");
|
||||||
|
await root["fakedns"]![1]!["poolSize"]!.GetValue<long>().Should().BeEqualTo(65535L);
|
||||||
|
}
|
||||||
|
if (blockAAAA)
|
||||||
|
{
|
||||||
|
await root["dns"]!["queryStrategy"]!.GetValue<string>().Should().BeEqualTo("UseIPv4");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments(false, false)]
|
||||||
|
[Arguments(true, false)]
|
||||||
|
[Arguments(true, true)]
|
||||||
|
public async Task Singbox_ShouldAddIPv6OnlyWhenEnabledAndAAAAAllowed(bool enableIPv6, bool blockAAAA)
|
||||||
|
{
|
||||||
|
var context = CreateContext(ECoreType.sing_box, enableIPv6, blockAAAA);
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue();
|
||||||
|
var config = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
var fakeDns = config.dns.servers.Single(server => server.type == "fakeip");
|
||||||
|
|
||||||
|
await fakeDns.inet4_range.Should().BeEqualTo("198.18.0.0/15");
|
||||||
|
await fakeDns.inet6_range.Should().BeEqualTo(enableIPv6 && !blockAAAA ? "2001:2::/48" : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task DisabledFakeIP_ShouldNotCreateEitherPool()
|
||||||
|
{
|
||||||
|
foreach (var coreType in new[] { ECoreType.Xray, ECoreType.sing_box })
|
||||||
|
{
|
||||||
|
var context = CreateContext(coreType, true, false);
|
||||||
|
context.AppConfig.SimpleDNSItem.FakeIP = false;
|
||||||
|
var result = coreType == ECoreType.Xray
|
||||||
|
? new CoreConfigV2rayService(context).GenerateClientConfigContent()
|
||||||
|
: new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue();
|
||||||
|
var root = JsonUtils.ParseJson(result.Data!.ToString())!;
|
||||||
|
await root["fakedns"].Should().BeNull();
|
||||||
|
await root["dns"]!["servers"]!.AsArray()
|
||||||
|
.Any(server => server is JsonObject obj && obj["type"]?.GetValue<string>() == "fakeip")
|
||||||
|
.Should().BeFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CoreConfigContext CreateContext(ECoreType coreType, bool enableIPv6, bool blockAAAA)
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(coreType);
|
||||||
|
config.SimpleDNSItem.FakeIP = true;
|
||||||
|
config.SimpleDNSItem.FakeIPRange = "198.18.0.0/15";
|
||||||
|
config.SimpleDNSItem.FakeIPv6 = enableIPv6;
|
||||||
|
config.SimpleDNSItem.FakeIPv6Range = "2001:2::/48";
|
||||||
|
config.SimpleDNSItem.BlockAAAAQuery = blockAAAA;
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
var node = CoreConfigTestFactory.CreateVmessNode(coreType);
|
||||||
|
return CoreConfigTestFactory.CreateContext(config, node, coreType) with
|
||||||
|
{
|
||||||
|
RoutingItem = new RoutingItem
|
||||||
|
{
|
||||||
|
Id = "fakeip-test",
|
||||||
|
Remarks = "FakeIP test",
|
||||||
|
DomainStrategy = Global.AsIs,
|
||||||
|
DomainStrategy4Singbox = string.Empty,
|
||||||
|
RuleSet = JsonUtils.Serialize(new List<RulesItem>
|
||||||
|
{
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
Enabled = true,
|
||||||
|
RuleType = ERuleType.DNS,
|
||||||
|
OutboundTag = Global.ProxyTag,
|
||||||
|
Domain = ["full:example.com"],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,17 +1,9 @@
|
|||||||
using AwesomeAssertions;
|
|
||||||
using ServiceLib.Common;
|
|
||||||
using ServiceLib.Enums;
|
|
||||||
using ServiceLib.Manager;
|
|
||||||
using ServiceLib.Models;
|
|
||||||
using ServiceLib.Services.CoreConfig;
|
|
||||||
using Xunit;
|
|
||||||
|
|
||||||
namespace ServiceLib.Tests.CoreConfig.Singbox;
|
namespace ServiceLib.Tests.CoreConfig.Singbox;
|
||||||
|
|
||||||
public class CoreConfigSingboxServiceTests
|
public class CoreConfigSingboxServiceTests
|
||||||
{
|
{
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_ShouldGenerateBasicProxyConfig()
|
public async Task GenerateClientConfigContent_ShouldGenerateBasicProxyConfig()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
@@ -20,17 +12,17 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
result.Data.Should().NotBeNull();
|
await result.Data.Should().NotBeNull();
|
||||||
|
|
||||||
var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString());
|
var singboxConfig = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString());
|
||||||
singboxConfig.Should().NotBeNull();
|
await singboxConfig.Should().NotBeNull();
|
||||||
singboxConfig!.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "socks");
|
await singboxConfig!.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "socks");
|
||||||
singboxConfig.inbounds.Should().Contain(i => i.type == nameof(EInboundProtocol.mixed));
|
await singboxConfig.inbounds.Should().Contain(i => i.type == nameof(EInboundProtocol.mixed));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_TunWithLoopbackPreSocks_ShouldKeepMixedInbound()
|
public async Task GenerateClientConfigContent_TunWithLoopbackPreSocks_ShouldKeepMixedInbound()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
@@ -44,18 +36,166 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
cfg.inbounds.Should().Contain(i =>
|
await cfg.inbounds.Should().Contain(i =>
|
||||||
i.type == nameof(EInboundProtocol.mixed)
|
i.type == nameof(EInboundProtocol.mixed)
|
||||||
&& i.listen == Global.Loopback
|
&& i.listen == Global.Loopback
|
||||||
&& i.listen_port == AppManager.Instance.GetLocalPort(EInboundProtocol.socks));
|
&& i.listen_port == AppManager.Instance.GetLocalPort(EInboundProtocol.socks));
|
||||||
cfg.inbounds.Should().Contain(i => i.type == "tun");
|
await cfg.inbounds.Should().Contain(i => i.type == "tun");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_BindInterface_ShouldUseDialBindInterface()
|
[Arguments(null)]
|
||||||
|
[Arguments("Default")]
|
||||||
|
public async Task GenerateClientConfigContent_TunDnsModeDefault_ShouldNotIncludeDnsMode(string? dnsMode)
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.TunModeItem.EnableTun = true;
|
||||||
|
config.TunModeItem.DnsMode = dnsMode;
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
|
||||||
|
{
|
||||||
|
IsTunEnabled = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
await result.Data!.ToString().Should().NotContain("\"dns_mode\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_TunDnsModeDisabled_ShouldIncludeDnsMode()
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.TunModeItem.EnableTun = true;
|
||||||
|
config.TunModeItem.DnsMode = "disabled";
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
|
||||||
|
{
|
||||||
|
IsTunEnabled = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
var tun = cfg.inbounds.First(i => i.type == "tun");
|
||||||
|
await tun.dns_mode.Should().BeEqualTo("disabled");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments(true)]
|
||||||
|
[Arguments(false)]
|
||||||
|
public async Task GenerateClientConfigContent_TunDnsModeDisabled_ShouldNotIncludeGlobalDnsHijackRule(bool sniffingEnabled)
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.TunModeItem.EnableTun = true;
|
||||||
|
config.TunModeItem.DnsMode = "disabled";
|
||||||
|
config.Inbound.First().SniffingEnabled = sniffingEnabled;
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
|
||||||
|
{
|
||||||
|
IsTunEnabled = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
await cfg.route.rules.Any(
|
||||||
|
r => r.action == "hijack-dns" && r.process_path == null).Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_TunEnabled_ShouldKeepEmbeddedTunRules()
|
||||||
|
{
|
||||||
|
// The embedded tun rules reject local-network noise (NetBIOS/mDNS, multicast).
|
||||||
|
// They are deserialized into List<Rule4Sbox>, so a schema mismatch in the
|
||||||
|
// embedded template makes JsonUtils.Deserialize return null and silently
|
||||||
|
// drops every one of them.
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.TunModeItem.EnableTun = true;
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
|
||||||
|
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.sing_box);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
|
||||||
|
{
|
||||||
|
IsTunEnabled = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
|
await cfg.route.rules.Should().Contain(
|
||||||
|
r => r.action == "reject"
|
||||||
|
&& r.network != null && r.network.Contains("udp")
|
||||||
|
&& r.port != null && r.port.Contains(5353),
|
||||||
|
"the embedded tun rules must reject mDNS/NetBIOS noise");
|
||||||
|
await cfg.route.rules.Should().Contain(
|
||||||
|
r => r.action == "reject"
|
||||||
|
&& r.ip_cidr != null && r.ip_cidr.Contains("224.0.0.0/3"),
|
||||||
|
"the embedded tun rules must reject multicast traffic");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_TunEnabled_ShouldRejectTrafficToTunOwnAddresses()
|
||||||
|
{
|
||||||
|
// Regression test: traffic addressed to the TUN interface's own addresses must
|
||||||
|
// never reach an outbound. auto_route hijacks the default route, so `direct`
|
||||||
|
// writes such a packet straight back into the TUN, which routes it to the
|
||||||
|
// outbound again - an infinite loop that pins a CPU core. Observed in the wild
|
||||||
|
// with WebRTC ICE connectivity checks against the TUN's own fc00::/7 ULA
|
||||||
|
// address, sustaining ~8k packets/s out of the TUN interface.
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.TunModeItem.EnableTun = true;
|
||||||
|
config.TunModeItem.EnableIPv6Address = true;
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
|
||||||
|
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.sing_box);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
|
||||||
|
{
|
||||||
|
IsTunEnabled = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
var tun = cfg.inbounds.First(i => i.type == "tun");
|
||||||
|
//tun.address.Should().NotBeNullOrEmpty();
|
||||||
|
await tun.address.Should().NotBeNull();
|
||||||
|
await tun.address.Should().NotBeEmpty();
|
||||||
|
|
||||||
|
foreach (var address in tun.address!)
|
||||||
|
{
|
||||||
|
var self = IPAddress.Parse(address.Split('/').First());
|
||||||
|
var hostBits = self.AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32;
|
||||||
|
var expected = $"{self}/{hostBits}";
|
||||||
|
await cfg.route.rules.Should().Contain(
|
||||||
|
r => r.action == "reject" && r.ip_cidr != null && r.ip_cidr.Contains(expected),
|
||||||
|
$"traffic to the TUN's own address '{address}' must be rejected, not routed");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The match has to stay on the addresses themselves. sing-tun derives the TUN's DNS
|
||||||
|
// entry from the address right after the interface's own, and every prefix offered
|
||||||
|
// here leaves room for it, so a prefix match would drop system name lookups too.
|
||||||
|
var dropRule = cfg.route.rules.First(r =>
|
||||||
|
r.action == "reject" && r.method == "drop" && r.ip_cidr?.Count > 0);
|
||||||
|
//dropRule.ip_cidr!.Should().OnlyContain(c =>
|
||||||
|
// c.EndsWith("/32", StringComparison.Ordinal) || c.EndsWith("/128", StringComparison.Ordinal));
|
||||||
|
await dropRule.ip_cidr.Should().All(c => c.EndsWith("/32", StringComparison.Ordinal) || c.EndsWith("/128", StringComparison.Ordinal));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_BindInterface_ShouldUseDialBindInterface()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
config.CoreBasicItem.BindInterface = "eth0";
|
config.CoreBasicItem.BindInterface = "eth0";
|
||||||
@@ -69,16 +209,16 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
var proxy = cfg.outbounds.First(o => o.tag == Global.ProxyTag);
|
var proxy = cfg.outbounds.First(o => o.tag == Global.ProxyTag);
|
||||||
|
|
||||||
proxy.bind_interface.Should().Be("eth0");
|
await proxy.bind_interface.Should().BeEqualTo("eth0");
|
||||||
proxy.detour.Should().BeNullOrEmpty();
|
await proxy.detour.Should().BeNull().Or.BeEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_PolicyGroup_ShouldExpandChildrenAndBuildSelector()
|
public async Task GenerateClientConfigContent_PolicyGroup_ShouldExpandChildrenAndBuildSelector()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
@@ -95,17 +235,17 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "selector");
|
await cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "selector");
|
||||||
cfg.outbounds.Should().Contain(o => o.tag == $"{Global.ProxyTag}-auto" && o.type == "urltest");
|
await cfg.outbounds.Should().Contain(o => o.tag == $"{Global.ProxyTag}-auto" && o.type == "urltest");
|
||||||
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-1-", StringComparison.Ordinal));
|
await cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-1-", StringComparison.Ordinal));
|
||||||
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-2-", StringComparison.Ordinal));
|
await cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-2-", StringComparison.Ordinal));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_ProxyChain_ShouldBuildDetourChain()
|
public async Task GenerateClientConfigContent_ProxyChain_ShouldBuildDetourChain()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
@@ -122,18 +262,18 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "socks");
|
await cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "socks");
|
||||||
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-", StringComparison.Ordinal));
|
await cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-", StringComparison.Ordinal));
|
||||||
cfg.outbounds.Should().Contain(o =>
|
await cfg.outbounds.Should().Contain(o =>
|
||||||
o.tag == Global.ProxyTag &&
|
o.tag == Global.ProxyTag &&
|
||||||
(o.detour ?? string.Empty).StartsWith("chain-proxy-1-", StringComparison.Ordinal));
|
(o.detour ?? string.Empty).StartsWith("chain-proxy-1-", StringComparison.Ordinal));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_PolicyGroupWithProxyChain_ShouldBuildCombinedOutbounds()
|
public async Task GenerateClientConfigContent_PolicyGroupWithProxyChain_ShouldBuildCombinedOutbounds()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
@@ -155,18 +295,18 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "selector");
|
await cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "selector");
|
||||||
cfg.outbounds.Should().Contain(o => o.tag == $"{Global.ProxyTag}-auto" && o.type == "urltest");
|
await cfg.outbounds.Should().Contain(o => o.tag == $"{Global.ProxyTag}-auto" && o.type == "urltest");
|
||||||
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-1-", StringComparison.Ordinal));
|
await cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-1-", StringComparison.Ordinal));
|
||||||
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-", StringComparison.Ordinal));
|
await cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-", StringComparison.Ordinal));
|
||||||
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-2-", StringComparison.Ordinal));
|
await cfg.outbounds.Should().Contain(o => o.tag.StartsWith("proxy-2-", StringComparison.Ordinal));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_ProxyChainWithPolicyGroup_ShouldBuildClonedChainBranches()
|
public async Task GenerateClientConfigContent_ProxyChainWithPolicyGroup_ShouldBuildClonedChainBranches()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
@@ -188,25 +328,25 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "selector");
|
await cfg.outbounds.Should().Contain(o => o.tag == Global.ProxyTag && o.type == "selector");
|
||||||
cfg.outbounds.Should().Contain(o => o.tag == $"{Global.ProxyTag}-auto" && o.type == "urltest");
|
await cfg.outbounds.Should().Contain(o => o.tag == $"{Global.ProxyTag}-auto" && o.type == "urltest");
|
||||||
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-group-1-", StringComparison.Ordinal));
|
await cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-group-1-", StringComparison.Ordinal));
|
||||||
cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-group-2-", StringComparison.Ordinal));
|
await cfg.outbounds.Should().Contain(o => o.tag.StartsWith("chain-proxy-1-group-2-", StringComparison.Ordinal));
|
||||||
|
|
||||||
var proxyCloneCount = cfg.outbounds.Count(o => o.tag.StartsWith("proxy-clone-", StringComparison.Ordinal));
|
var proxyCloneCount = cfg.outbounds.Count(o => o.tag.StartsWith("proxy-clone-", StringComparison.Ordinal));
|
||||||
proxyCloneCount.Should().Be(2);
|
await proxyCloneCount.Should().BeEqualTo(2);
|
||||||
|
|
||||||
var allCloneDetoursPointToGroupBranches = cfg.outbounds
|
var allCloneDetoursPointToGroupBranches = cfg.outbounds
|
||||||
.Where(o => o.tag.StartsWith("proxy-clone-", StringComparison.Ordinal))
|
.Where(o => o.tag.StartsWith("proxy-clone-", StringComparison.Ordinal))
|
||||||
.All(o => (o.detour ?? string.Empty).StartsWith("chain-proxy-1-group-", StringComparison.Ordinal));
|
.All(o => (o.detour ?? string.Empty).StartsWith("chain-proxy-1-group-", StringComparison.Ordinal));
|
||||||
allCloneDetoursPointToGroupBranches.Should().BeTrue();
|
await allCloneDetoursPointToGroupBranches.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_RoutingSplit_DirectAndBlock_ShouldApplyRules()
|
public async Task GenerateClientConfigContent_RoutingSplit_DirectAndBlock_ShouldApplyRules()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
@@ -242,24 +382,24 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
var hasDirectRule = cfg.route.rules.Any(r =>
|
var hasDirectRule = cfg.route.rules.Any(r =>
|
||||||
r.domain != null
|
r.domain != null
|
||||||
&& r.domain.Contains("direct.example.com")
|
&& r.domain.Contains("direct.example.com")
|
||||||
&& r.outbound == Global.DirectTag);
|
&& r.outbound == Global.DirectTag);
|
||||||
hasDirectRule.Should().BeTrue();
|
await hasDirectRule.Should().BeTrue();
|
||||||
|
|
||||||
var hasBlockRule = cfg.route.rules.Any(r =>
|
var hasBlockRule = cfg.route.rules.Any(r =>
|
||||||
r.domain != null
|
r.domain != null
|
||||||
&& r.domain.Contains("block.example.com")
|
&& r.domain.Contains("block.example.com")
|
||||||
&& r.action == "reject");
|
&& r.action == "reject");
|
||||||
hasBlockRule.Should().BeTrue();
|
await hasBlockRule.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_RoutingSplit_ByRemark_ShouldGenerateTargetOutbound()
|
public async Task GenerateClientConfigContent_RoutingSplit_ByRemark_ShouldGenerateTargetOutbound()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
@@ -291,65 +431,21 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
var expectedPrefix = $"{routeNode.IndexId}-{Global.ProxyTag}-{routeNode.Remarks}";
|
var expectedPrefix = $"{routeNode.IndexId}-{Global.ProxyTag}-{routeNode.Remarks}";
|
||||||
|
|
||||||
cfg.outbounds.Should().Contain(o => o.tag.StartsWith(expectedPrefix, StringComparison.Ordinal));
|
await cfg.outbounds.Should().Contain(o => o.tag.StartsWith(expectedPrefix, StringComparison.Ordinal));
|
||||||
|
|
||||||
var hasRouteRule = cfg.route.rules.Any(r =>
|
var hasRouteRule = cfg.route.rules.Any(r =>
|
||||||
r.domain != null
|
r.domain != null
|
||||||
&& r.domain.Contains("route.example.com")
|
&& r.domain.Contains("route.example.com")
|
||||||
&& (r.outbound ?? string.Empty).StartsWith(expectedPrefix, StringComparison.Ordinal));
|
&& (r.outbound ?? string.Empty).StartsWith(expectedPrefix, StringComparison.Ordinal));
|
||||||
hasRouteRule.Should().BeTrue();
|
await hasRouteRule.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_DirectExpectedIPs_ShouldApplyGeoipAndCidrToDirectDnsRule()
|
public async Task GenerateClientConfigContent_BootstrapDNS_ShouldConfigurePureIPResolver()
|
||||||
{
|
|
||||||
var config = CoreConfigTestFactory.CreateConfigWithDirectExpectedIPs(
|
|
||||||
ECoreType.sing_box,
|
|
||||||
"192.168.0.0/16,geoip:cn");
|
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
|
||||||
|
|
||||||
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
|
|
||||||
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
|
|
||||||
{
|
|
||||||
RoutingItem = new RoutingItem
|
|
||||||
{
|
|
||||||
Id = "r-dns-direct-expected",
|
|
||||||
Remarks = "dns-direct-expected",
|
|
||||||
RuleSet = JsonUtils.Serialize(new List<RulesItem>
|
|
||||||
{
|
|
||||||
new()
|
|
||||||
{
|
|
||||||
Enabled = true,
|
|
||||||
RuleType = ERuleType.DNS,
|
|
||||||
OutboundTag = Global.DirectTag,
|
|
||||||
Domain = ["geosite:cn"],
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
DomainStrategy = Global.AsIs,
|
|
||||||
DomainStrategy4Singbox = string.Empty,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
|
||||||
|
|
||||||
var hasExpectedRule = cfg.dns.rules?.Any(r =>
|
|
||||||
r.server == Global.SingboxDirectDNSTag
|
|
||||||
&& r.ip_cidr?.Contains("192.168.0.0/16") == true
|
|
||||||
&& r.rule_set?.Contains("geosite-cn") == true
|
|
||||||
&& r.rule_set?.Contains("geoip-cn") == true) ?? false;
|
|
||||||
|
|
||||||
hasExpectedRule.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GenerateClientConfigContent_BootstrapDNS_ShouldConfigurePureIPResolver()
|
|
||||||
{
|
{
|
||||||
var bootstrapDns = "8.8.8.8";
|
var bootstrapDns = "8.8.8.8";
|
||||||
var config = CoreConfigTestFactory.CreateConfigWithBootstrapDNS(ECoreType.sing_box, bootstrapDns);
|
var config = CoreConfigTestFactory.CreateConfigWithBootstrapDNS(ECoreType.sing_box, bootstrapDns);
|
||||||
@@ -360,17 +456,17 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
config.SimpleDNSItem.BootstrapDNS.Should().Be(bootstrapDns);
|
await config.SimpleDNSItem.BootstrapDNS.Should().BeEqualTo(bootstrapDns);
|
||||||
|
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
var bootstrapServer = cfg.dns.servers?.FirstOrDefault(s => s.tag == Global.SingboxLocalDNSTag);
|
var bootstrapServer = cfg.dns?.servers.FirstOrDefault(s => s.tag == Global.SingboxLocalDNSTag);
|
||||||
bootstrapServer.Should().NotBeNull();
|
await bootstrapServer.Should().NotBeNull();
|
||||||
(bootstrapServer?.server ?? string.Empty).Should().Contain(bootstrapDns);
|
await bootstrapServer!.server.Should().Contain(bootstrapDns);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_DnsFallback_LastRuleDirect_ShouldUseDirectFinalDns()
|
public async Task GenerateClientConfigContent_DnsFallback_LastRuleDirect_ShouldUseDirectFinalDns()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
config.SimpleDNSItem.DirectDNS = "1.1.1.1";
|
config.SimpleDNSItem.DirectDNS = "1.1.1.1";
|
||||||
@@ -403,14 +499,14 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
cfg.dns.final.Should().Be(Global.SingboxDirectDNSTag);
|
await cfg.dns.final.Should().BeEqualTo(Global.SingboxDirectDNSTag);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_DirectExpectedIPs_NonMatchingRegion_ShouldNotApplyExpectedRule()
|
public async Task GenerateClientConfigContent_DirectExpectedIPs_NonMatchingRegion_ShouldNotApplyExpectedRule()
|
||||||
{
|
{
|
||||||
var config =
|
var config =
|
||||||
CoreConfigTestFactory.CreateConfigWithDirectExpectedIPs(ECoreType.sing_box, "192.168.0.0/16,geoip:cn");
|
CoreConfigTestFactory.CreateConfigWithDirectExpectedIPs(ECoreType.sing_box, "192.168.0.0/16,geoip:cn");
|
||||||
@@ -440,21 +536,21 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
var hasExpectedRule = cfg.dns.rules?.Any(r =>
|
var hasExpectedRule = cfg.dns.rules?.Any(r =>
|
||||||
r.server == Global.SingboxDirectDNSTag
|
r.server == Global.SingboxDirectDNSTag
|
||||||
&& r.ip_cidr?.Contains("192.168.0.0/16") == true
|
&& r.ip_cidr?.Contains("192.168.0.0/16") == true
|
||||||
&& r.rule_set?.Contains("geoip-cn") == true) ?? false;
|
&& r.rule_set?.Contains("geoip-cn") == true) ?? false;
|
||||||
hasExpectedRule.Should().BeFalse();
|
await hasExpectedRule.Should().BeFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Test]
|
||||||
[InlineData("geosite:cn", "geosite-cn")]
|
[Arguments("geosite:cn", "geosite-cn")]
|
||||||
[InlineData("geosite:geolocation-cn", "geosite-geolocation-cn")]
|
[Arguments("geosite:geolocation-cn", "geosite-geolocation-cn")]
|
||||||
[InlineData("geosite:tld-cn", "geosite-tld-cn")]
|
[Arguments("geosite:tld-cn", "geosite-tld-cn")]
|
||||||
public void GenerateClientConfigContent_DirectExpectedIPs_RegionVariant_ShouldApplyExpectedRule(string domainTag,
|
public async Task GenerateClientConfigContent_DirectExpectedIPs_RegionVariant_ShouldApplyExpectedRule(string domainTag,
|
||||||
string expectedRuleSetTag)
|
string expectedRuleSetTag)
|
||||||
{
|
{
|
||||||
var config =
|
var config =
|
||||||
@@ -470,31 +566,38 @@ public class CoreConfigSingboxServiceTests
|
|||||||
Remarks = "dns-direct-variant",
|
Remarks = "dns-direct-variant",
|
||||||
RuleSet = JsonUtils.Serialize(new List<RulesItem>
|
RuleSet = JsonUtils.Serialize(new List<RulesItem>
|
||||||
{
|
{
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
Enabled = true, RuleType = ERuleType.DNS, OutboundTag = Global.ProxyTag, Domain = ["geosite:google"],
|
||||||
|
},
|
||||||
new()
|
new()
|
||||||
{
|
{
|
||||||
Enabled = true, RuleType = ERuleType.DNS, OutboundTag = Global.DirectTag, Domain = [domainTag],
|
Enabled = true, RuleType = ERuleType.DNS, OutboundTag = Global.DirectTag, Domain = [domainTag],
|
||||||
}
|
},
|
||||||
}),
|
}),
|
||||||
DomainStrategy = Global.AsIs,
|
DomainStrategy = Global.AsIs,
|
||||||
DomainStrategy4Singbox = string.Empty,
|
DomainStrategy4Singbox = string.Empty,
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
var hasExpectedRule = cfg.dns.rules?.Any(r =>
|
var hasExpectedRule = (cfg.dns.rules?.Any(r =>
|
||||||
r.server == Global.SingboxDirectDNSTag
|
r.ip_cidr?.Contains("192.168.0.0/16") == true
|
||||||
&& r.ip_cidr?.Contains("192.168.0.0/16") == true
|
&& r.action == "respond"
|
||||||
&& r.rule_set?.Contains(expectedRuleSetTag) == true
|
&& r.rule_set?.Contains("geoip-cn") == true) ?? false)
|
||||||
&& r.rule_set?.Contains("geoip-cn") == true) ?? false;
|
&& (cfg.dns.rules?.Any(r =>
|
||||||
hasExpectedRule.Should().BeTrue();
|
r.server == Global.SingboxDirectDNSTag
|
||||||
|
&& r.rule_set?.Contains(expectedRuleSetTag) == true
|
||||||
|
&& r.action == "evaluate") ?? false);
|
||||||
|
await hasExpectedRule.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_Hosts_ShouldPopulateHostsServerAndDomainResolver()
|
public async Task GenerateClientConfigContent_Hosts_ShouldPopulateHostsServerAndDomainResolver()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
config.SimpleDNSItem.Hosts = "resolver.example 1.1.1.1";
|
config.SimpleDNSItem.Hosts = "resolver.example 1.1.1.1";
|
||||||
@@ -506,21 +609,21 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
var hostsServer = cfg.dns.servers.FirstOrDefault(s => s.tag == Global.SingboxHostsDNSTag);
|
var hostsServer = cfg.dns.servers.FirstOrDefault(s => s.tag == Global.SingboxHostsDNSTag);
|
||||||
hostsServer.Should().NotBeNull();
|
await hostsServer.Should().NotBeNull();
|
||||||
hostsServer!.predefined.Should().ContainKey("resolver.example");
|
await hostsServer!.predefined.Should().ContainKey("resolver.example");
|
||||||
hostsServer.predefined!["resolver.example"].Should().Contain("1.1.1.1");
|
await hostsServer.predefined!["resolver.example"].Should().Contain("1.1.1.1");
|
||||||
|
|
||||||
var directServer = cfg.dns.servers.FirstOrDefault(s => s.tag == Global.SingboxDirectDNSTag);
|
var directServer = cfg.dns.servers.FirstOrDefault(s => s.tag == Global.SingboxDirectDNSTag);
|
||||||
directServer.Should().NotBeNull();
|
await directServer.Should().NotBeNull();
|
||||||
directServer!.domain_resolver.Should().Be(Global.SingboxHostsDNSTag);
|
await directServer!.domain_resolver.Should().BeEqualTo(Global.SingboxHostsDNSTag);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GenerateClientConfigContent_RawDnsEnabled_ShouldUseCustomDnsAndInjectLocalResolver()
|
public async Task GenerateClientConfigContent_RawDnsEnabled_ShouldUseCustomDnsAndInjectLocalResolver()
|
||||||
{
|
{
|
||||||
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
CoreConfigTestFactory.BindAppManagerConfig(config);
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
@@ -549,12 +652,254 @@ public class CoreConfigSingboxServiceTests
|
|||||||
|
|
||||||
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
result.Success.Should().BeTrue($"ret msg: {result.Msg}");
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
cfg.dns.servers.Should().Contain(s => s.tag == "remote" && s.type == "udp" && s.server == "8.8.8.8");
|
await cfg.dns.servers.Should().Contain(s => s.tag == "remote" && s.type == "udp" && s.server == "8.8.8.8");
|
||||||
cfg.dns.servers.Should().Contain(s => s.tag == Global.SingboxLocalDNSTag);
|
await cfg.dns.servers.Should().Contain(s => s.tag == Global.SingboxLocalDNSTag);
|
||||||
cfg.dns.rules.Should().Contain(r => r.clash_mode == nameof(ERuleMode.Global));
|
await cfg.dns.rules.Should().Contain(r => r.clash_mode == nameof(ERuleMode.Global));
|
||||||
cfg.dns.rules.Should().Contain(r => r.clash_mode == nameof(ERuleMode.Direct));
|
await cfg.dns.rules.Should().Contain(r => r.clash_mode == nameof(ERuleMode.Direct));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments(true)]
|
||||||
|
[Arguments(false)]
|
||||||
|
public async Task GenerateClientConfigContent_MultiDnsServers_ShouldIncludeAllServers(bool parallelQuery)
|
||||||
|
{
|
||||||
|
var config =
|
||||||
|
CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.SimpleDNSItem.ParallelQuery = parallelQuery;
|
||||||
|
config.SimpleDNSItem.DirectDNS = "1.1.1.1,2.2.2.2";
|
||||||
|
config.SimpleDNSItem.RemoteDNS = "3.3.3.3,4.4.4.4";
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
|
||||||
|
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box, "n-main", "main");
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
|
||||||
|
{
|
||||||
|
RoutingItem = new RoutingItem
|
||||||
|
{
|
||||||
|
Id = "r-dns-direct-variant",
|
||||||
|
Remarks = "dns-direct-variant",
|
||||||
|
RuleSet = JsonUtils.Serialize(new List<RulesItem>
|
||||||
|
{
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
Enabled = true,
|
||||||
|
RuleType = ERuleType.DNS,
|
||||||
|
OutboundTag = Global.ProxyTag,
|
||||||
|
Domain = ["geosite:google"],
|
||||||
|
},
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
Enabled = true,
|
||||||
|
RuleType = ERuleType.DNS,
|
||||||
|
OutboundTag = Global.DirectTag,
|
||||||
|
Domain = ["geosite:cn"],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
DomainStrategy = Global.AsIs,
|
||||||
|
DomainStrategy4Singbox = string.Empty,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
|
await cfg.dns.servers.Where(s => s.tag.StartsWith(Global.SingboxDirectDNSTagPrefix)).Should().HaveCount(2);
|
||||||
|
await cfg.dns.servers.Where(s => s.tag.StartsWith(Global.SingboxRemoteDNSTagPrefix)).Should().HaveCount(2);
|
||||||
|
if (parallelQuery)
|
||||||
|
{
|
||||||
|
await cfg.dns.rules.Should().Contain(r => r.race == true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments("5-15", "5s", "15s")]
|
||||||
|
[Arguments("20-25", "20s", "25s")]
|
||||||
|
[Arguments("15", "15s", null)]
|
||||||
|
[Arguments("4-10", "30s", null)]
|
||||||
|
[Arguments("15-5", "30s", null)]
|
||||||
|
public async Task GenerateClientConfigContent_Hysteria2HopInterval_ShouldPreserveRange(string interval, string expected, string? expectedMax)
|
||||||
|
{
|
||||||
|
var node = Hysteria2Fmt.Resolve("hysteria2://password@example.com:443?mport=20000-50000", out _)!;
|
||||||
|
node.CoreType = ECoreType.sing_box;
|
||||||
|
node.SetProtocolExtra(node.GetProtocolExtra() with { HopInterval = interval });
|
||||||
|
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.HysteriaItem.HopInterval = 30;
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box);
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
var proxy = cfg.outbounds.First(o => o.tag == Global.ProxyTag);
|
||||||
|
await proxy.hop_interval.Should().BeEqualTo(expected);
|
||||||
|
await proxy.hop_interval_max.Should().BeEqualTo(expectedMax);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_Hysteria2Realm_ShouldEmitHttpsServerUrl()
|
||||||
|
{
|
||||||
|
var shareLink =
|
||||||
|
"hysteria2+realm://public@realm.hy2.io/my-realm-id?auth=uuid&stun=turn.cloudflare.com%3A3478&sni=cloudflare.com&pinSHA256=xxx#Realm-Test";
|
||||||
|
var node = Hysteria2Fmt.ResolveRealm(shareLink, out _);
|
||||||
|
await node.Should().NotBeNull();
|
||||||
|
node!.CoreType = ECoreType.sing_box;
|
||||||
|
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.CoreTypeItem =
|
||||||
|
[
|
||||||
|
new CoreTypeItem { ConfigType = EConfigType.Hysteria2, CoreType = ECoreType.sing_box }
|
||||||
|
];
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box);
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
var proxy = cfg.outbounds.First(o => o.tag == Global.ProxyTag);
|
||||||
|
|
||||||
|
await proxy.type.Should().BeEqualTo("hysteria2");
|
||||||
|
await proxy.realm.Should().NotBeNull();
|
||||||
|
await proxy.realm!.server_url.Should().StartWith("https://");
|
||||||
|
await proxy.realm.server_url.Should().Contain("realm.hy2.io");
|
||||||
|
await proxy.realm.token.Should().BeEqualTo("public");
|
||||||
|
await proxy.realm.realm_id.Should().BeEqualTo("my-realm-id");
|
||||||
|
await proxy.realm.stun_servers.Should().Contain("turn.cloudflare.com:3478");
|
||||||
|
await proxy.server.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_TunSystemStackWithIpv6_ShouldUsePrefixWithPeerAddress()
|
||||||
|
{
|
||||||
|
// Regression test for #9820: sing-box fails with "need one more IPv6 address in
|
||||||
|
// first prefix for system stack" when the TUN inbound uses a /128 IPv6 prefix.
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.TunModeItem.EnableTun = true;
|
||||||
|
config.TunModeItem.Stack = "system";
|
||||||
|
config.TunModeItem.EnableIPv6Address = true;
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
|
||||||
|
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.sing_box);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box) with
|
||||||
|
{
|
||||||
|
IsTunEnabled = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
var tun = cfg.inbounds.First(i => i.type == "tun");
|
||||||
|
|
||||||
|
await tun.address.Should().NotBeNull();
|
||||||
|
await tun.address.Should().NotBeEmpty();
|
||||||
|
foreach (var address in tun.address!)
|
||||||
|
{
|
||||||
|
var prefixLength = int.Parse(address[(address.LastIndexOf('/') + 1)..]);
|
||||||
|
var isIpv6 = address.Contains(':');
|
||||||
|
await prefixLength.Should().BeLessThanOrEqualTo(isIpv6 ? 126 : 30,
|
||||||
|
$"'{address}' must leave room for the peer address the system stack derives");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_CustomOutbound_ShouldReplaceWithUserCustomOutboundJson()
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
|
||||||
|
var customNode = CoreConfigTestFactory.CreateCustomOutboundNode(ECoreType.sing_box, "n-custom", "custom-singbox");
|
||||||
|
var customJsonContent = """
|
||||||
|
{
|
||||||
|
"type": "shadowsocks",
|
||||||
|
"server": "1.2.3.4",
|
||||||
|
"server_port": 8388,
|
||||||
|
"method": "aes-128-gcm",
|
||||||
|
"password": "custom_password"
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, customNode, ECoreType.sing_box);
|
||||||
|
context.CustomOutboundContent[customNode.IndexId] = customJsonContent;
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
await result.Data.Should().NotBeNull();
|
||||||
|
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString());
|
||||||
|
await cfg.Should().NotBeNull();
|
||||||
|
var proxyOutbound = cfg!.outbounds.FirstOrDefault(o => o.tag == Global.ProxyTag);
|
||||||
|
await proxyOutbound.Should().NotBeNull();
|
||||||
|
await proxyOutbound!.type.Should().BeEqualTo("shadowsocks");
|
||||||
|
await proxyOutbound.server.Should().BeEqualTo("1.2.3.4");
|
||||||
|
await proxyOutbound.server_port.Should().BeEqualTo(8388);
|
||||||
|
await proxyOutbound.method.Should().BeEqualTo("aes-128-gcm");
|
||||||
|
await proxyOutbound.password.Should().BeEqualTo("custom_password");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments("/ws?ed=2048", "/ws")]
|
||||||
|
[Arguments("/ws?ed=2048&key=value", "/ws?key=value")]
|
||||||
|
[Arguments("/ws?key=value&ed=2048", "/ws?key=value")]
|
||||||
|
[Arguments("/ws?a=1&ed=2048&b=2", "/ws?a=1&b=2")]
|
||||||
|
public async Task GenerateClientConfigContent_WsEarlyDataInPath_ShouldKeepRemainingQuery(string path, string expectedPath)
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.sing_box);
|
||||||
|
node.Network = nameof(ETransport.ws);
|
||||||
|
node.SetTransportExtra(node.GetTransportExtra() with { Path = path });
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box);
|
||||||
|
|
||||||
|
var result = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue().Because($"ret msg: {result.Msg}");
|
||||||
|
var cfg = JsonUtils.Deserialize<SingboxConfig>(result.Data!.ToString())!;
|
||||||
|
var transport = cfg.outbounds.First(o => o.tag == Global.ProxyTag).transport;
|
||||||
|
await transport.Should().NotBeNull();
|
||||||
|
await transport!.max_early_data.Should().BeEqualTo(2048);
|
||||||
|
await transport.early_data_header_name.Should().BeEqualTo("Sec-WebSocket-Protocol");
|
||||||
|
await transport.path.Should().BeEqualTo(expectedPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientSpeedtestConfig_ShouldInheritProxyDialStrategy()
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.sing_box);
|
||||||
|
config.SimpleDNSItem.Strategy4ProxyDial = "UseIPv6v4";
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
|
||||||
|
var node = CoreConfigTestFactory.CreateSocksNode(ECoreType.sing_box);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.sing_box);
|
||||||
|
|
||||||
|
var normal = new CoreConfigSingboxService(context).GenerateClientConfigContent();
|
||||||
|
await normal.Success.Should().BeTrue().Because($"ret msg: {normal.Msg}");
|
||||||
|
var normalCfg = JsonUtils.Deserialize<SingboxConfig>(normal.Data!.ToString())!;
|
||||||
|
await normalCfg.route.default_domain_resolver!.strategy.Should().BeEqualTo("prefer_ipv6");
|
||||||
|
|
||||||
|
var speedtest = new CoreConfigSingboxService(context).GenerateClientSpeedtestConfig(
|
||||||
|
[
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
IndexId = node.IndexId,
|
||||||
|
Address = node.Address,
|
||||||
|
Port = node.Port,
|
||||||
|
ConfigType = node.ConfigType,
|
||||||
|
Profile = node,
|
||||||
|
CoreType = ECoreType.sing_box,
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
|
||||||
|
await speedtest.Success.Should().BeTrue().Because($"ret msg: {speedtest.Msg}");
|
||||||
|
var speedtestCfg = JsonUtils.Deserialize<SingboxConfig>(speedtest.Data!.ToString())!;
|
||||||
|
await speedtestCfg.route.default_domain_resolver.Should().NotBeNull();
|
||||||
|
await speedtestCfg.route.default_domain_resolver!.strategy.Should().BeEqualTo("prefer_ipv6");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
namespace ServiceLib.Tests.CoreConfig.V2ray;
|
||||||
|
|
||||||
|
public class CoreConfigV2rayIPNetworkTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments("0.0.0.0/0", "::/0")]
|
||||||
|
[Arguments("::/0", "0.0.0.0/0")]
|
||||||
|
[Arguments("0.0.0.0/1", "128.0.0.0/1,::/0")]
|
||||||
|
[Arguments("::/1", "0.0.0.0/0,8000::/1")]
|
||||||
|
public async Task GenerateClientConfigContent_TunExclusion_ShouldPreserveRemainingRoutes(
|
||||||
|
string excludedNetwork, string expectedRoutes)
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfigWithTun(ECoreType.Xray, true);
|
||||||
|
config.TunModeItem.RouteExcludeAddress = [excludedNetwork];
|
||||||
|
var generated = await GenerateConfig(config);
|
||||||
|
|
||||||
|
var routes = generated.inbounds.Single(i => i.protocol == "tun").settings.autoSystemRoutingTable;
|
||||||
|
await routes.Should().BeEquivalentTo(expectedRoutes.Split(','), StringComparer.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_TunExclusions_ShouldHandleOverlappingAndDuplicateNetworks()
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfigWithTun(ECoreType.Xray, true);
|
||||||
|
config.TunModeItem.RouteExcludeAddress =
|
||||||
|
[
|
||||||
|
"0.0.0.0/1", "128.0.0.1/2", "128.0.0.1/2", "128.0.0.1/32",
|
||||||
|
"::/1", "8000::1/2", "8000::1/128"
|
||||||
|
];
|
||||||
|
var generated = await GenerateConfig(config);
|
||||||
|
|
||||||
|
var routes = generated.inbounds.Single(i => i.protocol == "tun").settings.autoSystemRoutingTable;
|
||||||
|
await routes.Should().BeEquivalentTo(new[] { "192.0.0.0/2", "c000::/2" }, StringComparer.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_TunExclusions_ShouldAllowExcludingBothAddressFamilies()
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfigWithTun(ECoreType.Xray, true);
|
||||||
|
config.TunModeItem.RouteExcludeAddress = ["0.0.0.0/0", "::/0"];
|
||||||
|
var generated = await GenerateConfig(config);
|
||||||
|
|
||||||
|
var routes = generated.inbounds.Single(i => i.protocol == "tun").settings.autoSystemRoutingTable;
|
||||||
|
await routes.Should().BeEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfigContent_TunHostExclusions_ShouldPreserveNeighbouringAddresses()
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfigWithTun(ECoreType.Xray, true);
|
||||||
|
config.TunModeItem.RouteExcludeAddress =
|
||||||
|
[
|
||||||
|
"0.0.0.0/32", "255.255.255.255/32",
|
||||||
|
"::/128", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"
|
||||||
|
];
|
||||||
|
var generated = await GenerateConfig(config);
|
||||||
|
var routes = generated.inbounds.Single(i => i.protocol == "tun").settings.autoSystemRoutingTable
|
||||||
|
.Select(IPNetwork.Parse).ToArray();
|
||||||
|
|
||||||
|
foreach (var address in new[]
|
||||||
|
{
|
||||||
|
"0.0.0.0", "255.255.255.255", "::", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"
|
||||||
|
})
|
||||||
|
{
|
||||||
|
await routes.Any(route => route.Contains(IPAddress.Parse(address))).Should().BeFalse();
|
||||||
|
}
|
||||||
|
foreach (var address in new[]
|
||||||
|
{
|
||||||
|
"0.0.0.1", "255.255.255.254", "::1", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe"
|
||||||
|
})
|
||||||
|
{
|
||||||
|
await routes.Any(route => route.Contains(IPAddress.Parse(address))).Should().BeTrue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments("198.18.0.0/15", 131071L)]
|
||||||
|
[Arguments("0.0.0.0/0", 4294967295L)]
|
||||||
|
[Arguments("198.18.0.0/31", 1L)]
|
||||||
|
[Arguments("198.18.0.1/32", 65535L)]
|
||||||
|
[Arguments("fd00::/64", long.MaxValue)]
|
||||||
|
[Arguments("fd00::/66", 4611686018427387903L)]
|
||||||
|
[Arguments("fd00::/127", 1L)]
|
||||||
|
[Arguments("fd00::1/128", 65535L)]
|
||||||
|
[Arguments("invalid-network", 65535L)]
|
||||||
|
[Arguments("198.18.0.0/33", 65535L)]
|
||||||
|
[Arguments("fd00::/129", 65535L)]
|
||||||
|
public async Task GenerateClientConfigContent_FakeDns_ShouldDerivePoolSizeOrUseFallback(
|
||||||
|
string range, long expectedPoolSize)
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig(ECoreType.Xray);
|
||||||
|
config.SimpleDNSItem.FakeIP = true;
|
||||||
|
config.SimpleDNSItem.FakeIPRange = range;
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray);
|
||||||
|
context.RoutingItem!.RuleSet = JsonUtils.Serialize(new List<RulesItem>
|
||||||
|
{
|
||||||
|
new()
|
||||||
|
{
|
||||||
|
Enabled = true,
|
||||||
|
RuleType = ERuleType.DNS,
|
||||||
|
OutboundTag = Global.ProxyTag,
|
||||||
|
Domain = ["full:example.com"],
|
||||||
|
}
|
||||||
|
});
|
||||||
|
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
|
||||||
|
await result.Success.Should().BeTrue();
|
||||||
|
var generated = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString())!;
|
||||||
|
|
||||||
|
await generated.fakedns.Should().NotBeNull();
|
||||||
|
await generated.fakedns!["ipPool"]!.GetValue<string>().Should().BeEqualTo(range);
|
||||||
|
await generated.fakedns["poolSize"]!.GetValue<long>().Should().BeEqualTo(expectedPoolSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<V2rayConfig> GenerateConfig(Config config)
|
||||||
|
{
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
var node = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray);
|
||||||
|
var context = CoreConfigTestFactory.CreateContext(config, node, ECoreType.Xray);
|
||||||
|
var result = new CoreConfigV2rayService(context).GenerateClientConfigContent();
|
||||||
|
|
||||||
|
await result.Success.Should().BeTrue();
|
||||||
|
var generated = JsonUtils.Deserialize<V2rayConfig>(result.Data!.ToString());
|
||||||
|
await generated.Should().NotBeNull();
|
||||||
|
return generated!;
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,47 @@
|
|||||||
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
|
public class AnytlsFmtTests
|
||||||
|
{
|
||||||
|
// "服务器的地址和可选端口。如果省略端口,则默认为 443。" (the port is optional and defaults to 443)
|
||||||
|
// -- https://github.com/anytls/anytls-go/blob/main/docs/uri_scheme.md
|
||||||
|
// The first two cases are the examples given there.
|
||||||
|
[Test]
|
||||||
|
[Arguments("anytls://letmein@example.com/?sni=real.example.com")]
|
||||||
|
[Arguments("anytls://letmein@example.com/?sni=127.0.0.1&insecure=1")]
|
||||||
|
[Arguments("anytls://letmein@example.com")]
|
||||||
|
[Arguments("anytls://letmein@example.com:/")]
|
||||||
|
public async Task ResolveConfig_WithoutPort_ShouldDefaultTo443(string shareUri)
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.ConfigType.Should().BeEqualTo(EConfigType.Anytls);
|
||||||
|
await resolved.Address.Should().BeEqualTo("example.com");
|
||||||
|
await resolved.Port.Should().BeEqualTo(443);
|
||||||
|
await resolved.Password.Should().BeEqualTo("letmein");
|
||||||
|
await resolved.IsValid().Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_WithExplicitPort_ShouldKeepIt()
|
||||||
|
{
|
||||||
|
// The third example from the URI scheme document.
|
||||||
|
const string shareUri = "anytls://0fdf77d7-d4ba-455e-9ed9-a98dd6d5489a@[2409:8a71:6a00:1953::615]:8964/?insecure=1";
|
||||||
|
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.Address.Should().BeEqualTo("2409:8a71:6a00:1953::615");
|
||||||
|
await resolved.Port.Should().BeEqualTo(8964);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_WithExplicitZeroPort_ShouldNotApplyTheDefault()
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig("anytls://letmein@example.com:0/", out _);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull();
|
||||||
|
await resolved!.Port.Should().BeEqualTo(0);
|
||||||
|
await resolved.IsValid().Should().BeFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,103 +1,354 @@
|
|||||||
using AwesomeAssertions;
|
|
||||||
using ServiceLib.Enums;
|
|
||||||
using ServiceLib.Handler.Fmt;
|
|
||||||
using ServiceLib.Models;
|
|
||||||
using Xunit;
|
|
||||||
|
|
||||||
namespace ServiceLib.Tests.Fmt;
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
public class FmtHandlerTests
|
public class FmtHandlerTests
|
||||||
{
|
{
|
||||||
[Fact]
|
/// <summary>
|
||||||
public void GetShareUriAndResolveConfig_Vmess_ShouldRoundTripBasicFields()
|
/// One profile factory per protocol that <see cref="FmtHandler.GetShareUri" /> can export.
|
||||||
|
/// The suite below asserts that this map and <see cref="Global.ProtocolShares" /> agree, so a
|
||||||
|
/// newly exportable protocol cannot be added without a round-trip case.
|
||||||
|
/// </summary>
|
||||||
|
private static readonly Dictionary<EConfigType, Func<ProfileItem>> ShareProfileFactories = new()
|
||||||
|
{
|
||||||
|
[EConfigType.VMess] = CreateVmessProfile,
|
||||||
|
[EConfigType.Shadowsocks] = CreateShadowsocksProfile,
|
||||||
|
[EConfigType.SOCKS] = CreateSocksProfile,
|
||||||
|
[EConfigType.VLESS] = CreateVlessProfile,
|
||||||
|
[EConfigType.Trojan] = CreateTrojanProfile,
|
||||||
|
[EConfigType.Hysteria2] = CreateHysteria2Profile,
|
||||||
|
[EConfigType.TUIC] = CreateTuicProfile,
|
||||||
|
[EConfigType.WireGuard] = CreateWireguardProfile,
|
||||||
|
[EConfigType.Anytls] = CreateAnytlsProfile,
|
||||||
|
[EConfigType.Naive] = () => CreateNaiveProfile(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ShareUriSuite_ShouldCoverAndRoundTripEveryExportableProtocol()
|
||||||
|
{
|
||||||
|
var uncovered = string.Join(", ", Global.ProtocolShares.Keys.Except(ShareProfileFactories.Keys));
|
||||||
|
var unexpected = string.Join(", ", ShareProfileFactories.Keys.Except(Global.ProtocolShares.Keys));
|
||||||
|
|
||||||
|
await uncovered.Should().BeEqualTo(string.Empty);
|
||||||
|
await unexpected.Should().BeEqualTo(string.Empty);
|
||||||
|
|
||||||
|
foreach (var (configType, factory) in ShareProfileFactories)
|
||||||
|
{
|
||||||
|
var source = factory();
|
||||||
|
|
||||||
|
var resolved = await ExportThenImport(source);
|
||||||
|
|
||||||
|
await resolved.ConfigType.Should().BeEqualTo(configType);
|
||||||
|
await resolved.Address.Should().BeEqualTo(source.Address);
|
||||||
|
await resolved.Port.Should().BeEqualTo(source.Port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUriAndResolveConfig_Vmess_ShouldRoundTripBasicFields()
|
||||||
{
|
{
|
||||||
var source = CreateVmessProfile();
|
var source = CreateVmessProfile();
|
||||||
|
|
||||||
var resolved = ExportThenImport(source);
|
var resolved = await ExportThenImport(source);
|
||||||
|
|
||||||
resolved.ConfigType.Should().Be(EConfigType.VMess);
|
await resolved.ConfigType.Should().BeEqualTo(EConfigType.VMess);
|
||||||
resolved.Remarks.Should().Be(source.Remarks);
|
await resolved.Remarks.Should().BeEqualTo(source.Remarks);
|
||||||
resolved.Address.Should().Be(source.Address);
|
await resolved.Address.Should().BeEqualTo(source.Address);
|
||||||
resolved.Port.Should().Be(source.Port);
|
await resolved.Port.Should().BeEqualTo(source.Port);
|
||||||
resolved.Password.Should().Be(source.Password);
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
resolved.GetProtocolExtra().AlterId.Should().Be(source.GetProtocolExtra().AlterId);
|
await resolved.GetProtocolExtra().AlterId.Should().BeEqualTo(source.GetProtocolExtra().AlterId);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GetShareUriAndResolveConfig_Vless_ShouldRoundTripBasicFields()
|
public async Task GetShareUriAndResolveConfig_Vless_ShouldRoundTripBasicFields()
|
||||||
{
|
{
|
||||||
var source = CreateVlessProfile();
|
var source = CreateVlessProfile();
|
||||||
|
|
||||||
var resolved = ExportThenImport(source);
|
var resolved = await ExportThenImport(source);
|
||||||
|
|
||||||
resolved.ConfigType.Should().Be(EConfigType.VLESS);
|
await resolved.ConfigType.Should().BeEqualTo(EConfigType.VLESS);
|
||||||
resolved.Remarks.Should().Be(source.Remarks);
|
await resolved.Remarks.Should().BeEqualTo(source.Remarks);
|
||||||
resolved.Address.Should().Be(source.Address);
|
await resolved.Address.Should().BeEqualTo(source.Address);
|
||||||
resolved.Port.Should().Be(source.Port);
|
await resolved.Port.Should().BeEqualTo(source.Port);
|
||||||
resolved.Password.Should().Be(source.Password);
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
resolved.GetProtocolExtra().VlessEncryption.Should().Be(Global.None);
|
await resolved.GetProtocolExtra().VlessEncryption.Should().BeEqualTo(Global.None);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GetShareUriAndResolveConfig_Shadowsocks_ShouldRoundTripBasicFields()
|
public async Task GetShareUriAndResolveConfig_Shadowsocks_ShouldRoundTripBasicFields()
|
||||||
{
|
{
|
||||||
var source = CreateShadowsocksProfile();
|
var source = CreateShadowsocksProfile();
|
||||||
|
|
||||||
var resolved = ExportThenImport(source);
|
var resolved = await ExportThenImport(source);
|
||||||
|
|
||||||
resolved.ConfigType.Should().Be(EConfigType.Shadowsocks);
|
await resolved.ConfigType.Should().BeEqualTo(EConfigType.Shadowsocks);
|
||||||
resolved.Remarks.Should().Be(source.Remarks);
|
await resolved.Remarks.Should().BeEqualTo(source.Remarks);
|
||||||
resolved.Address.Should().Be(source.Address);
|
await resolved.Address.Should().BeEqualTo(source.Address);
|
||||||
resolved.Port.Should().Be(source.Port);
|
await resolved.Port.Should().BeEqualTo(source.Port);
|
||||||
resolved.Password.Should().Be(source.Password);
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
resolved.GetProtocolExtra().SsMethod.Should().Be(source.GetProtocolExtra().SsMethod);
|
await resolved.GetProtocolExtra().SsMethod.Should().BeEqualTo(source.GetProtocolExtra().SsMethod);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GetShareUriAndResolveConfig_Socks_ShouldRoundTripBasicFields()
|
public async Task GetShareUriAndResolveConfig_Socks_ShouldRoundTripBasicFields()
|
||||||
{
|
{
|
||||||
var source = CreateSocksProfile();
|
var source = CreateSocksProfile();
|
||||||
|
|
||||||
var resolved = ExportThenImport(source);
|
var resolved = await ExportThenImport(source);
|
||||||
|
|
||||||
resolved.ConfigType.Should().Be(EConfigType.SOCKS);
|
await resolved.ConfigType.Should().BeEqualTo(EConfigType.SOCKS);
|
||||||
resolved.Remarks.Should().Be(source.Remarks);
|
await resolved.Remarks.Should().BeEqualTo(source.Remarks);
|
||||||
resolved.Address.Should().Be(source.Address);
|
await resolved.Address.Should().BeEqualTo(source.Address);
|
||||||
resolved.Port.Should().Be(source.Port);
|
await resolved.Port.Should().BeEqualTo(source.Port);
|
||||||
resolved.Username.Should().Be(source.Username);
|
await resolved.Username.Should().BeEqualTo(source.Username);
|
||||||
resolved.Password.Should().Be(source.Password);
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void ResolveConfig_UnsupportedProtocol_ShouldReturnNull()
|
public async Task GetShareUriAndResolveConfig_Trojan_ShouldRoundTripBasicFields()
|
||||||
|
{
|
||||||
|
var source = CreateTrojanProfile();
|
||||||
|
|
||||||
|
var resolved = await ExportThenImport(source);
|
||||||
|
|
||||||
|
await AssertCommonShareFields(source, resolved);
|
||||||
|
await AssertRawTransportFields(source, resolved);
|
||||||
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
|
await resolved.Sni.Should().BeEqualTo(source.Sni);
|
||||||
|
await resolved.GetProtocolExtra().Flow.Should().BeEqualTo(source.GetProtocolExtra().Flow);
|
||||||
|
await resolved.GetAllowInsecure().Should().BeTrue();
|
||||||
|
|
||||||
|
// Trojan is the one exporter that writes both spellings of the flag.
|
||||||
|
await AssertExportContains(source, "allowInsecure=1", "insecure=1");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUriAndResolveConfig_Tuic_ShouldRoundTripUserInfoAndCongestionControl()
|
||||||
|
{
|
||||||
|
var source = CreateTuicProfile();
|
||||||
|
|
||||||
|
var resolved = await ExportThenImport(source);
|
||||||
|
|
||||||
|
await AssertCommonShareFields(source, resolved);
|
||||||
|
await resolved.Username.Should().BeEqualTo(source.Username);
|
||||||
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
|
await resolved.Sni.Should().BeEqualTo(source.Sni);
|
||||||
|
await resolved.Alpn.Should().BeEqualTo(source.Alpn);
|
||||||
|
await resolved.GetProtocolExtra().CongestionControl.Should()
|
||||||
|
.BeEqualTo(source.GetProtocolExtra().CongestionControl);
|
||||||
|
await resolved.GetAllowInsecure().Should().BeTrue();
|
||||||
|
|
||||||
|
await AssertExportContains(source, "allow_insecure=1");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUriAndResolveConfig_Anytls_ShouldRoundTripBasicFields()
|
||||||
|
{
|
||||||
|
var source = CreateAnytlsProfile();
|
||||||
|
|
||||||
|
var resolved = await ExportThenImport(source);
|
||||||
|
|
||||||
|
await AssertCommonShareFields(source, resolved);
|
||||||
|
await AssertRawTransportFields(source, resolved);
|
||||||
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
|
await resolved.Sni.Should().BeEqualTo(source.Sni);
|
||||||
|
await resolved.Alpn.Should().BeEqualTo(source.Alpn);
|
||||||
|
await resolved.GetAllowInsecure().Should().BeTrue();
|
||||||
|
|
||||||
|
await AssertExportContains(source, "insecure=1");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUriAndResolveConfig_Hysteria2_ShouldRoundTripObfsAndNormalizePortRange()
|
||||||
|
{
|
||||||
|
var source = CreateHysteria2Profile();
|
||||||
|
|
||||||
|
var resolved = await ExportThenImport(source);
|
||||||
|
var sourceExtra = source.GetProtocolExtra();
|
||||||
|
var resolvedExtra = resolved.GetProtocolExtra();
|
||||||
|
|
||||||
|
await AssertCommonShareFields(source, resolved);
|
||||||
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
|
await resolved.Sni.Should().BeEqualTo(source.Sni);
|
||||||
|
await resolved.Alpn.Should().BeEqualTo(source.Alpn);
|
||||||
|
await resolved.EchConfigList.Should().BeEqualTo(source.EchConfigList);
|
||||||
|
await resolved.GetAllowInsecure().Should().BeTrue();
|
||||||
|
await resolvedExtra.SalamanderPass.Should().BeEqualTo(sourceExtra.SalamanderPass);
|
||||||
|
|
||||||
|
// Hysteria2Fmt stores a port range internally as "5000:6000" and emits the URI form.
|
||||||
|
await resolvedExtra.Ports.Should().BeEqualTo("5000-6000");
|
||||||
|
|
||||||
|
await AssertExportContains(source, "insecure=1", "obfs=salamander", "mport=5000-6000");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUriAndResolveConfig_Wireguard_ShouldRoundTripKeysAndInterface()
|
||||||
|
{
|
||||||
|
var source = CreateWireguardProfile();
|
||||||
|
|
||||||
|
var resolved = await ExportThenImport(source);
|
||||||
|
var extra = resolved.GetProtocolExtra();
|
||||||
|
var sourceExtra = source.GetProtocolExtra();
|
||||||
|
|
||||||
|
await AssertCommonShareFields(source, resolved);
|
||||||
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
|
await extra.WgPublicKey.Should().BeEqualTo(sourceExtra.WgPublicKey);
|
||||||
|
await extra.WgPresharedKey.Should().BeEqualTo(sourceExtra.WgPresharedKey);
|
||||||
|
await extra.WgReserved.Should().BeEqualTo(sourceExtra.WgReserved);
|
||||||
|
await extra.WgInterfaceAddress.Should().BeEqualTo(sourceExtra.WgInterfaceAddress);
|
||||||
|
await extra.WgMtu.Should().BeEqualTo(sourceExtra.WgMtu);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUri_Wireguard_ShouldEncodeKeysAndBracketIpv6()
|
||||||
|
{
|
||||||
|
var source = CreateWireguardProfile();
|
||||||
|
|
||||||
|
// Base64 keys carry '/', '+' and '=', and the address is an IPv6 literal: both have to
|
||||||
|
// survive the wire form, which a round trip through the same encoder would not prove.
|
||||||
|
await AssertExportContains(
|
||||||
|
source,
|
||||||
|
Uri.EscapeDataString(source.Password),
|
||||||
|
Uri.EscapeDataString(source.GetProtocolExtra().WgPublicKey ?? string.Empty),
|
||||||
|
"@[2001:db8::40]:51820");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUriAndResolveConfig_Naive_ShouldRoundTripCredentialsOverHttps()
|
||||||
|
{
|
||||||
|
var source = CreateNaiveProfile(false);
|
||||||
|
|
||||||
|
var resolved = await ExportThenImport(source, Global.NaiveHttpsProtocolShare);
|
||||||
|
|
||||||
|
await AssertCommonShareFields(source, resolved);
|
||||||
|
await AssertRawTransportFields(source, resolved);
|
||||||
|
await resolved.Username.Should().BeEqualTo(source.Username);
|
||||||
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
|
await resolved.GetProtocolExtra().InsecureConcurrency.Should()
|
||||||
|
.BeEqualTo(source.GetProtocolExtra().InsecureConcurrency);
|
||||||
|
|
||||||
|
// NaiveFmt only ever sets this flag on the quic branch, so the https branch leaves it
|
||||||
|
// unset rather than false - assert "is not quic" instead of an explicit false.
|
||||||
|
await (resolved.GetProtocolExtra().NaiveQuic == true).Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUriAndResolveConfig_NaiveQuic_ShouldRoundTripQuicScheme()
|
||||||
|
{
|
||||||
|
var source = CreateNaiveProfile(true);
|
||||||
|
|
||||||
|
var resolved = await ExportThenImport(source, Global.NaiveQuicProtocolShare);
|
||||||
|
|
||||||
|
await AssertCommonShareFields(source, resolved);
|
||||||
|
await AssertRawTransportFields(source, resolved);
|
||||||
|
await resolved.Username.Should().BeEqualTo(source.Username);
|
||||||
|
await resolved.Password.Should().BeEqualTo(source.Password);
|
||||||
|
await resolved.GetProtocolExtra().InsecureConcurrency.Should()
|
||||||
|
.BeEqualTo(source.GetProtocolExtra().InsecureConcurrency);
|
||||||
|
await resolved.GetProtocolExtra().NaiveQuic.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments("p:a@ss#% +/=")]
|
||||||
|
[Arguments("пароль 東京")]
|
||||||
|
public async Task GetShareUriAndResolveConfig_Trojan_ShouldRoundTripEncodedCredentials(string password)
|
||||||
|
{
|
||||||
|
var source = CreateTrojanProfile();
|
||||||
|
source.Password = password;
|
||||||
|
source.Remarks = "Trojan — тест 東京 #1";
|
||||||
|
|
||||||
|
var resolved = await ExportThenImport(source);
|
||||||
|
|
||||||
|
await resolved.Password.Should().BeEqualTo(password);
|
||||||
|
await resolved.Remarks.Should().BeEqualTo(source.Remarks);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_UnsupportedProtocol_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
var resolved = FmtHandler.ResolveConfig("not-a-share-uri", out var msg);
|
var resolved = FmtHandler.ResolveConfig("not-a-share-uri", out var msg);
|
||||||
|
|
||||||
resolved.Should().BeNull();
|
await resolved.Should().BeNull();
|
||||||
msg.Should().NotBeNullOrWhiteSpace();
|
await msg.Should().NotBeNull();
|
||||||
|
await msg.Should().NotBeEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Test]
|
||||||
public void GetShareUri_UnsupportedConfigType_ShouldReturnNull()
|
public async Task GetShareUri_UnsupportedConfigType_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
var item = new ProfileItem { ConfigType = EConfigType.PolicyGroup, Remarks = "group", };
|
var item = new ProfileItem { ConfigType = EConfigType.PolicyGroup, Remarks = "group", };
|
||||||
|
|
||||||
var uri = FmtHandler.GetShareUri(item);
|
var uri = FmtHandler.GetShareUri(item);
|
||||||
|
|
||||||
uri.Should().BeNull();
|
await uri.Should().BeNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ProfileItem ExportThenImport(ProfileItem source)
|
private static async Task AssertCommonShareFields(ProfileItem source, ProfileItem resolved)
|
||||||
|
{
|
||||||
|
await resolved.ConfigType.Should().BeEqualTo(source.ConfigType);
|
||||||
|
await resolved.Remarks.Should().BeEqualTo(source.Remarks);
|
||||||
|
await resolved.Address.Should().BeEqualTo(source.Address);
|
||||||
|
await resolved.Port.Should().BeEqualTo(source.Port);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Only for protocols whose exporter goes through the shared transport query
|
||||||
|
/// (<c>security</c>, <c>type</c>, <c>headerType</c>). TUIC, Hysteria2 and WireGuard do not.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task AssertRawTransportFields(ProfileItem source, ProfileItem resolved)
|
||||||
|
{
|
||||||
|
await resolved.Network.Should().BeEqualTo(source.Network);
|
||||||
|
await resolved.StreamSecurity.Should().BeEqualTo(source.StreamSecurity);
|
||||||
|
await resolved.GetTransportExtra().RawHeaderType.Should()
|
||||||
|
.BeEqualTo(source.GetTransportExtra().RawHeaderType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Asserts on the wire form itself. A round trip cannot catch an exporter and an importer that
|
||||||
|
/// agree on the wrong spelling of a parameter, and the insecure flag is spelled differently by
|
||||||
|
/// every protocol.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task AssertExportContains(ProfileItem source, params string[] expectedFragments)
|
||||||
{
|
{
|
||||||
var uri = FmtHandler.GetShareUri(source);
|
var uri = FmtHandler.GetShareUri(source);
|
||||||
|
|
||||||
uri.Should().NotBeNullOrWhiteSpace();
|
await uri.Should().NotBeNull();
|
||||||
uri!.StartsWith(Global.ProtocolShares[source.ConfigType], StringComparison.OrdinalIgnoreCase).Should()
|
|
||||||
.BeTrue();
|
foreach (var fragment in expectedFragments)
|
||||||
|
{
|
||||||
|
await uri!.Contains(fragment, StringComparison.Ordinal).Should()
|
||||||
|
.BeTrue().Because($"uri: {uri}, expected fragment: {fragment}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ExpectedShareScheme(ProfileItem item)
|
||||||
|
{
|
||||||
|
if (item.ConfigType != EConfigType.Naive)
|
||||||
|
{
|
||||||
|
return Global.ProtocolShares[item.ConfigType];
|
||||||
|
}
|
||||||
|
|
||||||
|
// NaiveFmt never emits the "naive://" prefix that Global.ProtocolShares records for the
|
||||||
|
// type; that entry is only read when importing.
|
||||||
|
return item.GetProtocolExtra().NaiveQuic == true
|
||||||
|
? Global.NaiveQuicProtocolShare
|
||||||
|
: Global.NaiveHttpsProtocolShare;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<ProfileItem> ExportThenImport(ProfileItem source)
|
||||||
|
{
|
||||||
|
return await ExportThenImport(source, ExpectedShareScheme(source));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task<ProfileItem> ExportThenImport(ProfileItem source, string expectedPrefix)
|
||||||
|
{
|
||||||
|
var uri = FmtHandler.GetShareUri(source);
|
||||||
|
|
||||||
|
await uri.Should().NotBeNull();
|
||||||
|
await uri.Should().NotBeEmpty();
|
||||||
|
await uri!.StartsWith(expectedPrefix, StringComparison.OrdinalIgnoreCase).Should().BeTrue();
|
||||||
|
|
||||||
var resolved = FmtHandler.ResolveConfig(uri, out var msg);
|
var resolved = FmtHandler.ResolveConfig(uri, out var msg);
|
||||||
|
|
||||||
resolved.Should().NotBeNull($"uri: {uri}, msg: {msg}");
|
await resolved.Should().NotBeNull().Because($"uri: {uri}, msg: {msg}");
|
||||||
return resolved!;
|
return resolved!;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -170,4 +421,142 @@ public class FmtHandlerTests
|
|||||||
Password = "pass",
|
Password = "pass",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static ProfileItem CreateTrojanProfile()
|
||||||
|
{
|
||||||
|
var item = new ProfileItem
|
||||||
|
{
|
||||||
|
ConfigType = EConfigType.Trojan,
|
||||||
|
Remarks = "trojan demo",
|
||||||
|
Address = "trojan.example",
|
||||||
|
Port = 443,
|
||||||
|
Password = "trojan-pass",
|
||||||
|
Network = nameof(ETransport.raw),
|
||||||
|
StreamSecurity = Global.StreamSecurity,
|
||||||
|
Sni = "sni.trojan.example",
|
||||||
|
AllowInsecure = Global.StringTrue,
|
||||||
|
};
|
||||||
|
|
||||||
|
item.SetProtocolExtra(new ProtocolExtraItem { Flow = Global.Flows[1], });
|
||||||
|
item.SetTransportExtra(new TransportExtraItem { RawHeaderType = Global.None, });
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ProfileItem CreateTuicProfile()
|
||||||
|
{
|
||||||
|
var item = new ProfileItem
|
||||||
|
{
|
||||||
|
ConfigType = EConfigType.TUIC,
|
||||||
|
Remarks = "tuic demo",
|
||||||
|
Address = "tuic.example",
|
||||||
|
Port = 8443,
|
||||||
|
// A colon separates the two halves of the TUIC user info, so it cannot appear in the
|
||||||
|
// uuid; a fixed value also keeps a failure reproducible.
|
||||||
|
Username = "01234567-89ab-cdef-0123-456789abcdef",
|
||||||
|
Password = "tuic-pass",
|
||||||
|
Sni = "sni.tuic.example",
|
||||||
|
Alpn = "h3",
|
||||||
|
AllowInsecure = Global.StringTrue,
|
||||||
|
};
|
||||||
|
|
||||||
|
item.SetProtocolExtra(new ProtocolExtraItem { CongestionControl = "bbr", });
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ProfileItem CreateAnytlsProfile()
|
||||||
|
{
|
||||||
|
var item = new ProfileItem
|
||||||
|
{
|
||||||
|
ConfigType = EConfigType.Anytls,
|
||||||
|
Remarks = "anytls demo",
|
||||||
|
Address = "anytls.example",
|
||||||
|
Port = 8443,
|
||||||
|
Password = "anytls-pass",
|
||||||
|
Network = nameof(ETransport.raw),
|
||||||
|
StreamSecurity = Global.StreamSecurity,
|
||||||
|
Sni = "sni.anytls.example",
|
||||||
|
Alpn = "h2,http/1.1",
|
||||||
|
AllowInsecure = Global.StringTrue,
|
||||||
|
};
|
||||||
|
|
||||||
|
item.SetTransportExtra(new TransportExtraItem { RawHeaderType = Global.None, });
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ProfileItem CreateHysteria2Profile()
|
||||||
|
{
|
||||||
|
// CertSha is deliberately left unset: the importer turns AllowInsecure on by itself when a
|
||||||
|
// pinSHA256 is present, which would mask an exporter that stopped emitting insecure=1.
|
||||||
|
var item = new ProfileItem
|
||||||
|
{
|
||||||
|
ConfigType = EConfigType.Hysteria2,
|
||||||
|
Remarks = "hysteria2 demo",
|
||||||
|
Address = "hy2.example",
|
||||||
|
Port = 8443,
|
||||||
|
Password = "demo-user:demo-pass",
|
||||||
|
Sni = "sni.hy2.example",
|
||||||
|
Alpn = "h3",
|
||||||
|
EchConfigList = "AAj+DQAEAAAAAA==",
|
||||||
|
AllowInsecure = Global.StringTrue,
|
||||||
|
};
|
||||||
|
|
||||||
|
item.SetProtocolExtra(new ProtocolExtraItem
|
||||||
|
{
|
||||||
|
SalamanderPass = "salamander-pass",
|
||||||
|
Ports = "5000:6000",
|
||||||
|
});
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string CreateWireguardKey(byte value)
|
||||||
|
{
|
||||||
|
return Convert.ToBase64String(Enumerable.Repeat(value, 32).ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ProfileItem CreateWireguardProfile()
|
||||||
|
{
|
||||||
|
var item = new ProfileItem
|
||||||
|
{
|
||||||
|
ConfigType = EConfigType.WireGuard,
|
||||||
|
Remarks = "WireGuard — тест 東京 #1",
|
||||||
|
Address = "2001:db8::40",
|
||||||
|
Port = 51820,
|
||||||
|
Password = CreateWireguardKey(0xFE),
|
||||||
|
};
|
||||||
|
|
||||||
|
item.SetProtocolExtra(new ProtocolExtraItem
|
||||||
|
{
|
||||||
|
WgPublicKey = CreateWireguardKey(0xFD),
|
||||||
|
WgPresharedKey = CreateWireguardKey(0xFC),
|
||||||
|
WgReserved = "1,2,255",
|
||||||
|
WgInterfaceAddress = "10.0.0.2/32,fd00::2/128",
|
||||||
|
WgMtu = 1420,
|
||||||
|
});
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ProfileItem CreateNaiveProfile(bool quic)
|
||||||
|
{
|
||||||
|
var item = new ProfileItem
|
||||||
|
{
|
||||||
|
ConfigType = EConfigType.Naive,
|
||||||
|
Remarks = quic ? "naive quic demo" : "naive https demo",
|
||||||
|
Address = "naive.example",
|
||||||
|
Port = 443,
|
||||||
|
Username = "naive-user",
|
||||||
|
Password = "päss:word@/?#&=+ 東京",
|
||||||
|
Network = nameof(ETransport.raw),
|
||||||
|
StreamSecurity = Global.None,
|
||||||
|
};
|
||||||
|
|
||||||
|
item.SetProtocolExtra(new ProtocolExtraItem { NaiveQuic = quic, InsecureConcurrency = 4, });
|
||||||
|
item.SetTransportExtra(new TransportExtraItem { RawHeaderType = Global.None, });
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
|
public class HyRealmTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
public async Task TryParse_ShouldParseValidRealm()
|
||||||
|
{
|
||||||
|
var str = "realm://public@realm.hy2.io/57f9be7c-2810-4f5b-8cb9-260bc84d6c90?stun=example.stun:3478&stun=example2.stun:3478";
|
||||||
|
var result = HyRealm.TryParse(str, out var realm);
|
||||||
|
await result.Should().BeTrue();
|
||||||
|
await realm.Should().NotBeNull();
|
||||||
|
|
||||||
|
await realm.IsHttp.Should().BeFalse();
|
||||||
|
await realm.Token.Should().BeEqualTo("public");
|
||||||
|
await realm.RendezvousHost.Should().BeEqualTo("realm.hy2.io");
|
||||||
|
await realm.RendezvousPort.Should().BeEqualTo(443);
|
||||||
|
await realm.RealmName.Should().BeEqualTo("57f9be7c-2810-4f5b-8cb9-260bc84d6c90");
|
||||||
|
await realm.StunList.Should().HaveCount(2);
|
||||||
|
await realm.StunList.Should().Contain("example.stun:3478");
|
||||||
|
await realm.StunList.Should().Contain("example2.stun:3478");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ToUri_ShouldGenerateValidUri()
|
||||||
|
{
|
||||||
|
var realm = new HyRealm(
|
||||||
|
IsHttp: false,
|
||||||
|
Token: "public",
|
||||||
|
RendezvousHost: "realm.hy2.io",
|
||||||
|
RendezvousPort: 443,
|
||||||
|
RealmName: "57f9be7c-2810-4f5b-8cb9-260bc84d6c90",
|
||||||
|
StunList: ["example.stun:3478", "example2.stun:3478"]
|
||||||
|
);
|
||||||
|
var uri = realm.ToUri();
|
||||||
|
await uri.Should().Contain("realm://public@realm.hy2.io");
|
||||||
|
await uri.Should().Contain("/57f9be7c-2810-4f5b-8cb9-260bc84d6c90");
|
||||||
|
await uri.Should().Contain("stun=example.stun:3478");
|
||||||
|
await uri.Should().Contain("stun=example2.stun:3478");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUriAndResolveConfig_Hy2Realm_ShouldRoundTripBasicFields()
|
||||||
|
{
|
||||||
|
var str = "hysteria2+realm://mytoken@rendezvous.example.com/my-cabin-1f3a8c2e9b?auth=your_password&insecure=1&pinSHA256=deadbeef#remark";
|
||||||
|
var resolved = Hysteria2Fmt.ResolveRealm(str, out var msg);
|
||||||
|
await resolved.Should().NotBeNull();
|
||||||
|
await resolved.Password.Should().BeEqualTo("your_password");
|
||||||
|
var result = HyRealm.TryParse(resolved.GetProtocolExtra().Hy2RealmUrl, out var realm);
|
||||||
|
await result.Should().BeTrue();
|
||||||
|
await realm.Should().NotBeNull();
|
||||||
|
await realm.Token.Should().BeEqualTo("mytoken");
|
||||||
|
|
||||||
|
// To uri
|
||||||
|
var uri = Hysteria2Fmt.ToUri(resolved);
|
||||||
|
await uri.Should().Contain("hysteria2+realm://mytoken@rendezvous.example.com");
|
||||||
|
await uri.Should().EndWith("#remark");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ToServerUrl_ShouldIncludeSchemeForSingbox()
|
||||||
|
{
|
||||||
|
var realm = new HyRealm(
|
||||||
|
IsHttp: false,
|
||||||
|
Token: "public",
|
||||||
|
RendezvousHost: "realm.hy2.io",
|
||||||
|
RendezvousPort: 443,
|
||||||
|
RealmName: "my-realm-id",
|
||||||
|
StunList: ["turn.cloudflare.com:3478"]
|
||||||
|
);
|
||||||
|
|
||||||
|
await realm.ToServerUrl().Should().BeEqualTo("https://realm.hy2.io:443");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveRealm_Issue9635_ShouldProduceHttpsServerUrl()
|
||||||
|
{
|
||||||
|
var str = "hysteria2+realm://public@realm.hy2.io/my-realm-id?auth=uuid&stun=turn.cloudflare.com%3A3478&sni=cloudflare.com&pinSHA256=xxx#Realm-Test";
|
||||||
|
var resolved = Hysteria2Fmt.ResolveRealm(str, out _);
|
||||||
|
await resolved.Should().NotBeNull();
|
||||||
|
|
||||||
|
await HyRealm.TryParse(resolved!.GetProtocolExtra().Hy2RealmUrl, out var realm).Should().BeTrue();
|
||||||
|
await realm!.ToServerUrl().Should().StartWith("https://");
|
||||||
|
await realm.ToServerUrl().Should().Contain("realm.hy2.io");
|
||||||
|
await realm.StunList.Should().Contain("turn.cloudflare.com:3478");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
|
public class Hysteria2FmtTests
|
||||||
|
{
|
||||||
|
// "The hostname and optional port of the server. If the port is omitted, it defaults to 443."
|
||||||
|
// -- https://v2.hysteria.network/docs/developers/URI-Scheme/
|
||||||
|
// A ':' with no digits after it is an omitted port too, per RFC 3986 'port = *DIGIT'.
|
||||||
|
[Test]
|
||||||
|
[Arguments("hysteria2://password@hy2.example/")]
|
||||||
|
[Arguments("hysteria2://password@hy2.example")]
|
||||||
|
[Arguments("hysteria2://password@hy2.example:/")]
|
||||||
|
[Arguments("hy2://password@hy2.example/?sni=real.example")]
|
||||||
|
public async Task ResolveConfig_WithoutPort_ShouldDefaultTo443(string shareUri)
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.ConfigType.Should().BeEqualTo(EConfigType.Hysteria2);
|
||||||
|
await resolved.Address.Should().BeEqualTo("hy2.example");
|
||||||
|
await resolved.Port.Should().BeEqualTo(443);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_WithoutPort_ShouldProduceAValidProfile()
|
||||||
|
{
|
||||||
|
// Uri.Port is -1 for an unregistered scheme with no port, and ProfileItem.IsValid rejects
|
||||||
|
// any port outside 1..65535 - so the default is what keeps such a link usable at all.
|
||||||
|
var resolved = FmtHandler.ResolveConfig("hysteria2://password@hy2.example/", out _);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull();
|
||||||
|
await resolved!.IsValid().Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_WithExplicitPort_ShouldKeepIt()
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig("hysteria2://password@hy2.example:8443/", out _);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull();
|
||||||
|
await resolved!.Port.Should().BeEqualTo(8443);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_WithExplicitZeroPort_ShouldNotApplyTheDefault()
|
||||||
|
{
|
||||||
|
// Uri.Port is 0 here, not -1: the port is present, it is just not a usable one. Treating
|
||||||
|
// it as "omitted" would silently move the endpoint to :443, so it stays invalid instead.
|
||||||
|
var resolved = FmtHandler.ResolveConfig("hysteria2://password@hy2.example:0/", out _);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull();
|
||||||
|
await resolved!.Port.Should().BeEqualTo(0);
|
||||||
|
await resolved.IsValid().Should().BeFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,11 @@
|
|||||||
using AwesomeAssertions;
|
|
||||||
using ServiceLib.Enums;
|
|
||||||
using ServiceLib.Handler.Fmt;
|
|
||||||
using ServiceLib.Tests.CoreConfig;
|
using ServiceLib.Tests.CoreConfig;
|
||||||
using Xunit;
|
|
||||||
|
|
||||||
namespace ServiceLib.Tests.Fmt;
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
public class InnerFmtTests
|
public class InnerFmtTests
|
||||||
{
|
{
|
||||||
[Fact]
|
[Test]
|
||||||
public void ToUriAndResolve_ShouldRoundTripPolicyGroupReferences()
|
public async Task ToUriAndResolve_ShouldRoundTripPolicyGroupReferences()
|
||||||
{
|
{
|
||||||
var childA = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "child-a", "child-a");
|
var childA = CoreConfigTestFactory.CreateSocksNode(ECoreType.Xray, "child-a", "child-a");
|
||||||
var childB = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "child-b", "child-b");
|
var childB = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, "child-b", "child-b");
|
||||||
@@ -19,19 +15,20 @@ public class InnerFmtTests
|
|||||||
|
|
||||||
var uri = InnerFmt.ToUri([group, childA, childB]);
|
var uri = InnerFmt.ToUri([group, childA, childB]);
|
||||||
|
|
||||||
uri.Should().NotBeNullOrWhiteSpace();
|
await uri.Should().NotBeNull();
|
||||||
|
await uri.Should().NotBeEmpty();
|
||||||
|
|
||||||
var resolved = InnerFmt.Resolve(uri!, "sub-123");
|
var resolved = InnerFmt.Resolve(uri!, "sub-123");
|
||||||
|
|
||||||
resolved.Should().NotBeNull();
|
await resolved.Should().NotBeNull();
|
||||||
resolved.Should().HaveCount(3);
|
await resolved.Should().HaveCount(3);
|
||||||
|
|
||||||
var resolvedGroup = resolved!.Single(x => x.Remarks == group.Remarks);
|
var resolvedGroup = resolved!.Single(x => x.Remarks == group.Remarks);
|
||||||
var resolvedChildA = resolved.Single(x => x.Remarks == childA.Remarks);
|
var resolvedChildA = resolved.Single(x => x.Remarks == childA.Remarks);
|
||||||
var resolvedChildB = resolved.Single(x => x.Remarks == childB.Remarks);
|
var resolvedChildB = resolved.Single(x => x.Remarks == childB.Remarks);
|
||||||
|
|
||||||
resolvedGroup.ConfigType.Should().Be(EConfigType.PolicyGroup);
|
await resolvedGroup.ConfigType.Should().BeEqualTo(EConfigType.PolicyGroup);
|
||||||
resolvedGroup.GetProtocolExtra().SubChildItems.Should().Be("sub-123");
|
await resolvedGroup.GetProtocolExtra().SubChildItems.Should().BeEqualTo("sub-123");
|
||||||
resolvedGroup.GetProtocolExtra().ChildItems.Should().Be($"{resolvedChildA.IndexId},{resolvedChildB.IndexId}");
|
await resolvedGroup.GetProtocolExtra().ChildItems.Should().BeEqualTo($"{resolvedChildA.IndexId},{resolvedChildB.IndexId}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
|
public class NaiveFmtTests
|
||||||
|
{
|
||||||
|
// "port can be omitted if it's 443" -- https://gist.github.com/DuckSoft/ca03913b0a26fc77a1da4d01cc6ab2f1
|
||||||
|
// The first two cases are examples given there; none of its examples carries a port.
|
||||||
|
[Test]
|
||||||
|
[Arguments("naive+https://what:happened@test.someone.cf?padding=false#Naive!", false)]
|
||||||
|
[Arguments("naive+quic://manhole:114514@quic.test.me", true)]
|
||||||
|
[Arguments("naive+https://what:happened@test.someone.cf/", false)]
|
||||||
|
[Arguments("naive+https://what:happened@test.someone.cf:/", false)]
|
||||||
|
public async Task ResolveConfig_WithoutPort_ShouldDefaultTo443(string shareUri, bool quic)
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.ConfigType.Should().BeEqualTo(EConfigType.Naive);
|
||||||
|
await resolved.Port.Should().BeEqualTo(443);
|
||||||
|
await (resolved.GetProtocolExtra().NaiveQuic == true).Should().BeEqualTo(quic);
|
||||||
|
await resolved.IsValid().Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_WithExplicitPort_ShouldKeepIt()
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig("naive+https://what:happened@test.someone.cf:8443", out _);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull();
|
||||||
|
await resolved!.Address.Should().BeEqualTo("test.someone.cf");
|
||||||
|
await resolved.Port.Should().BeEqualTo(8443);
|
||||||
|
await resolved.Username.Should().BeEqualTo("what");
|
||||||
|
await resolved.Password.Should().BeEqualTo("happened");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_WithExplicitZeroPort_ShouldNotApplyTheDefault()
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig("naive+https://what:happened@test.someone.cf:0", out _);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull();
|
||||||
|
await resolved!.Port.Should().BeEqualTo(0);
|
||||||
|
await resolved.IsValid().Should().BeFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
|
public class NaiveFmtUserInfoTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments("pa:ss")]
|
||||||
|
[Arguments("a:b:c")]
|
||||||
|
[Arguments(":leading")]
|
||||||
|
[Arguments("trailing:")]
|
||||||
|
public async Task GetShareUriAndResolveConfig_PasswordOnlyWithColon_ShouldKeepPassword(string password)
|
||||||
|
{
|
||||||
|
var source = CreateNaiveProfile(string.Empty, password);
|
||||||
|
|
||||||
|
var uri = FmtHandler.GetShareUri(source);
|
||||||
|
await uri.Should().NotBeNull();
|
||||||
|
|
||||||
|
var resolved = FmtHandler.ResolveConfig(uri!, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {uri}, msg: {msg}");
|
||||||
|
await resolved!.Username.Should().BeEqualTo(string.Empty);
|
||||||
|
await resolved.Password.Should().BeEqualTo(password);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task GetShareUriAndResolveConfig_UsernameAndPasswordWithColons_ShouldKeepBoth()
|
||||||
|
{
|
||||||
|
var source = CreateNaiveProfile("us:er", "pa:ss");
|
||||||
|
|
||||||
|
var uri = FmtHandler.GetShareUri(source);
|
||||||
|
await uri.Should().NotBeNull();
|
||||||
|
|
||||||
|
var resolved = FmtHandler.ResolveConfig(uri!, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {uri}, msg: {msg}");
|
||||||
|
await resolved!.Username.Should().BeEqualTo("us:er");
|
||||||
|
await resolved.Password.Should().BeEqualTo("pa:ss");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments("naive+https://what:happened@test.someone.cf:443", "what", "happened")]
|
||||||
|
[Arguments("naive+https://what:hap:pened@test.someone.cf:443", "what", "hap:pened")]
|
||||||
|
[Arguments("naive+https://wh%40t:hap%3Apened@test.someone.cf:443", "wh@t", "hap:pened")]
|
||||||
|
[Arguments("naive+https://pa%3Ass@test.someone.cf:443", "", "pa:ss")]
|
||||||
|
[Arguments("naive+quic://secret@test.someone.cf:443", "", "secret")]
|
||||||
|
public async Task ResolveConfig_ShouldSplitUserInfoBeforeDecoding(string shareUri, string username, string password)
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.Username.Should().BeEqualTo(username);
|
||||||
|
await resolved.Password.Should().BeEqualTo(password);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ProfileItem CreateNaiveProfile(string username, string password)
|
||||||
|
{
|
||||||
|
var item = new ProfileItem
|
||||||
|
{
|
||||||
|
ConfigType = EConfigType.Naive,
|
||||||
|
Remarks = "naive demo",
|
||||||
|
Address = "naive.example",
|
||||||
|
Port = 443,
|
||||||
|
Username = username,
|
||||||
|
Password = password,
|
||||||
|
Network = nameof(ETransport.raw),
|
||||||
|
StreamSecurity = Global.None,
|
||||||
|
};
|
||||||
|
item.SetTransportExtra(new TransportExtraItem { RawHeaderType = Global.None, });
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
|
public class ShadowsocksFmtTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments("8388", true)]
|
||||||
|
[Arguments("\"8388\"", true)]
|
||||||
|
[Arguments("8388", false)]
|
||||||
|
[Arguments("\"8388\"", false)]
|
||||||
|
public async Task ResolveSip008_ObjectAndArrayDocuments_ShouldPreserveServerFields(string port, bool useObject)
|
||||||
|
{
|
||||||
|
var server = $$"""
|
||||||
|
{
|
||||||
|
"id": "27b8a625-4f4b-4428-9f0f-8a2317db7c79",
|
||||||
|
"remarks": "SIP008 server",
|
||||||
|
"server": "example.com",
|
||||||
|
"server_port": {{port}},
|
||||||
|
"password": "example",
|
||||||
|
"method": "chacha20-ietf-poly1305"
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
var document = useObject
|
||||||
|
? $$"""{"version": 1, "servers": [{{server}}]}"""
|
||||||
|
: $"[{server}]";
|
||||||
|
|
||||||
|
var resolved = ShadowsocksFmt.ResolveSip008(document);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull();
|
||||||
|
await resolved!.Should().HaveCount(1);
|
||||||
|
await resolved[0].Remarks.Should().BeEqualTo("SIP008 server");
|
||||||
|
await resolved[0].Address.Should().BeEqualTo("example.com");
|
||||||
|
await resolved[0].Port.Should().BeEqualTo(8388);
|
||||||
|
await resolved[0].Password.Should().BeEqualTo("example");
|
||||||
|
await resolved[0].GetProtocolExtra().SsMethod.Should().BeEqualTo("chacha20-ietf-poly1305");
|
||||||
|
}
|
||||||
|
|
||||||
|
// SIP002 user info that is not base64 is "method:password", percent-encoded once.
|
||||||
|
[Test]
|
||||||
|
[Arguments("ss://2022-blake3-aes-128-gcm:p%2541ss@1.2.3.4:8388#demo", "p%41ss")]
|
||||||
|
[Arguments("ss://2022-blake3-aes-128-gcm:p%25ss@1.2.3.4:8388#demo", "p%ss")]
|
||||||
|
[Arguments("ss://2022-blake3-aes-128-gcm:a%3Ab%2Fc%2B%3D@1.2.3.4:8388#demo", "a:b/c+=")]
|
||||||
|
public async Task ResolveConfig_PlainUserInfo_ShouldDecodePasswordOnce(string shareUri, string password)
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.ConfigType.Should().BeEqualTo(EConfigType.Shadowsocks);
|
||||||
|
await resolved.GetProtocolExtra().SsMethod.Should().BeEqualTo("2022-blake3-aes-128-gcm");
|
||||||
|
await resolved.Password.Should().BeEqualTo(password);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
|
public class ShareUriQueryTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments("ob%41fs")]
|
||||||
|
[Arguments("66%ff")]
|
||||||
|
[Arguments("100%")]
|
||||||
|
public async Task GetShareUriAndResolveConfig_QueryValueWithPercent_ShouldSurviveTheRoundTrip(string obfsPassword)
|
||||||
|
{
|
||||||
|
var source = new ProfileItem
|
||||||
|
{
|
||||||
|
ConfigType = EConfigType.Hysteria2,
|
||||||
|
Remarks = "percent demo",
|
||||||
|
Address = "hy2.example",
|
||||||
|
Port = 8443,
|
||||||
|
Password = "pw",
|
||||||
|
};
|
||||||
|
source.SetProtocolExtra(new ProtocolExtraItem { SalamanderPass = obfsPassword, });
|
||||||
|
|
||||||
|
var uri = FmtHandler.GetShareUri(source);
|
||||||
|
|
||||||
|
await uri.Should().NotBeNull();
|
||||||
|
|
||||||
|
var resolved = FmtHandler.ResolveConfig(uri!, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {uri}, msg: {msg}");
|
||||||
|
await resolved!.GetProtocolExtra().SalamanderPass.Should().BeEqualTo(obfsPassword);
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 3986 lists '=' among the sub-delimiters a query value may carry, so only the first one
|
||||||
|
// separates the key from the value. Splitting on every '=' discarded the pair outright.
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_QueryValueWithUnescapedEquals_ShouldNotBeDropped()
|
||||||
|
{
|
||||||
|
const string shareUri = "hysteria2://pw@hy2.example:8443/?ech=AAj+DQAEAAAAAA==&sni=real.example";
|
||||||
|
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.EchConfigList.Should().BeEqualTo("AAj+DQAEAAAAAA==");
|
||||||
|
await resolved.Sni.Should().BeEqualTo("real.example");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Canonical SIP002 percent-encodes the plugin argument, and that is what this client's own
|
||||||
|
// exporter emits. This covers the non-canonical spelling instead: the options are a ';'
|
||||||
|
// separated list of 'key=value' pairs, so left unescaped the value always carries '='.
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_NonCanonicalSip002PluginWithLiteralEquals_ShouldConfigureObfs()
|
||||||
|
{
|
||||||
|
const string shareUri =
|
||||||
|
"ss://YWVzLTEyOC1nY206cGFzczEyMw==@1.2.3.4:8388/?plugin=obfs-local;obfs=http;obfs-host=example.com#ss";
|
||||||
|
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.ConfigType.Should().BeEqualTo(EConfigType.Shadowsocks);
|
||||||
|
await resolved.GetTransportExtra().Host.Should().BeEqualTo("example.com");
|
||||||
|
await resolved.GetTransportExtra().RawHeaderType.Should().BeEqualTo(Global.RawHeaderHttp);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ResolveConfig_EscapedQueryValue_ShouldStillDecodeExactlyOnce()
|
||||||
|
{
|
||||||
|
const string shareUri = "hysteria2://pw@hy2.example:8443/?ech=AAj%2BDQAEAAAAAA%3D%3D&obfs=salamander&obfs-password=a%20b";
|
||||||
|
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.EchConfigList.Should().BeEqualTo("AAj+DQAEAAAAAA==");
|
||||||
|
await resolved.GetProtocolExtra().SalamanderPass.Should().BeEqualTo("a b");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
|
public class SocksFmtTests
|
||||||
|
{
|
||||||
|
// The legacy form base64-encodes the whole "user:pass@host:port".
|
||||||
|
[Test]
|
||||||
|
[Arguments("socks://YWRtaW46YWRtaW5AMS4yLjMuNDoxMDgw#demo", "admin", "admin", "1.2.3.4", 1080)]
|
||||||
|
[Arguments("socks://dXNlcjpwYXNzQDEuMi4zLjQ6MTA4MA==#demo", "user", "pass", "1.2.3.4", 1080)]
|
||||||
|
[Arguments("socks://dXNlcjpxd2VydHk/QDEuMi4zLjQ6MTA4MA==#demo", "user", "qwerty?", "1.2.3.4", 1080)]
|
||||||
|
[Arguments("socks://dXNlcjpxd2VydHk_QDEuMi4zLjQ6MTA4MA#demo", "user", "qwerty?", "1.2.3.4", 1080)]
|
||||||
|
public async Task ResolveConfig_LegacyBase64_ShouldDecodeServerAndCredentials(
|
||||||
|
string shareUri, string username, string password, string address, int port)
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.ConfigType.Should().BeEqualTo(EConfigType.SOCKS);
|
||||||
|
await resolved.Address.Should().BeEqualTo(address);
|
||||||
|
await resolved.Port.Should().BeEqualTo(port);
|
||||||
|
await resolved.Username.Should().BeEqualTo(username);
|
||||||
|
await resolved.Password.Should().BeEqualTo(password);
|
||||||
|
await resolved.Remarks.Should().BeEqualTo("demo");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments("socks://YWRtaW46YWRtaW4@1.2.3.4:1080#demo", "admin", "admin")]
|
||||||
|
[Arguments("socks://admin:admin@1.2.3.4:1080#demo", "admin", "admin")]
|
||||||
|
[Arguments("socks://1.2.3.4:1080#demo", "", "")]
|
||||||
|
public async Task ResolveConfig_HostAndPort_ShouldKeepParsingIt(string shareUri, string username, string password)
|
||||||
|
{
|
||||||
|
var resolved = FmtHandler.ResolveConfig(shareUri, out var msg);
|
||||||
|
|
||||||
|
await resolved.Should().NotBeNull().Because($"uri: {shareUri}, msg: {msg}");
|
||||||
|
await resolved!.Address.Should().BeEqualTo("1.2.3.4");
|
||||||
|
await resolved.Port.Should().BeEqualTo(1080);
|
||||||
|
await resolved.Username.Should().BeEqualTo(username);
|
||||||
|
await resolved.Password.Should().BeEqualTo(password);
|
||||||
|
await resolved.Remarks.Should().BeEqualTo("demo");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,9 @@
|
|||||||
using AwesomeAssertions;
|
|
||||||
using ServiceLib.Handler.Fmt;
|
|
||||||
using Xunit;
|
|
||||||
|
|
||||||
namespace ServiceLib.Tests.Fmt;
|
namespace ServiceLib.Tests.Fmt;
|
||||||
|
|
||||||
public class WireguardFmtTests
|
public class WireguardFmtTests
|
||||||
{
|
{
|
||||||
[Fact]
|
[Test]
|
||||||
public void ResolveConfig_ShouldParsePeersAndIgnoreInlineComments()
|
public async Task ResolveConfig_ShouldParsePeersAndIgnoreInlineComments()
|
||||||
{
|
{
|
||||||
const string config =
|
const string config =
|
||||||
"""
|
"""
|
||||||
@@ -15,6 +11,7 @@ public class WireguardFmtTests
|
|||||||
PrivateKey = interface-private-key
|
PrivateKey = interface-private-key
|
||||||
Address = 10.0.0.2/32, fd00::2/128 ; inline comment
|
Address = 10.0.0.2/32, fd00::2/128 ; inline comment
|
||||||
MTU = 1420
|
MTU = 1420
|
||||||
|
DNS = 2001::db8::53, 1.2.3.4, 2001:db8::54
|
||||||
|
|
||||||
[Peer]
|
[Peer]
|
||||||
PublicKey = peer-public-key
|
PublicKey = peer-public-key
|
||||||
@@ -29,19 +26,20 @@ public class WireguardFmtTests
|
|||||||
|
|
||||||
var resolved = WireguardFmt.ResolveConfig(config);
|
var resolved = WireguardFmt.ResolveConfig(config);
|
||||||
|
|
||||||
resolved.Should().NotBeNull();
|
await resolved.Should().NotBeNull();
|
||||||
resolved.Should().HaveCount(2);
|
await resolved.Should().HaveCount(2);
|
||||||
|
|
||||||
var first = resolved![0];
|
var first = resolved![0];
|
||||||
first.Address.Should().Be("2001:db8::1");
|
await first.Address.Should().BeEqualTo("2001:db8::1");
|
||||||
first.Port.Should().Be(51820);
|
await first.Port.Should().BeEqualTo(51820);
|
||||||
first.Password.Should().Be("interface-private-key");
|
await first.Password.Should().BeEqualTo("interface-private-key");
|
||||||
first.GetProtocolExtra().WgReserved.Should().Be("1, 2, 3");
|
await first.GetProtocolExtra().WgReserved.Should().BeEqualTo("1, 2, 3");
|
||||||
first.GetProtocolExtra().WgInterfaceAddress.Should().Be("10.0.0.2/32, fd00::2/128");
|
await first.GetProtocolExtra().WgInterfaceAddress.Should().BeEqualTo("10.0.0.2/32, fd00::2/128");
|
||||||
first.GetProtocolExtra().WgMtu.Should().Be(1420);
|
await first.GetProtocolExtra().WgMtu.Should().BeEqualTo(1420);
|
||||||
|
await first.GetProtocolExtra().WgDns.Should().BeEqualTo("2001::db8::53, 1.2.3.4, 2001:db8::54");
|
||||||
|
|
||||||
var second = resolved[1];
|
var second = resolved[1];
|
||||||
second.Address.Should().Be("example.com");
|
await second.Address.Should().BeEqualTo("example.com");
|
||||||
second.Port.Should().Be(12345);
|
await second.Port.Should().BeEqualTo(12345);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,6 @@ global using System.Diagnostics;
|
|||||||
global using System.Net;
|
global using System.Net;
|
||||||
global using System.Net.NetworkInformation;
|
global using System.Net.NetworkInformation;
|
||||||
global using System.Net.Sockets;
|
global using System.Net.Sockets;
|
||||||
global using System.Reactive;
|
|
||||||
global using System.Reactive.Disposables;
|
|
||||||
global using System.Reactive.Linq;
|
|
||||||
global using System.Reflection;
|
global using System.Reflection;
|
||||||
global using System.Runtime.InteropServices;
|
global using System.Runtime.InteropServices;
|
||||||
global using System.Security.Cryptography;
|
global using System.Security.Cryptography;
|
||||||
@@ -15,10 +12,7 @@ global using System.Text.Json;
|
|||||||
global using System.Text.Json.Nodes;
|
global using System.Text.Json.Nodes;
|
||||||
global using System.Text.Json.Serialization;
|
global using System.Text.Json.Serialization;
|
||||||
global using System.Text.RegularExpressions;
|
global using System.Text.RegularExpressions;
|
||||||
global using DynamicData;
|
|
||||||
global using DynamicData.Binding;
|
|
||||||
global using ReactiveUI;
|
global using ReactiveUI;
|
||||||
global using ReactiveUI.Fody.Helpers;
|
|
||||||
global using ServiceLib.Base;
|
global using ServiceLib.Base;
|
||||||
global using ServiceLib.Common;
|
global using ServiceLib.Common;
|
||||||
global using ServiceLib.Enums;
|
global using ServiceLib.Enums;
|
||||||
@@ -27,6 +21,7 @@ global using ServiceLib.Handler;
|
|||||||
global using ServiceLib.Handler.Builder;
|
global using ServiceLib.Handler.Builder;
|
||||||
global using ServiceLib.Handler.Fmt;
|
global using ServiceLib.Handler.Fmt;
|
||||||
global using ServiceLib.Handler.SysProxy;
|
global using ServiceLib.Handler.SysProxy;
|
||||||
|
global using ServiceLib.Handler.Data;
|
||||||
global using ServiceLib.Helper;
|
global using ServiceLib.Helper;
|
||||||
global using ServiceLib.Manager;
|
global using ServiceLib.Manager;
|
||||||
global using ServiceLib.Models.CoreConfigs;
|
global using ServiceLib.Models.CoreConfigs;
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
namespace ServiceLib.Tests.Handler;
|
||||||
|
|
||||||
|
// launchd terminates the processes of a LaunchAgent job when the job is unloaded. When v2rayN was
|
||||||
|
// started by its own LaunchAgent at login, "launchctl unload" on that agent kills v2rayN itself.
|
||||||
|
// These tests run the macOS code paths against a fake launchctl that only records its arguments.
|
||||||
|
[NotInParallel]
|
||||||
|
public class AutoStartupHandlerTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
public async Task MacOS_SaveWithAutoRunEnabled_ShouldNotUnloadLaunchAgent()
|
||||||
|
{
|
||||||
|
await WithFakeLaunchctl(async (plistPath, readCalls) =>
|
||||||
|
{
|
||||||
|
await InvokeMacOS("SetTaskOSX");
|
||||||
|
|
||||||
|
// UpdateTask on macOS when settings are saved with auto-start still enabled
|
||||||
|
await InvokeMacOS("ClearTaskOSX");
|
||||||
|
await InvokeMacOS("SetTaskOSX");
|
||||||
|
|
||||||
|
var calls = await readCalls();
|
||||||
|
await calls.Any(call => call.StartsWith("unload")).Should().BeFalse();
|
||||||
|
await calls.Should().HaveCount(2);
|
||||||
|
await calls[1].Should().BeEqualTo($"load -w {plistPath}");
|
||||||
|
await File.ReadAllText(plistPath).Contains(Utils.GetExePath()).Should().BeTrue();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task MacOS_DisableAutoRun_ShouldRemovePlistWithoutUnload()
|
||||||
|
{
|
||||||
|
await WithFakeLaunchctl(async (plistPath, readCalls) =>
|
||||||
|
{
|
||||||
|
await InvokeMacOS("SetTaskOSX");
|
||||||
|
|
||||||
|
// UpdateTask on macOS when auto-start is turned off
|
||||||
|
await InvokeMacOS("ClearTaskOSX");
|
||||||
|
|
||||||
|
var calls = await readCalls();
|
||||||
|
await calls.Any(call => call.StartsWith("unload")).Should().BeFalse();
|
||||||
|
await File.Exists(plistPath).Should().BeFalse();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task InvokeMacOS(string methodName)
|
||||||
|
{
|
||||||
|
var method = typeof(AutoStartupHandler).GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic)!;
|
||||||
|
await (Task)method.Invoke(null, null)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task WithFakeLaunchctl(Func<string, Func<Task<string[]>>, Task> test)
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var root = Directory.CreateTempSubdirectory("v2rayN-autostart-").FullName;
|
||||||
|
var binDir = Directory.CreateDirectory(Path.Combine(root, "bin")).FullName;
|
||||||
|
var logPath = Path.Combine(root, "launchctl.log");
|
||||||
|
var launchctl = Path.Combine(binDir, "launchctl");
|
||||||
|
await File.WriteAllTextAsync(launchctl, $"#!/bin/sh\necho \"$*\" >> \"{logPath}\"\n");
|
||||||
|
File.SetUnixFileMode(launchctl, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||||
|
|
||||||
|
var oldHome = Environment.GetEnvironmentVariable("HOME");
|
||||||
|
var oldPath = Environment.GetEnvironmentVariable("PATH");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Environment.SetEnvironmentVariable("HOME", root);
|
||||||
|
Environment.SetEnvironmentVariable("PATH", $"{binDir}:{oldPath}");
|
||||||
|
var plistPath = Path.Combine(root, "Library", "LaunchAgents", $"{Global.AppName}-LaunchAgent.plist");
|
||||||
|
|
||||||
|
await test(plistPath, async () => File.Exists(logPath) ? await File.ReadAllLinesAsync(logPath) : []);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Environment.SetEnvironmentVariable("HOME", oldHome);
|
||||||
|
Environment.SetEnvironmentVariable("PATH", oldPath);
|
||||||
|
Directory.Delete(root, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
|
||||||
|
using ServiceLib.Tests.CoreConfig;
|
||||||
|
|
||||||
|
namespace ServiceLib.Tests.Handler;
|
||||||
|
|
||||||
|
public class ConfigHandlerCustomSubscriptionTests
|
||||||
|
{
|
||||||
|
private const string FullXrayConfigs = """
|
||||||
|
[
|
||||||
|
{"remarks":"custom-1","inbounds":[{"tag":"socks","listen":"127.0.0.1","port":10808,"protocol":"socks","settings":{"auth":"noauth","udp":true}}],"outbounds":[{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"127.0.0.1","port":443,"users":[{"id":"00000000-0000-0000-0000-000000000001","encryption":"none"}]}]},"streamSettings":{"network":"tcp"}}],"routing":{"domainStrategy":"AsIs","rules":[]}},
|
||||||
|
{"remarks":"custom-2","inbounds":[{"tag":"socks","listen":"127.0.0.1","port":10808,"protocol":"socks","settings":{"auth":"noauth","udp":true}}],"outbounds":[{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"127.0.0.1","port":443,"users":[{"id":"00000000-0000-0000-0000-000000000001","encryption":"none"}]}]},"streamSettings":{"network":"tcp"}}],"routing":{"domainStrategy":"AsIs","rules":[]}}
|
||||||
|
]
|
||||||
|
""";
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AddBatchServers_FullConfigsFromSubscription_InheritSubscriptionPreSocksPort()
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig();
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
TestDatabase.Initialize();
|
||||||
|
|
||||||
|
var subId = $"sub-{Guid.NewGuid():N}";
|
||||||
|
await SQLiteHelper.Instance.ReplaceAsync(new SubItem
|
||||||
|
{
|
||||||
|
Id = subId,
|
||||||
|
Remarks = "sub",
|
||||||
|
Url = "http://127.0.0.1/sub",
|
||||||
|
PreSocksPort = 10808,
|
||||||
|
});
|
||||||
|
var oldProfile = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, $"profile-{Guid.NewGuid():N}", "old");
|
||||||
|
oldProfile.Subid = subId;
|
||||||
|
oldProfile.IsSub = true;
|
||||||
|
await SQLiteHelper.Instance.InsertAsync(oldProfile);
|
||||||
|
|
||||||
|
var count = await ConfigDbHandler.AddBatchServers( FullXrayConfigs, subId, true);
|
||||||
|
var profiles = await ConfigDbQuery.ProfileItems(subId) ?? [];
|
||||||
|
|
||||||
|
await count.Should().BeEqualTo(2);
|
||||||
|
await profiles.Should().HaveCount(2);
|
||||||
|
await profiles.Any(profile => profile.IndexId == oldProfile.IndexId).Should().BeFalse();
|
||||||
|
foreach (var profile in profiles)
|
||||||
|
{
|
||||||
|
await profile.ConfigType.Should().BeEqualTo(EConfigType.Custom);
|
||||||
|
await profile.PreSocksPort.Should().BeEqualTo(10808);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AddBatchServers_UnsuccessfulSubscriptionUpdate_PreservesExistingProfiles()
|
||||||
|
{
|
||||||
|
var config = CoreConfigTestFactory.CreateConfig();
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(config);
|
||||||
|
TestDatabase.Initialize();
|
||||||
|
|
||||||
|
var subId = $"sub-failed-{Guid.NewGuid():N}";
|
||||||
|
await SQLiteHelper.Instance.ReplaceAsync(new SubItem
|
||||||
|
{
|
||||||
|
Id = subId,
|
||||||
|
Remarks = "sub",
|
||||||
|
Url = "http://127.0.0.1/sub",
|
||||||
|
});
|
||||||
|
|
||||||
|
var existing = CoreConfigTestFactory.CreateVmessNode(ECoreType.Xray, $"profile-{Guid.NewGuid():N}", "existing");
|
||||||
|
existing.Subid = subId;
|
||||||
|
existing.IsSub = true;
|
||||||
|
await SQLiteHelper.Instance.InsertAsync(existing);
|
||||||
|
|
||||||
|
var invalidSubscription = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("not a valid profile"));
|
||||||
|
var count = await ConfigDbHandler.AddBatchServers( invalidSubscription, subId, true);
|
||||||
|
var profiles = await ConfigDbQuery.ProfileItems(subId) ?? [];
|
||||||
|
|
||||||
|
await (count < 1).Should().BeTrue();
|
||||||
|
await profiles.Should().HaveCount(1);
|
||||||
|
await profiles[0].IndexId.Should().BeEqualTo(existing.IndexId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
namespace ServiceLib.Tests.Handler;
|
||||||
|
|
||||||
|
public class CoreConfigHandlerTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
public async Task GenerateClientConfig_CustomProfileWithMissingSource_ShouldIncludeSourcePath()
|
||||||
|
{
|
||||||
|
var sourcePath = Path.Combine(Path.GetTempPath(), $"v2rayN-missing-{Guid.NewGuid():N}.json");
|
||||||
|
var outputPath = Path.Combine(Path.GetTempPath(), $"v2rayN-output-{Guid.NewGuid():N}.json");
|
||||||
|
var node = new ProfileItem
|
||||||
|
{
|
||||||
|
ConfigType = EConfigType.Custom,
|
||||||
|
Address = sourcePath,
|
||||||
|
Remarks = "missing custom config",
|
||||||
|
};
|
||||||
|
var context = new CoreConfigContext
|
||||||
|
{
|
||||||
|
Node = node,
|
||||||
|
RunCoreType = ECoreType.Xray,
|
||||||
|
};
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await CoreConfigHandler.GenerateClientConfig(context, outputPath);
|
||||||
|
|
||||||
|
await result.Success.Should().BeFalse();
|
||||||
|
await result.Msg.Should().Contain(ResUI.FailedReadConfiguration);
|
||||||
|
await result.Msg.Should().Contain(sourcePath);
|
||||||
|
await File.Exists(outputPath).Should().BeFalse();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
File.Delete(outputPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
namespace ServiceLib.Tests.Helper;
|
||||||
|
|
||||||
|
public class HttpRequestHeadersHelperTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
public async Task TryParse_ShouldAcceptEmptySettingsForExistingSubscriptions()
|
||||||
|
{
|
||||||
|
foreach (var json in new string?[] { null, "", " \r\n ", "{}" })
|
||||||
|
{
|
||||||
|
await HttpRequestHeadersHelper.TryParse(json, out var headers).Should().BeTrue();
|
||||||
|
await headers.Count.Should().BeEqualTo(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task TryParse_ShouldPreserveValuesAndUseCaseInsensitiveNames()
|
||||||
|
{
|
||||||
|
const string json = """
|
||||||
|
{
|
||||||
|
"X-hwid": "my_test_device",
|
||||||
|
"Authorization": "Bearer test:token",
|
||||||
|
"accept": "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Empty": ""
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
|
||||||
|
await HttpRequestHeadersHelper.TryParse(json, out var headers).Should().BeTrue();
|
||||||
|
await headers["x-HWID"].Should().BeEqualTo("my_test_device");
|
||||||
|
await headers["AUTHORIZATION"].Should().BeEqualTo("Bearer test:token");
|
||||||
|
await headers["Accept"].Should().BeEqualTo("application/json");
|
||||||
|
await headers["Content-Type"].Should().BeEqualTo("application/json");
|
||||||
|
await headers["X-Empty"].Should().BeEqualTo("");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments("not-json")]
|
||||||
|
[Arguments("null")]
|
||||||
|
[Arguments("[]")]
|
||||||
|
[Arguments("{\"X-Test\": 1}")]
|
||||||
|
[Arguments("{\"X-Test\": null}")]
|
||||||
|
[Arguments("{\"X-Test\": [\"one\", \"two\"]}")]
|
||||||
|
[Arguments("{\"X-Test\": \"one\", \"X-Test\": \"two\"}")]
|
||||||
|
[Arguments("{\"Accept\": \"one\", \"accept\": \"two\"}")]
|
||||||
|
[Arguments("{\"Bad Header\": \"value\"}")]
|
||||||
|
[Arguments("{\"Bad:Header\": \"value\"}")]
|
||||||
|
[Arguments("{\"\": \"value\"}")]
|
||||||
|
[Arguments("{\"X-Test\": \"one\\r\\nInjected: two\"}")]
|
||||||
|
[Arguments("{\"X-Test\": \"one\\nInjected: two\"}")]
|
||||||
|
[Arguments("{\"X-Test\": \"one\\u0000two\"}")]
|
||||||
|
public async Task TryParse_ShouldRejectInvalidHeadersWithoutReturningPartialSettings(string json)
|
||||||
|
{
|
||||||
|
await HttpRequestHeadersHelper.TryParse(json, out var headers).Should().BeFalse();
|
||||||
|
await headers.Count.Should().BeEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task RequestHeaders_ShouldSurviveDatabaseMigrationAndEditing()
|
||||||
|
{
|
||||||
|
using var database = new SQLiteConnection(":memory:", false);
|
||||||
|
database.Execute("CREATE TABLE SubItem (Id TEXT PRIMARY KEY, Remarks TEXT, Url TEXT)");
|
||||||
|
database.Execute("INSERT INTO SubItem (Id, Remarks, Url) VALUES (?, ?, ?)", "existing", "Existing", "https://example.com/sub");
|
||||||
|
database.CreateTable<SubItem>();
|
||||||
|
|
||||||
|
var item = database.Find<SubItem>("existing");
|
||||||
|
await HttpRequestHeadersHelper.TryParse(item.RequestHeaders, out var oldHeaders).Should().BeTrue();
|
||||||
|
await oldHeaders.Count.Should().BeEqualTo(0);
|
||||||
|
|
||||||
|
item.RequestHeaders = "{\"X-hwid\":\"my_device\"}";
|
||||||
|
database.Update(item, typeof(SubItem));
|
||||||
|
await database.Find<SubItem>(item.Id).RequestHeaders.Should().BeEqualTo(item.RequestHeaders);
|
||||||
|
|
||||||
|
item.RequestHeaders = "";
|
||||||
|
database.Update(item, typeof(SubItem));
|
||||||
|
await database.Find<SubItem>(item.Id).RequestHeaders.Should().BeEqualTo("");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
namespace ServiceLib.Tests.Helper;
|
||||||
|
|
||||||
|
public class RegexGuardTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
public async Task IsRegexMatch_NormalPattern_ShouldMatch()
|
||||||
|
{
|
||||||
|
await Utils.IsRegexMatch("HK-node-01", "HK|香港").Should().BeTrue();
|
||||||
|
await Utils.IsRegexMatch("JP-node-01", "HK|香港").Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task IsRegexMatch_EmptyPattern_ShouldPassThrough()
|
||||||
|
{
|
||||||
|
await Utils.IsRegexMatch("anything", "").Should().BeTrue();
|
||||||
|
await Utils.IsRegexMatch("anything", null).Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task IsRegexMatch_InvalidPattern_ShouldFailOpen()
|
||||||
|
{
|
||||||
|
await Utils.IsRegexMatch("node-01", "([unclosed").Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task IsRegexMatch_EvilPattern_ShouldTimeoutAndFailOpen()
|
||||||
|
{
|
||||||
|
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||||||
|
var result = Utils.IsRegexMatch(new string('a', 30) + "!", "(a+)+$");
|
||||||
|
sw.Stop();
|
||||||
|
|
||||||
|
await result.Should().BeTrue();
|
||||||
|
await (sw.Elapsed < TimeSpan.FromSeconds(30)).Should().BeTrue().Because(
|
||||||
|
$"evil pattern must be cut off by timeout, took {sw.Elapsed}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
namespace ServiceLib.Tests.Helper;
|
||||||
|
|
||||||
|
[NotInParallel]
|
||||||
|
public class SQLiteHelperTests
|
||||||
|
{
|
||||||
|
private static readonly Lazy<SQLiteHelper> Database = new(() =>
|
||||||
|
{
|
||||||
|
var database = SQLiteHelper.Instance;
|
||||||
|
database.CreateTable<HelperRow>();
|
||||||
|
database.CreateTable<ReplacementRow>();
|
||||||
|
database.CreateTable<DeleteAllRow>();
|
||||||
|
database.CreateTable<NoPrimaryKeyRow>();
|
||||||
|
return database;
|
||||||
|
});
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task RepeatedSharedSchemaInitialization_ShouldSucceedDuringAnExclusiveTransaction()
|
||||||
|
{
|
||||||
|
TestDatabase.Initialize();
|
||||||
|
var database = Database.Value;
|
||||||
|
var item = new SubItem { Id = Guid.NewGuid().ToString("N"), Remarks = "schema-init", Url = "http://127.0.0.1/sub" };
|
||||||
|
await database.InsertAsync(item);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await database.ExecuteAsync("BEGIN EXCLUSIVE");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
TestDatabase.Initialize();
|
||||||
|
var saved = await database.TableAsync<SubItem>().Where(row => row.Id == item.Id).FirstAsync();
|
||||||
|
await saved.Id.Should().BeEqualTo(item.Id);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.ExecuteAsync("ROLLBACK");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.DeleteAsync(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task SingleWrites_ShouldPreserveValuesAndDeleteByPrimaryKey()
|
||||||
|
{
|
||||||
|
var database = Database.Value;
|
||||||
|
var id = Guid.NewGuid().ToString("N");
|
||||||
|
var row = new HelperRow { Id = id, Value = $"{id}-original" };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await (await database.InsertAsync(row)).Should().BeEqualTo(1);
|
||||||
|
await (await database.ReplaceAsync(new HelperRow { Id = id, Value = $"{id}-replacement" })).Should().BeEqualTo(1);
|
||||||
|
row.Value = $"{id}-updated";
|
||||||
|
await (await database.UpdateAsync(row)).Should().BeEqualTo(1);
|
||||||
|
|
||||||
|
var rows = await database.QueryAsync<HelperRow>($"SELECT * FROM SQLiteHelperTestRows WHERE Id = '{id}'");
|
||||||
|
await rows.Count.Should().BeEqualTo(1);
|
||||||
|
await rows[0].Value.Should().BeEqualTo($"{id}-updated");
|
||||||
|
await (await database.TableAsync<HelperRow>().Where(item => item.Id == id).CountAsync()).Should().BeEqualTo(1);
|
||||||
|
|
||||||
|
row.Value = "not-the-stored-value";
|
||||||
|
await (await database.DeleteAsync(row)).Should().BeEqualTo(1);
|
||||||
|
await (await database.DeleteAsync(row)).Should().BeEqualTo(0);
|
||||||
|
await (await database.TableAsync<HelperRow>().Where(item => item.Id == id).CountAsync()).Should().BeEqualTo(0);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.ExecuteAsync($"DELETE FROM SQLiteHelperTestRows WHERE Id = '{id}'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task BulkWrites_ShouldCommitEveryRowAndReturnAffectedCounts()
|
||||||
|
{
|
||||||
|
var database = Database.Value;
|
||||||
|
var prefix = Guid.NewGuid().ToString("N");
|
||||||
|
var rows = new[]
|
||||||
|
{
|
||||||
|
new HelperRow { Id = $"{prefix}-first", Value = $"{prefix}-original-first" },
|
||||||
|
new HelperRow { Id = $"{prefix}-second", Value = $"{prefix}-original-second" },
|
||||||
|
};
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await (await database.InsertAllAsync(rows)).Should().BeEqualTo(2);
|
||||||
|
rows[0].Value = $"{prefix}-updated-first";
|
||||||
|
rows[1].Value = $"{prefix}-updated-second";
|
||||||
|
await (await database.UpdateAllAsync(rows)).Should().BeEqualTo(2);
|
||||||
|
|
||||||
|
var saved = await database.QueryAsync<HelperRow>($"SELECT * FROM SQLiteHelperTestRows WHERE Id LIKE '{prefix}%' ORDER BY Id");
|
||||||
|
await saved.Count.Should().BeEqualTo(2);
|
||||||
|
await saved[0].Value.Should().BeEqualTo($"{prefix}-updated-first");
|
||||||
|
await saved[1].Value.Should().BeEqualTo($"{prefix}-updated-second");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.ExecuteAsync($"DELETE FROM SQLiteHelperTestRows WHERE Id LIKE '{prefix}%'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task InsertAllAsync_ShouldRollBackEarlierRowsWhenALaterInsertFails()
|
||||||
|
{
|
||||||
|
var database = Database.Value;
|
||||||
|
var id = Guid.NewGuid().ToString("N");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SQLiteException? error = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await database.InsertAllAsync(new[]
|
||||||
|
{
|
||||||
|
new HelperRow { Id = id, Value = $"{id}-first" },
|
||||||
|
new HelperRow { Id = id, Value = $"{id}-duplicate" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (SQLiteException exception)
|
||||||
|
{
|
||||||
|
error = exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
await error.Should().NotBeNull();
|
||||||
|
await (await database.TableAsync<HelperRow>().Where(item => item.Id == id).CountAsync()).Should().BeEqualTo(0);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.ExecuteAsync($"DELETE FROM SQLiteHelperTestRows WHERE Id = '{id}'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task UpdateAllAsync_ShouldRollBackEarlierChangesWhenALaterUpdateFails()
|
||||||
|
{
|
||||||
|
var database = Database.Value;
|
||||||
|
var prefix = Guid.NewGuid().ToString("N");
|
||||||
|
var first = new HelperRow { Id = $"{prefix}-first", Value = $"{prefix}-original-first" };
|
||||||
|
var second = new HelperRow { Id = $"{prefix}-second", Value = $"{prefix}-original-second" };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await database.InsertAllAsync(new[] { first, second });
|
||||||
|
first.Value = $"{prefix}-updated-first";
|
||||||
|
second.Value = first.Value;
|
||||||
|
SQLiteException? error = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await database.UpdateAllAsync(new[] { first, second });
|
||||||
|
}
|
||||||
|
catch (SQLiteException exception)
|
||||||
|
{
|
||||||
|
error = exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
await error.Should().NotBeNull();
|
||||||
|
var saved = await database.QueryAsync<HelperRow>($"SELECT * FROM SQLiteHelperTestRows WHERE Id LIKE '{prefix}%' ORDER BY Id");
|
||||||
|
await saved.Count.Should().BeEqualTo(2);
|
||||||
|
await saved[0].Value.Should().BeEqualTo($"{prefix}-original-first");
|
||||||
|
await saved[1].Value.Should().BeEqualTo($"{prefix}-original-second");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.ExecuteAsync($"DELETE FROM SQLiteHelperTestRows WHERE Id LIKE '{prefix}%'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task EmptyBatches_ShouldReturnZero()
|
||||||
|
{
|
||||||
|
var database = Database.Value;
|
||||||
|
await (await database.InsertAllAsync(Array.Empty<HelperRow>())).Should().BeEqualTo(0);
|
||||||
|
await (await database.UpdateAllAsync(Array.Empty<HelperRow>())).Should().BeEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task DeleteAsync_ShouldRejectRowsWithoutAPrimaryKey()
|
||||||
|
{
|
||||||
|
var database = Database.Value;
|
||||||
|
var value = Guid.NewGuid().ToString("N");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var row = new NoPrimaryKeyRow { Value = value };
|
||||||
|
await database.InsertAsync(row);
|
||||||
|
NotSupportedException? error = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await database.DeleteAsync(row);
|
||||||
|
}
|
||||||
|
catch (NotSupportedException exception)
|
||||||
|
{
|
||||||
|
error = exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
await error.Should().NotBeNull();
|
||||||
|
await (await database.TableAsync<NoPrimaryKeyRow>().Where(item => item.Value == value).CountAsync()).Should().BeEqualTo(1);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.ExecuteAsync($"DELETE FROM SQLiteHelperNoPrimaryKeyTestRows WHERE Value = '{value}'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task DeleteAllAsync_ShouldReturnTheNumberOfDeletedRows()
|
||||||
|
{
|
||||||
|
var database = Database.Value;
|
||||||
|
await database.DeleteAllAsync<DeleteAllRow>();
|
||||||
|
await database.InsertAllAsync(new[] { new DeleteAllRow { Id = "first" }, new DeleteAllRow { Id = "second" } });
|
||||||
|
|
||||||
|
await (await database.DeleteAllAsync<DeleteAllRow>()).Should().BeEqualTo(2);
|
||||||
|
await (await database.TableAsync<DeleteAllRow>().CountAsync()).Should().BeEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ReplaceAllAsync_ShouldInsertAndReplaceRowsAndReturnAffectedCounts()
|
||||||
|
{
|
||||||
|
var database = Database.Value;
|
||||||
|
var prefix = Guid.NewGuid().ToString("N");
|
||||||
|
var existing = new HelperRow { Id = $"{prefix}-existing", Value = $"{prefix}-original" };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await database.InsertAsync(existing);
|
||||||
|
var replacements = new[]
|
||||||
|
{
|
||||||
|
new HelperRow { Id = existing.Id, Value = $"{prefix}-updated" },
|
||||||
|
new HelperRow { Id = $"{prefix}-new", Value = $"{prefix}-new-value" },
|
||||||
|
};
|
||||||
|
|
||||||
|
await (await database.ReplaceAllAsync(replacements)).Should().BeEqualTo(2);
|
||||||
|
await (await database.ReplaceAllAsync(replacements)).Should().BeEqualTo(2);
|
||||||
|
var saved = await database.QueryAsync<HelperRow>($"SELECT * FROM SQLiteHelperTestRows WHERE Id LIKE '{prefix}%' ORDER BY Id");
|
||||||
|
|
||||||
|
await saved.Count.Should().BeEqualTo(2);
|
||||||
|
await saved[0].Value.Should().BeEqualTo($"{prefix}-updated");
|
||||||
|
await saved[1].Value.Should().BeEqualTo($"{prefix}-new-value");
|
||||||
|
await (await database.ReplaceAllAsync(Array.Empty<HelperRow>())).Should().BeEqualTo(0);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.ExecuteAsync($"DELETE FROM SQLiteHelperTestRows WHERE Id LIKE '{prefix}%'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ReplaceAllAsync_ShouldRollBackReplacementsAndInsertsWhenALaterRowFails()
|
||||||
|
{
|
||||||
|
var database = Database.Value;
|
||||||
|
var prefix = Guid.NewGuid().ToString("N");
|
||||||
|
var existing = new ReplacementRow { Id = $"{prefix}-existing", Value = "original" };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await database.InsertAsync(existing);
|
||||||
|
SQLiteException? error = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await database.ReplaceAllAsync(new[]
|
||||||
|
{
|
||||||
|
new ReplacementRow { Id = existing.Id, Value = "replacement" },
|
||||||
|
new ReplacementRow { Id = $"{prefix}-new", Value = "inserted" },
|
||||||
|
new ReplacementRow { Id = $"{prefix}-invalid", Value = null! },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (SQLiteException exception)
|
||||||
|
{
|
||||||
|
error = exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
await error.Should().NotBeNull();
|
||||||
|
var saved = await database.QueryAsync<ReplacementRow>($"SELECT * FROM SQLiteHelperReplaceAllTestRows WHERE Id LIKE '{prefix}%'");
|
||||||
|
await saved.Count.Should().BeEqualTo(1);
|
||||||
|
await saved[0].Id.Should().BeEqualTo(existing.Id);
|
||||||
|
await saved[0].Value.Should().BeEqualTo("original");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.ExecuteAsync($"DELETE FROM SQLiteHelperReplaceAllTestRows WHERE Id LIKE '{prefix}%'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Table("SQLiteHelperTestRows")]
|
||||||
|
public class HelperRow
|
||||||
|
{
|
||||||
|
[PrimaryKey]
|
||||||
|
public string Id { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[Unique]
|
||||||
|
public string Value { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Table("SQLiteHelperDeleteAllTestRows")]
|
||||||
|
public class DeleteAllRow
|
||||||
|
{
|
||||||
|
[PrimaryKey]
|
||||||
|
public string Id { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Table("SQLiteHelperReplaceAllTestRows")]
|
||||||
|
public class ReplacementRow
|
||||||
|
{
|
||||||
|
[PrimaryKey]
|
||||||
|
public string Id { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[NotNull]
|
||||||
|
public string Value { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
[Table("SQLiteHelperNoPrimaryKeyTestRows")]
|
||||||
|
public class NoPrimaryKeyRow
|
||||||
|
{
|
||||||
|
public string Value { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
namespace ServiceLib.Tests.Manager;
|
||||||
|
|
||||||
|
public class CoreManagerTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments(ECoreType.sing_box)]
|
||||||
|
[Arguments(ECoreType.mihomo)]
|
||||||
|
[Arguments(ECoreType.Xray)]
|
||||||
|
public async Task ShouldRunAsSudo_TunLaunchOnNonWindows_RequiresElevation(ECoreType coreType)
|
||||||
|
{
|
||||||
|
await CoreManager.ShouldRunAsSudo(isTunLaunch: true, coreType, isNonWindows: true).Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ShouldRunAsSudo_NonTunLaunch_ShouldNotElevate()
|
||||||
|
{
|
||||||
|
// Regression guard for the macOS TUN failure: the elevation decision must follow
|
||||||
|
// the context snapshot that generated the config. A launch whose snapshot has TUN
|
||||||
|
// disabled must never elevate, and a launch whose snapshot has TUN enabled must
|
||||||
|
// elevate regardless of later changes to the live config.
|
||||||
|
await CoreManager.ShouldRunAsSudo(isTunLaunch: false, ECoreType.sing_box, isNonWindows: true).Should().BeFalse();
|
||||||
|
await CoreManager.ShouldRunAsSudo(isTunLaunch: false, ECoreType.Xray, isNonWindows: true).Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task ShouldRunAsSudo_OnWindows_ShouldNotElevate()
|
||||||
|
{
|
||||||
|
await CoreManager.ShouldRunAsSudo(isTunLaunch: true, ECoreType.sing_box, isNonWindows: false).Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments(ECoreType.v2fly)]
|
||||||
|
[Arguments(ECoreType.hysteria)]
|
||||||
|
[Arguments(null)]
|
||||||
|
public async Task ShouldRunAsSudo_UnsupportedCoreType_ShouldNotElevate(ECoreType? coreType)
|
||||||
|
{
|
||||||
|
await CoreManager.ShouldRunAsSudo(isTunLaunch: true, coreType, isNonWindows: true).Should().BeFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
namespace ServiceLib.Tests.Manager;
|
||||||
|
|
||||||
|
public class ProfileExManagerConcurrencyTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
public async Task SetTestDelay_FromManyThreads_ShouldNotThrow()
|
||||||
|
{
|
||||||
|
var manager = CreateManager();
|
||||||
|
var exceptions = new List<Exception>();
|
||||||
|
var threads = Environment.ProcessorCount * 2;
|
||||||
|
|
||||||
|
//Hammer the same manager from several streams at once: the queue is mutated while
|
||||||
|
//other threads keep pushing into it
|
||||||
|
var barrier = new Barrier(threads);
|
||||||
|
Parallel.For(0, threads, t =>
|
||||||
|
{
|
||||||
|
barrier.SignalAndWait();
|
||||||
|
for (var i = 0; i < 5000; i++)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
manager.SetTestDelay($"index{i % 500}", i);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
lock (exceptions)
|
||||||
|
{
|
||||||
|
exceptions.Add(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await exceptions.Count.Should().BeEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task SetTestDelay_FromManyThreads_ShouldNotLoseQueuedIds()
|
||||||
|
{
|
||||||
|
var manager = CreateManager();
|
||||||
|
var ids = 500;
|
||||||
|
|
||||||
|
Parallel.For(0, Environment.ProcessorCount * 2, t =>
|
||||||
|
{
|
||||||
|
for (var i = 0; i < 5000; i++)
|
||||||
|
{
|
||||||
|
manager.SetTestDelay($"id{i % ids}", i);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
var drained = Drain(manager);
|
||||||
|
await drained.Count.Should().BeGreaterThanOrEqualTo(ids);
|
||||||
|
await drained.Distinct().Count().Should().BeEqualTo(ids);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task SetTestDelay_ShouldCreateOneEntryPerIndex()
|
||||||
|
{
|
||||||
|
var manager = CreateManager();
|
||||||
|
|
||||||
|
await RunConcurrentUpdates(8, 10, (_, index) => manager.SetTestDelay($"same{index}", index));
|
||||||
|
|
||||||
|
var items = await manager.GetProfileExs();
|
||||||
|
await items.Count.Should().BeEqualTo(10);
|
||||||
|
await items.Select(t => t.IndexId).Distinct().Count().Should().BeEqualTo(10);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task SetTestResults_ConcurrentUpdates_ShouldKeepAllValuesOnOneEntry()
|
||||||
|
{
|
||||||
|
var manager = CreateManager();
|
||||||
|
Action<string>[] updates =
|
||||||
|
[
|
||||||
|
indexId => manager.SetTestDelay(indexId, 123),
|
||||||
|
indexId => manager.SetTestSpeed(indexId, 45.6m),
|
||||||
|
indexId => manager.SetTestMessage(indexId, "result"),
|
||||||
|
indexId => manager.SetTestIpInfo(indexId, "203.0.113.1"),
|
||||||
|
indexId => manager.SetSort(indexId, 7)
|
||||||
|
];
|
||||||
|
|
||||||
|
await RunConcurrentUpdates(updates.Length, 100, (worker, index) => updates[worker]($"profile{index}"));
|
||||||
|
|
||||||
|
var items = await manager.GetProfileExs();
|
||||||
|
await items.Count.Should().BeEqualTo(100);
|
||||||
|
await items.Select(item => item.IndexId).Distinct().Count().Should().BeEqualTo(100);
|
||||||
|
foreach (var item in items)
|
||||||
|
{
|
||||||
|
await item.Delay.Should().BeEqualTo(123);
|
||||||
|
await item.Speed.Should().BeEqualTo(45.6m);
|
||||||
|
await item.Message.Should().BeEqualTo("result");
|
||||||
|
await item.IpInfo.Should().BeEqualTo("203.0.113.1");
|
||||||
|
await item.Sort.Should().BeEqualTo(7);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task SetSort_FromManyThreads_ShouldTrackMaxSort()
|
||||||
|
{
|
||||||
|
var manager = CreateManager();
|
||||||
|
await manager.GetMaxSort().Should().BeEqualTo(0);
|
||||||
|
|
||||||
|
Parallel.For(0, 1000, i => manager.SetSort($"sort{i % 100}", i));
|
||||||
|
manager.SetTestDelay("unsorted", 100);
|
||||||
|
|
||||||
|
await manager.GetMaxSort().Should().BeEqualTo(999);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task RunConcurrentUpdates(int workers, int indexes, Action<int, int> update)
|
||||||
|
{
|
||||||
|
using var barrier = new Barrier(workers);
|
||||||
|
var tasks = Enumerable.Range(0, workers).Select(worker => Task.Factory.StartNew(() =>
|
||||||
|
{
|
||||||
|
for (var index = 0; index < indexes; index++)
|
||||||
|
{
|
||||||
|
if (!barrier.SignalAndWait(TimeSpan.FromSeconds(10)))
|
||||||
|
{
|
||||||
|
throw new TimeoutException("Concurrent update workers did not synchronize.");
|
||||||
|
}
|
||||||
|
update(worker, index);
|
||||||
|
}
|
||||||
|
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray();
|
||||||
|
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ProfileExManager CreateManager()
|
||||||
|
{
|
||||||
|
return (ProfileExManager)Activator.CreateInstance(typeof(ProfileExManager), nonPublic: true)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<string> Drain(ProfileExManager manager)
|
||||||
|
{
|
||||||
|
var queue = (System.Collections.Concurrent.ConcurrentQueue<string>)typeof(ProfileExManager)
|
||||||
|
.GetField("_queIndexIds", BindingFlags.Instance | BindingFlags.NonPublic)!
|
||||||
|
.GetValue(manager)!;
|
||||||
|
|
||||||
|
var result = new List<string>();
|
||||||
|
while (queue.TryDequeue(out var id))
|
||||||
|
{
|
||||||
|
result.Add(id);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
namespace ServiceLib.Tests.Manager;
|
||||||
|
|
||||||
|
public class ProfileExManagerPersistenceTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
public async Task SaveTo_NewProfilesWithRepeatedResults_ShouldPersistEveryProfile()
|
||||||
|
{
|
||||||
|
TestDatabase.Initialize();
|
||||||
|
var manager = new ProfileExManager();
|
||||||
|
var ids = Enumerable.Range(0, 3).Select(_ => Guid.NewGuid().ToString("N")).ToArray();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var id in ids)
|
||||||
|
{
|
||||||
|
manager.SetTestDelay(id, 42);
|
||||||
|
manager.SetTestSpeed(id, 12.5m);
|
||||||
|
manager.SetTestMessage(id, "completed");
|
||||||
|
manager.SetTestIpInfo(id, "192.0.2.1");
|
||||||
|
manager.SetSort(id, 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
await manager.SaveTo();
|
||||||
|
|
||||||
|
foreach (var id in ids)
|
||||||
|
{
|
||||||
|
var saved = await SQLiteHelper.Instance.TableAsync<ProfileExItem>()
|
||||||
|
.Where(t => t.IndexId == id).ToListAsync();
|
||||||
|
await saved.Count.Should().BeEqualTo(1);
|
||||||
|
await saved[0].Delay.Should().BeEqualTo(42);
|
||||||
|
await saved[0].Speed.Should().BeEqualTo(12.5m);
|
||||||
|
await saved[0].Message.Should().BeEqualTo("completed");
|
||||||
|
await saved[0].IpInfo.Should().BeEqualTo("192.0.2.1");
|
||||||
|
await saved[0].Sort.Should().BeEqualTo(7);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
foreach (var id in ids)
|
||||||
|
{
|
||||||
|
await SQLiteHelper.Instance.DeleteAsync(new ProfileExItem { IndexId = id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task SaveTo_MixedNewAndExistingProfiles_ShouldInsertAndUpdateResults()
|
||||||
|
{
|
||||||
|
TestDatabase.Initialize();
|
||||||
|
var manager = new ProfileExManager();
|
||||||
|
var existingId = Guid.NewGuid().ToString("N");
|
||||||
|
var newId = Guid.NewGuid().ToString("N");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await SQLiteHelper.Instance.InsertAsync(new ProfileExItem
|
||||||
|
{
|
||||||
|
IndexId = existingId,
|
||||||
|
Delay = 1,
|
||||||
|
Speed = 2,
|
||||||
|
});
|
||||||
|
manager.SetTestDelay(existingId, 100);
|
||||||
|
manager.SetTestSpeed(existingId, 20);
|
||||||
|
manager.SetTestDelay(newId, 200);
|
||||||
|
manager.SetTestIpInfo(newId, "192.0.2.2");
|
||||||
|
|
||||||
|
await manager.SaveTo();
|
||||||
|
|
||||||
|
var existing = await SQLiteHelper.Instance.TableAsync<ProfileExItem>()
|
||||||
|
.Where(t => t.IndexId == existingId).FirstAsync();
|
||||||
|
await existing.Delay.Should().BeEqualTo(100);
|
||||||
|
await existing.Speed.Should().BeEqualTo(20m);
|
||||||
|
var inserted = await SQLiteHelper.Instance.TableAsync<ProfileExItem>()
|
||||||
|
.Where(t => t.IndexId == newId).ToListAsync();
|
||||||
|
await inserted.Count.Should().BeEqualTo(1);
|
||||||
|
await inserted[0].Delay.Should().BeEqualTo(200);
|
||||||
|
await inserted[0].IpInfo.Should().BeEqualTo("192.0.2.2");
|
||||||
|
|
||||||
|
manager.SetTestDelay(newId, 300);
|
||||||
|
await manager.SaveTo();
|
||||||
|
var updated = await SQLiteHelper.Instance.TableAsync<ProfileExItem>()
|
||||||
|
.Where(t => t.IndexId == newId).FirstAsync();
|
||||||
|
await updated.Delay.Should().BeEqualTo(300);
|
||||||
|
await updated.IpInfo.Should().BeEqualTo("192.0.2.2");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await SQLiteHelper.Instance.DeleteAsync(new ProfileExItem { IndexId = existingId });
|
||||||
|
await SQLiteHelper.Instance.DeleteAsync(new ProfileExItem { IndexId = newId });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +1,24 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
<IsPackable>false</IsPackable>
|
<IsPackable>false</IsPackable>
|
||||||
<IsTestProject>true</IsTestProject>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
</PropertyGroup>
|
<PublishAot>true</PublishAot>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="AwesomeAssertions" />
|
<PackageReference Include="TUnit" />
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
<PackageReference Include="TUnit.Assertions.Should" />
|
||||||
<PackageReference Include="xunit.runner.visualstudio">
|
</ItemGroup>
|
||||||
<PrivateAssets>all</PrivateAssets>
|
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
|
||||||
</PackageReference>
|
|
||||||
<PackageReference Include="xunit.v3" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\ServiceLib\ServiceLib.csproj" />
|
<ProjectReference Include="..\ServiceLib\ServiceLib.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="TUnit.Assertions.Should" />
|
||||||
|
<Using Include="TUnit.Assertions.Should.Extensions" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
namespace ServiceLib.Tests.Services;
|
||||||
|
|
||||||
|
public class DownloadServiceHeadersTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments(false, false)]
|
||||||
|
[Arguments(false, true)]
|
||||||
|
[Arguments(true, false)]
|
||||||
|
[Arguments(true, true)]
|
||||||
|
public async Task TryDownloadString_ShouldSendCustomHeadersThroughBothDownloaders(bool useProxy, bool failFirstRequest)
|
||||||
|
{
|
||||||
|
await CertPemManager.Instance.Init(new Config { GuiItem = new GUIItem() });
|
||||||
|
await using var server = new SubscriptionHttpServer(failFirstRequest);
|
||||||
|
const string json = """
|
||||||
|
{
|
||||||
|
"accept": "application/json",
|
||||||
|
"user-agent": "CustomSubscriptionClient/1.0",
|
||||||
|
"authorization": "Bearer test-token",
|
||||||
|
"X-hwid": "test-device",
|
||||||
|
"Cookie": "session=test",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
await HttpRequestHeadersHelper.TryParse(json, out var headers).Should().BeTrue();
|
||||||
|
IWebProxy? proxy = useProxy ? new WebProxy(server.Url) : null;
|
||||||
|
var handler = proxy is null ? HttpClientHelper.Instance.DirectHandler : HttpClientHelper.CreateProxySocketsHttpHandler(proxy, new());
|
||||||
|
var headersHandler = HttpRequestHeadersHelper.CreateHandler(handler, "CustomSubscriptionClient/1.0", "*/*", headers);
|
||||||
|
using var service = new DownloadService
|
||||||
|
{
|
||||||
|
Handler = headersHandler,
|
||||||
|
DisposeHandler = true,
|
||||||
|
};
|
||||||
|
var uri = new UriBuilder(useProxy ? "http://subscription.invalid/sub" : server.Url)
|
||||||
|
{
|
||||||
|
UserName = "user",
|
||||||
|
Password = "password",
|
||||||
|
}.Uri;
|
||||||
|
|
||||||
|
var content = await service.TryDownloadString(uri.AbsoluteUri).WaitAsync(TimeSpan.FromSeconds(20));
|
||||||
|
|
||||||
|
await content.Should().BeEqualTo(SubscriptionHttpServer.Body);
|
||||||
|
await (server.Requests.Count >= (failFirstRequest ? 2 : 1)).Should().BeTrue();
|
||||||
|
foreach (var request in server.Requests)
|
||||||
|
{
|
||||||
|
await request["Accept"].Should().BeEqualTo("application/json");
|
||||||
|
await request["User-Agent"].Should().BeEqualTo("CustomSubscriptionClient/1.0");
|
||||||
|
await request["Authorization"].Should().BeEqualTo("Bearer test-token");
|
||||||
|
await request["X-hwid"].Should().BeEqualTo("test-device");
|
||||||
|
await request["Cookie"].Should().BeEqualTo("session=test");
|
||||||
|
await request["Content-Type"].Should().BeEqualTo("application/json");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments(false)]
|
||||||
|
[Arguments(true)]
|
||||||
|
public async Task TryDownloadString_ShouldKeepDefaultAcceptUserAgentAndBasicAuth(bool failFirstRequest)
|
||||||
|
{
|
||||||
|
await CertPemManager.Instance.Init(new Config { GuiItem = new GUIItem() });
|
||||||
|
await using var server = new SubscriptionHttpServer(failFirstRequest);
|
||||||
|
using var handler = HttpRequestHeadersHelper.CreateHandler(HttpClientHelper.CreateSocketsHttpHandler(false, new()), "ExistingClient/1.0", "*/*", null);
|
||||||
|
var service = new DownloadService { Handler = handler };
|
||||||
|
var helper = new DownloaderHelper { Handler = handler };
|
||||||
|
var uri = new UriBuilder(server.Url) { UserName = "user", Password = "password" }.Uri;
|
||||||
|
|
||||||
|
await (await service.TryDownloadString(uri.AbsoluteUri).WaitAsync(TimeSpan.FromSeconds(20))).Should().BeEqualTo(SubscriptionHttpServer.Body);
|
||||||
|
await (await helper.DownloadStringAsync(uri.AbsoluteUri).WaitAsync(TimeSpan.FromSeconds(20))).Should().BeEqualTo(SubscriptionHttpServer.Body);
|
||||||
|
foreach (var request in server.Requests)
|
||||||
|
{
|
||||||
|
await request["Accept"].Should().BeEqualTo("*/*");
|
||||||
|
await request["User-Agent"].Should().BeEqualTo("ExistingClient/1.0");
|
||||||
|
await request["Authorization"].Should().BeEqualTo("Basic dXNlcjpwYXNzd29yZA==");
|
||||||
|
await request.ContainsKey("X-hwid").Should().BeFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task TryDownloadString_ShouldNotShareHeadersWithOtherDownloads()
|
||||||
|
{
|
||||||
|
await CertPemManager.Instance.Init(new Config { GuiItem = new GUIItem() });
|
||||||
|
await using var server = new SubscriptionHttpServer();
|
||||||
|
var handler = HttpRequestHeadersHelper.CreateHandler(HttpClientHelper.CreateSocketsHttpHandler(false, new()), "TestClient/1.0", "*/*", new Dictionary<string, string> { ["X-hwid"] = "first-device" });
|
||||||
|
using var subscription = new DownloadService
|
||||||
|
{
|
||||||
|
Handler = handler,
|
||||||
|
DisposeHandler = true,
|
||||||
|
};
|
||||||
|
var ordinaryDownload = new DownloadService();
|
||||||
|
|
||||||
|
await (await subscription.TryDownloadString(server.Url)).Should().BeEqualTo(SubscriptionHttpServer.Body);
|
||||||
|
await (await ordinaryDownload.TryDownloadString(server.Url)).Should().BeEqualTo(SubscriptionHttpServer.Body);
|
||||||
|
|
||||||
|
var requests = server.Requests.ToArray();
|
||||||
|
await requests.Length.Should().BeEqualTo(2);
|
||||||
|
await requests[0]["X-hwid"].Should().BeEqualTo("first-device");
|
||||||
|
await requests[1].ContainsKey("X-hwid").Should().BeFalse();
|
||||||
|
await requests[1].ContainsKey("Accept").Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class SubscriptionHttpServer : IAsyncDisposable
|
||||||
|
{
|
||||||
|
public const string Body = "subscription-test-content";
|
||||||
|
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
|
||||||
|
private readonly CancellationTokenSource _cancellation = new();
|
||||||
|
private readonly Task _serverTask;
|
||||||
|
private readonly bool _failFirstRequest;
|
||||||
|
|
||||||
|
public string Url { get; }
|
||||||
|
public ConcurrentQueue<Dictionary<string, string>> Requests { get; } = new();
|
||||||
|
|
||||||
|
public SubscriptionHttpServer(bool failFirstRequest = false)
|
||||||
|
{
|
||||||
|
_failFirstRequest = failFirstRequest;
|
||||||
|
_listener.Start();
|
||||||
|
Url = $"http://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/subscription";
|
||||||
|
_serverTask = ServeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ServeAsync()
|
||||||
|
{
|
||||||
|
var cancellationToken = _cancellation.Token;
|
||||||
|
while (!cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
using var client = await _listener.AcceptTcpClientAsync(cancellationToken);
|
||||||
|
await using var stream = client.GetStream();
|
||||||
|
using var reader = new StreamReader(stream, Encoding.ASCII, leaveOpen: true);
|
||||||
|
var requestLine = await reader.ReadLineAsync(cancellationToken);
|
||||||
|
if (requestLine == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
while (await reader.ReadLineAsync(cancellationToken) is { Length: > 0 } line)
|
||||||
|
{
|
||||||
|
var separator = line.IndexOf(':');
|
||||||
|
var name = line.Substring(0, separator);
|
||||||
|
var value = line.Substring(separator + 1).Trim();
|
||||||
|
headers[name] = headers.TryGetValue(name, out var previous) ? $"{previous}, {value}" : value;
|
||||||
|
}
|
||||||
|
Requests.Enqueue(headers);
|
||||||
|
|
||||||
|
var status = _failFirstRequest && Requests.Count == 1 ? "503 Service Unavailable" : "200 OK";
|
||||||
|
var body = requestLine.StartsWith("HEAD ") ? "" : Body;
|
||||||
|
var response = $"HTTP/1.1 {status}\r\nContent-Length: {Body.Length}\r\nConnection: close\r\n\r\n{body}";
|
||||||
|
await stream.WriteAsync(Encoding.ASCII.GetBytes(response), cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
await _cancellation.CancelAsync();
|
||||||
|
_listener.Stop();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _serverTask;
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_cancellation.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
namespace ServiceLib.Tests.Services;
|
||||||
|
|
||||||
|
public class SpeedtestServiceBatchTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments(0)]
|
||||||
|
[Arguments(1000)]
|
||||||
|
public async Task EmptySelection_ShouldReturnNoBatches(int pageSize)
|
||||||
|
{
|
||||||
|
await GetBatches([], pageSize).Count.Should().BeEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
[Arguments(0)]
|
||||||
|
[Arguments(-1)]
|
||||||
|
public async Task NonPositivePageSize_ShouldKeepEveryEligibleProfile(int pageSize)
|
||||||
|
{
|
||||||
|
var profiles = CreateProfiles();
|
||||||
|
var batches = GetBatches(profiles, pageSize);
|
||||||
|
|
||||||
|
await batches.Count.Should().BeEqualTo(profiles.Count);
|
||||||
|
await batches.SelectMany(batch => batch).Count().Should().BeEqualTo(profiles.Count);
|
||||||
|
foreach (var profile in profiles)
|
||||||
|
{
|
||||||
|
await batches.SelectMany(batch => batch).Count(item => ReferenceEquals(item, profile)).Should().BeEqualTo(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task NormalBatches_ShouldRespectPageSizeAndKeepCoreTypesSeparate()
|
||||||
|
{
|
||||||
|
var profiles = CreateProfiles();
|
||||||
|
var batches = GetBatches(profiles, 2);
|
||||||
|
|
||||||
|
await batches.Count.Should().BeEqualTo(3);
|
||||||
|
await batches.SelectMany(batch => batch).Count().Should().BeEqualTo(profiles.Count);
|
||||||
|
foreach (var batch in batches)
|
||||||
|
{
|
||||||
|
await (batch.Count > 0 && batch.Count <= 2).Should().BeTrue();
|
||||||
|
await batch.Select(item => item.CoreType).Distinct().Count().Should().BeEqualTo(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<ServerTestItem> CreateProfiles() =>
|
||||||
|
[
|
||||||
|
new() { CoreType = ECoreType.Xray },
|
||||||
|
new() { CoreType = ECoreType.Xray },
|
||||||
|
new() { CoreType = ECoreType.Xray },
|
||||||
|
new() { CoreType = ECoreType.sing_box },
|
||||||
|
new() { CoreType = ECoreType.sing_box }
|
||||||
|
];
|
||||||
|
|
||||||
|
private static List<List<ServerTestItem>> GetBatches(List<ServerTestItem> profiles, int pageSize)
|
||||||
|
{
|
||||||
|
var service = new SpeedtestService(new Config { SpeedTestItem = new() }, _ => Task.CompletedTask);
|
||||||
|
var method = typeof(SpeedtestService).GetMethod("GetTestBatchItem", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||||
|
return (List<List<ServerTestItem>>)method.Invoke(service, [profiles, pageSize])!;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
namespace ServiceLib.Tests.Services;
|
||||||
|
|
||||||
|
public class SpeedtestServiceResultTests
|
||||||
|
{
|
||||||
|
[Test]
|
||||||
|
[Arguments(ESpeedActionType.Speedtest, 0)]
|
||||||
|
[Arguments(ESpeedActionType.Mixedtest, 0)]
|
||||||
|
[Arguments(ESpeedActionType.Realping, 12.5)]
|
||||||
|
public async Task StartingATest_ShouldClearTheLastSpeedOfSpeedTests(ESpeedActionType actionType, double expected)
|
||||||
|
{
|
||||||
|
var indexId = Guid.NewGuid().ToString();
|
||||||
|
ProfileExManager.Instance.SetTestSpeed(indexId, 12.5m);
|
||||||
|
|
||||||
|
await SetTestResult([new() { IndexId = indexId }], actionType, ResUI.Speedtesting);
|
||||||
|
|
||||||
|
var profileEx = (await ProfileExManager.Instance.GetProfileExs()).First(t => t.IndexId == indexId);
|
||||||
|
await profileEx.Speed.Should().BeEqualTo((decimal)expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task SetTestResult(List<ServerTestItem> items, ESpeedActionType actionType, string message)
|
||||||
|
{
|
||||||
|
var service = new SpeedtestService(new Config { SpeedTestItem = new() }, _ => Task.CompletedTask);
|
||||||
|
var method = typeof(SpeedtestService).GetMethod("SetTestResultAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||||
|
return (Task)method.Invoke(service, [items, actionType, message])!;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace ServiceLib.Tests;
|
||||||
|
|
||||||
|
internal static class TestDatabase
|
||||||
|
{
|
||||||
|
private static readonly Lazy<SQLiteHelper> Database = new(() =>
|
||||||
|
{
|
||||||
|
var database = SQLiteHelper.Instance;
|
||||||
|
database.CreateTable<SubItem>();
|
||||||
|
database.CreateTable<ProfileItem>();
|
||||||
|
database.CreateTable<ProfileExItem>();
|
||||||
|
return database;
|
||||||
|
});
|
||||||
|
|
||||||
|
public static void Initialize() => _ = Database.Value;
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
using ReactiveUI.Builder;
|
||||||
|
using ServiceLib.Tests.CoreConfig;
|
||||||
|
using ServiceLib.ViewModels;
|
||||||
|
|
||||||
|
namespace ServiceLib.Tests.ViewModels;
|
||||||
|
|
||||||
|
[NotInParallel]
|
||||||
|
public class AddServerViewModelTests
|
||||||
|
{
|
||||||
|
static AddServerViewModelTests()
|
||||||
|
{
|
||||||
|
RxAppBuilder.CreateReactiveUIBuilder().WithCoreServices().BuildApp();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task XdriveServices_ShouldContainExpectedServices()
|
||||||
|
{
|
||||||
|
await Global.XdriveServices.Count.Should().BeEqualTo(3);
|
||||||
|
await Global.XdriveServices[0].Should().BeEqualTo("google-drive");
|
||||||
|
await Global.XdriveServices[1].Should().BeEqualTo("s3");
|
||||||
|
await Global.XdriveServices[2].Should().BeEqualTo("local");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AddServerViewModel_ShouldBindXdrivePropertiesFromTransportExtra()
|
||||||
|
{
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(CoreConfigTestFactory.CreateConfig());
|
||||||
|
|
||||||
|
var profile = new ProfileItem
|
||||||
|
{
|
||||||
|
IndexId = "test-node",
|
||||||
|
ConfigType = EConfigType.VLESS,
|
||||||
|
Address = "example.com",
|
||||||
|
Port = 443,
|
||||||
|
Network = nameof(ETransport.xdrive),
|
||||||
|
};
|
||||||
|
profile.SetTransportExtra(new TransportExtraItem
|
||||||
|
{
|
||||||
|
XdriveService = "s3",
|
||||||
|
XdriveRemoteFolder = "/remote/path",
|
||||||
|
XdriveSecrets = "sec1,sec2",
|
||||||
|
XdriveS3Endpoint = "s3.example.com",
|
||||||
|
XdriveS3Region = "us-west-2",
|
||||||
|
XdriveS3Bucket = "my-bucket",
|
||||||
|
XdriveS3PathStyle = true,
|
||||||
|
XdriveExtra = "{\"concurrency\":4}",
|
||||||
|
});
|
||||||
|
|
||||||
|
var vm = new AddServerViewModel(profile);
|
||||||
|
|
||||||
|
await vm.XdriveService.Should().BeEqualTo("s3");
|
||||||
|
await vm.XdriveRemoteFolder.Should().BeEqualTo("/remote/path");
|
||||||
|
await vm.XdriveSecrets.Should().BeEqualTo("sec1,sec2");
|
||||||
|
await vm.XdriveS3Endpoint.Should().BeEqualTo("s3.example.com");
|
||||||
|
await vm.XdriveS3Region.Should().BeEqualTo("us-west-2");
|
||||||
|
await vm.XdriveS3Bucket.Should().BeEqualTo("my-bucket");
|
||||||
|
await vm.XdriveS3PathStyle.Should().BeEqualTo(true);
|
||||||
|
await vm.XdriveExtra.Should().BeEqualTo("{\"concurrency\":4}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AddServerViewModel_TransportFriendlyProperties_ShouldAdaptToXdrive()
|
||||||
|
{
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(CoreConfigTestFactory.CreateConfig());
|
||||||
|
|
||||||
|
var profile = new ProfileItem
|
||||||
|
{
|
||||||
|
IndexId = "test-node",
|
||||||
|
ConfigType = EConfigType.VLESS,
|
||||||
|
Address = "example.com",
|
||||||
|
Port = 443,
|
||||||
|
Network = nameof(ETransport.xdrive),
|
||||||
|
};
|
||||||
|
profile.SetTransportExtra(new TransportExtraItem
|
||||||
|
{
|
||||||
|
XdriveService = "s3",
|
||||||
|
XdriveRemoteFolder = "/folder",
|
||||||
|
XdriveS3Endpoint = "s3.custom.endpoint",
|
||||||
|
XdriveExtra = "{\"segmentBytes\":1024}",
|
||||||
|
});
|
||||||
|
|
||||||
|
var vm = new AddServerViewModel(profile);
|
||||||
|
|
||||||
|
// Getters
|
||||||
|
await vm.TransportHeaderType.Should().BeEqualTo("s3");
|
||||||
|
await vm.TransportHost.Should().BeEqualTo("s3.custom.endpoint");
|
||||||
|
await vm.TransportPath.Should().BeEqualTo("/folder");
|
||||||
|
await vm.TransportExtraText.Should().BeEqualTo("{\"segmentBytes\":1024}");
|
||||||
|
|
||||||
|
// Setters
|
||||||
|
vm.TransportHeaderType = "google-drive";
|
||||||
|
await vm.XdriveService.Should().BeEqualTo("google-drive");
|
||||||
|
await vm.TransportHeaderType.Should().BeEqualTo("google-drive");
|
||||||
|
|
||||||
|
vm.TransportHost = "s3.new.endpoint";
|
||||||
|
await vm.XdriveS3Endpoint.Should().BeEqualTo("s3.new.endpoint");
|
||||||
|
await vm.TransportHost.Should().BeEqualTo("s3.new.endpoint");
|
||||||
|
|
||||||
|
vm.TransportPath = "/new/folder";
|
||||||
|
await vm.XdriveRemoteFolder.Should().BeEqualTo("/new/folder");
|
||||||
|
await vm.TransportPath.Should().BeEqualTo("/new/folder");
|
||||||
|
|
||||||
|
vm.TransportExtraText = "{\"flushIntervalMs\":500}";
|
||||||
|
await vm.XdriveExtra.Should().BeEqualTo("{\"flushIntervalMs\":500}");
|
||||||
|
await vm.TransportExtraText.Should().BeEqualTo("{\"flushIntervalMs\":500}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task AddServerViewModel_SaveServerAsync_ShouldPersistXdriveFields()
|
||||||
|
{
|
||||||
|
CoreConfigTestFactory.BindAppManagerConfig(CoreConfigTestFactory.CreateConfig());
|
||||||
|
|
||||||
|
var profile = new ProfileItem
|
||||||
|
{
|
||||||
|
IndexId = "test-node",
|
||||||
|
Remarks = "test remarks",
|
||||||
|
ConfigType = EConfigType.VLESS,
|
||||||
|
Address = "example.com",
|
||||||
|
Port = 443,
|
||||||
|
Password = Guid.NewGuid().ToString(),
|
||||||
|
Network = nameof(ETransport.xdrive),
|
||||||
|
};
|
||||||
|
|
||||||
|
var vm = new AddServerViewModel(profile);
|
||||||
|
vm.XdriveService = "s3";
|
||||||
|
vm.XdriveRemoteFolder = "/backup";
|
||||||
|
vm.XdriveSecrets = "key,secret";
|
||||||
|
vm.XdriveS3Endpoint = "s3.amazonaws.com";
|
||||||
|
vm.XdriveS3Region = "eu-central-1";
|
||||||
|
vm.XdriveS3Bucket = "bucket-1";
|
||||||
|
vm.XdriveS3PathStyle = false;
|
||||||
|
vm.XdriveExtra = "{\"concurrency\":8}";
|
||||||
|
|
||||||
|
var saveMethod = typeof(AddServerViewModel).GetMethod("SaveServerAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||||
|
await (Task)saveMethod.Invoke(vm, null)!;
|
||||||
|
|
||||||
|
var extra = vm.SelectedSource.GetTransportExtra();
|
||||||
|
await extra.XdriveService.Should().BeEqualTo("s3");
|
||||||
|
await extra.XdriveRemoteFolder.Should().BeEqualTo("/backup");
|
||||||
|
await extra.XdriveSecrets.Should().BeEqualTo("key,secret");
|
||||||
|
await extra.XdriveS3Endpoint.Should().BeEqualTo("s3.amazonaws.com");
|
||||||
|
await extra.XdriveS3Region.Should().BeEqualTo("eu-central-1");
|
||||||
|
await extra.XdriveS3Bucket.Should().BeEqualTo("bucket-1");
|
||||||
|
await extra.XdriveS3PathStyle.Should().BeEqualTo(false);
|
||||||
|
await extra.XdriveExtra.Should().BeEqualTo("{\"concurrency\":8}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Test]
|
||||||
|
public async Task Localization_ShouldProvideXdriveStrings()
|
||||||
|
{
|
||||||
|
await ResUI.XdriveService.IsNotEmpty().Should().BeTrue();
|
||||||
|
await ResUI.XdriveRemoteFolder.IsNotEmpty().Should().BeTrue();
|
||||||
|
await ResUI.XdriveSecrets.IsNotEmpty().Should().BeTrue();
|
||||||
|
await ResUI.XdriveS3Endpoint.IsNotEmpty().Should().BeTrue();
|
||||||
|
await ResUI.XdriveS3Region.IsNotEmpty().Should().BeTrue();
|
||||||
|
await ResUI.XdriveS3Bucket.IsNotEmpty().Should().BeTrue();
|
||||||
|
await ResUI.XdriveS3PathStyle.IsNotEmpty().Should().BeTrue();
|
||||||
|
await ResUI.XdriveExtra.IsNotEmpty().Should().BeTrue();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,16 +2,21 @@ namespace ServiceLib.UdpTest;
|
|||||||
|
|
||||||
public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposable
|
public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposable
|
||||||
{
|
{
|
||||||
|
private bool _initialized;
|
||||||
|
private IPEndPoint _relayEndPoint;
|
||||||
private TcpClient _tcpClient;
|
private TcpClient _tcpClient;
|
||||||
private UdpClient _udpClient;
|
private UdpClient _udpClient;
|
||||||
private IPEndPoint _relayEndPoint;
|
|
||||||
|
|
||||||
private bool _initialized = false;
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_tcpClient?.Dispose();
|
||||||
|
_udpClient?.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Send UDP data to a remote endpoint (IP address)
|
/// Send UDP data to a remote endpoint (IP address)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public async Task SendAsync(IPEndPoint remote, byte[] data)
|
public async Task SendAsync(IPEndPoint remote, byte[] data, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var addrData = new Socks5AddressData
|
var addrData = new Socks5AddressData
|
||||||
{
|
{
|
||||||
@@ -19,19 +24,20 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
? Socks5AddressData.AddrTypeIPv4
|
? Socks5AddressData.AddrTypeIPv4
|
||||||
: Socks5AddressData.AddrTypeIPv6,
|
: Socks5AddressData.AddrTypeIPv6,
|
||||||
Host = remote.Address.ToString(),
|
Host = remote.Address.ToString(),
|
||||||
Port = (ushort)remote.Port
|
Port = (ushort)remote.Port,
|
||||||
};
|
};
|
||||||
var packet = BuildSocks5UdpPacket(addrData, data);
|
var packet = BuildSocks5UdpPacket(addrData, data);
|
||||||
await _udpClient.SendAsync(packet, packet.Length, _relayEndPoint);
|
await _udpClient.SendAsync(packet.AsMemory(), _relayEndPoint, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Send UDP data to a remote endpoint (domain name or IP address)
|
/// Send UDP data to a remote endpoint (domain name or IP address)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="host">Domain name or IP address</param>
|
/// <param name="host">Domain name or IP address</param>
|
||||||
/// <param name="port">Port number</param>
|
/// <param name="port">Port number</param>
|
||||||
/// <param name="data">Data to send</param>
|
/// <param name="data">Data to send</param>
|
||||||
public async Task SendAsync(string host, ushort port, byte[] data)
|
/// <param name="ct">Cancellation token</param>
|
||||||
|
public async Task SendAsync(string host, ushort port, byte[] data, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var addrData = new Socks5AddressData();
|
var addrData = new Socks5AddressData();
|
||||||
|
|
||||||
@@ -53,11 +59,12 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
addrData.Port = port;
|
addrData.Port = port;
|
||||||
|
|
||||||
var packet = BuildSocks5UdpPacket(addrData, data);
|
var packet = BuildSocks5UdpPacket(addrData, data);
|
||||||
await _udpClient.SendAsync(packet, packet.Length, _relayEndPoint);
|
// await _udpClient.SendAsync(packet, packet.Length, _relayEndPoint);
|
||||||
|
await _udpClient.SendAsync(packet.AsMemory(), _relayEndPoint, ct);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Receive UDP data from remote endpoint
|
/// Receive UDP data from remote endpoint
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="cancellationToken">Cancellation token to cancel the receive operation</param>
|
/// <param name="cancellationToken">Cancellation token to cancel the receive operation</param>
|
||||||
/// <returns>Remote endpoint information and received data</returns>
|
/// <returns>Remote endpoint information and received data</returns>
|
||||||
@@ -69,16 +76,6 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
return (remote, payload);
|
return (remote, payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Represents a remote endpoint that can be either an IP address or a domain name
|
|
||||||
/// </summary>
|
|
||||||
public class Socks5RemoteEndpoint(string host, ushort port, bool isDomain)
|
|
||||||
{
|
|
||||||
public string Host { get; set; } = host;
|
|
||||||
public ushort Port { get; set; } = port;
|
|
||||||
public bool IsDomain { get; set; } = isDomain;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static byte[] BuildSocks5UdpPacket(Socks5AddressData addressData, byte[] data)
|
private static byte[] BuildSocks5UdpPacket(Socks5AddressData addressData, byte[] data)
|
||||||
{
|
{
|
||||||
using var ms = new MemoryStream();
|
using var ms = new MemoryStream();
|
||||||
@@ -104,6 +101,11 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
throw new ArgumentException("Invalid SOCKS5 UDP packet: too short");
|
throw new ArgumentException("Invalid SOCKS5 UDP packet: too short");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (packet[0] != 0x00 || packet[1] != 0x00)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Invalid SOCKS5 UDP packet: RSV field must be 0");
|
||||||
|
}
|
||||||
|
|
||||||
var offset = 0;
|
var offset = 0;
|
||||||
|
|
||||||
// RSV (2 bytes) - Reserved field, skip
|
// RSV (2 bytes) - Reserved field, skip
|
||||||
@@ -196,83 +198,34 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
return (remote, data);
|
return (remote, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
/// <summary>
|
||||||
|
/// Represents a remote endpoint that can be either an IP address or a domain name
|
||||||
|
/// </summary>
|
||||||
|
public class Socks5RemoteEndpoint(string host, ushort port, bool isDomain)
|
||||||
{
|
{
|
||||||
_tcpClient.Dispose();
|
public string Host { get; set; } = host;
|
||||||
_udpClient.Dispose();
|
public ushort Port { get; set; } = port;
|
||||||
|
public bool IsDomain { get; set; } = isDomain;
|
||||||
}
|
}
|
||||||
|
|
||||||
#region SOCKS5 Connection Handling
|
|
||||||
|
|
||||||
private const byte Socks5Version = 0x05;
|
|
||||||
private const byte SocksCmdUdpAssociate = 0x03;
|
|
||||||
|
|
||||||
public async Task<bool> EstablishUdpAssociationAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
if (_initialized)
|
|
||||||
{
|
|
||||||
Dispose();
|
|
||||||
_initialized = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
_udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
|
|
||||||
_tcpClient = new TcpClient();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await _tcpClient.ConnectAsync(socks5Host, socks5TcpPort, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (SocketException)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var tcpControlStream = _tcpClient.GetStream();
|
|
||||||
|
|
||||||
byte[] handshakeRequest = [Socks5Version, 0x01, 0x00];
|
|
||||||
await tcpControlStream.WriteAsync(handshakeRequest, cancellationToken).ConfigureAwait(false);
|
|
||||||
var handshakeResponse = new byte[2];
|
|
||||||
if (await tcpControlStream.ReadAsync(handshakeResponse, cancellationToken).ConfigureAwait(false) < 2 ||
|
|
||||||
handshakeResponse[0] != Socks5Version || handshakeResponse[1] != 0x00)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var clientAddrForSocks = new Socks5AddressData
|
|
||||||
{
|
|
||||||
AddressType = Socks5AddressData.AddrTypeIPv4,
|
|
||||||
Host = "0.0.0.0",
|
|
||||||
Port = 0
|
|
||||||
};
|
|
||||||
using var udpAssociateReqMs = new MemoryStream();
|
|
||||||
udpAssociateReqMs.WriteByte(Socks5Version);
|
|
||||||
udpAssociateReqMs.WriteByte(SocksCmdUdpAssociate);
|
|
||||||
udpAssociateReqMs.WriteByte(0x00);
|
|
||||||
udpAssociateReqMs.Write(clientAddrForSocks.ToBytes());
|
|
||||||
await tcpControlStream.WriteAsync(udpAssociateReqMs.ToArray(), cancellationToken).ConfigureAwait(false);
|
|
||||||
|
|
||||||
var verRepRsv = new byte[3];
|
|
||||||
if (await tcpControlStream.ReadAsync(verRepRsv, cancellationToken).ConfigureAwait(false) < 3 ||
|
|
||||||
verRepRsv[0] != Socks5Version || verRepRsv[1] != 0x00)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var proxyRelaySocksAddr =
|
|
||||||
await Socks5AddressData.ParseAsync(tcpControlStream, cancellationToken).ConfigureAwait(false);
|
|
||||||
if (proxyRelaySocksAddr == null || !IPAddress.TryParse(proxyRelaySocksAddr.Host, out var proxyRelayIp))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
_relayEndPoint = new IPEndPoint(proxyRelayIp, proxyRelaySocksAddr.Port);
|
|
||||||
_initialized = true;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion SOCKS5 Connection Handling
|
|
||||||
|
|
||||||
#region SOCKS5 Address Handling
|
#region SOCKS5 Address Handling
|
||||||
|
|
||||||
|
private static async Task<bool> TryReadExactlyAsync(
|
||||||
|
Stream stream,
|
||||||
|
Memory<byte> buffer,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await stream.ReadExactlyAsync(buffer, cancellationToken).ConfigureAwait(false);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (EndOfStreamException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private class Socks5AddressData
|
private class Socks5AddressData
|
||||||
{
|
{
|
||||||
public const byte AddrTypeIPv4 = 0x01;
|
public const byte AddrTypeIPv4 = 0x01;
|
||||||
@@ -343,7 +296,7 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
var typeByte = new byte[1];
|
var typeByte = new byte[1];
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (await stream.ReadAsync(typeByte.AsMemory(0, 1), ct).ConfigureAwait(false) < 1)
|
if (!await TryReadExactlyAsync(stream, typeByte, ct).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -353,7 +306,7 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
{
|
{
|
||||||
case AddrTypeIPv4:
|
case AddrTypeIPv4:
|
||||||
var ipv4Bytes = new byte[4];
|
var ipv4Bytes = new byte[4];
|
||||||
if (await stream.ReadAsync(ipv4Bytes.AsMemory(0, 4), ct).ConfigureAwait(false) < 4)
|
if (!await TryReadExactlyAsync(stream, ipv4Bytes, ct).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -363,7 +316,7 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
|
|
||||||
case AddrTypeDomain:
|
case AddrTypeDomain:
|
||||||
var lenByte = new byte[1];
|
var lenByte = new byte[1];
|
||||||
if (await stream.ReadAsync(lenByte.AsMemory(0, 1), ct).ConfigureAwait(false) < 1)
|
if (!await TryReadExactlyAsync(stream, lenByte, ct).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -375,8 +328,7 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
var domainBytes = new byte[lenByte[0]];
|
var domainBytes = new byte[lenByte[0]];
|
||||||
if (await stream.ReadAsync(domainBytes.AsMemory(0, domainBytes.Length), ct)
|
if (!await TryReadExactlyAsync(stream, domainBytes, ct).ConfigureAwait(false))
|
||||||
.ConfigureAwait(false) < domainBytes.Length)
|
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -388,7 +340,7 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
|
|
||||||
case AddrTypeIPv6:
|
case AddrTypeIPv6:
|
||||||
var ipv6Bytes = new byte[16];
|
var ipv6Bytes = new byte[16];
|
||||||
if (await stream.ReadAsync(ipv6Bytes.AsMemory(0, 16), ct).ConfigureAwait(false) < 16)
|
if (!await TryReadExactlyAsync(stream, ipv6Bytes, ct).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -401,7 +353,7 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
}
|
}
|
||||||
|
|
||||||
var portBytes = new byte[2];
|
var portBytes = new byte[2];
|
||||||
if (await stream.ReadAsync(portBytes.AsMemory(0, 2), ct).ConfigureAwait(false) < 2)
|
if (!await TryReadExactlyAsync(stream, portBytes, ct).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -417,4 +369,73 @@ public class Socks5UdpChannel(string socks5Host, int socks5TcpPort) : IDisposabl
|
|||||||
}
|
}
|
||||||
|
|
||||||
#endregion SOCKS5 Address Handling
|
#endregion SOCKS5 Address Handling
|
||||||
|
|
||||||
|
#region SOCKS5 Connection Handling
|
||||||
|
|
||||||
|
private const byte Socks5Version = 0x05;
|
||||||
|
private const byte SocksCmdUdpAssociate = 0x03;
|
||||||
|
|
||||||
|
public async Task<bool> EstablishUdpAssociationAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (_initialized)
|
||||||
|
{
|
||||||
|
Dispose();
|
||||||
|
_initialized = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
|
||||||
|
_tcpClient = new TcpClient();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _tcpClient.ConnectAsync(socks5Host, socks5TcpPort, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (SocketException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var tcpControlStream = _tcpClient.GetStream();
|
||||||
|
|
||||||
|
byte[] handshakeRequest = [Socks5Version, 0x01, 0x00];
|
||||||
|
await tcpControlStream.WriteAsync(handshakeRequest, cancellationToken).ConfigureAwait(false);
|
||||||
|
var handshakeResponse = new byte[2];
|
||||||
|
if (!await TryReadExactlyAsync(tcpControlStream, handshakeResponse, cancellationToken).ConfigureAwait(false) ||
|
||||||
|
handshakeResponse[0] != Socks5Version || handshakeResponse[1] != 0x00)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var clientAddrForSocks = new Socks5AddressData
|
||||||
|
{
|
||||||
|
AddressType = Socks5AddressData.AddrTypeIPv4,
|
||||||
|
Host = "0.0.0.0",
|
||||||
|
Port = 0,
|
||||||
|
};
|
||||||
|
using var udpAssociateReqMs = new MemoryStream();
|
||||||
|
udpAssociateReqMs.WriteByte(Socks5Version);
|
||||||
|
udpAssociateReqMs.WriteByte(SocksCmdUdpAssociate);
|
||||||
|
udpAssociateReqMs.WriteByte(0x00);
|
||||||
|
udpAssociateReqMs.Write(clientAddrForSocks.ToBytes());
|
||||||
|
await tcpControlStream.WriteAsync(udpAssociateReqMs.ToArray(), cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var verRepRsv = new byte[3];
|
||||||
|
if (!await TryReadExactlyAsync(tcpControlStream, verRepRsv, cancellationToken).ConfigureAwait(false) ||
|
||||||
|
verRepRsv[0] != Socks5Version || verRepRsv[1] != 0x00)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var proxyRelaySocksAddr =
|
||||||
|
await Socks5AddressData.ParseAsync(tcpControlStream, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (proxyRelaySocksAddr == null || !IPAddress.TryParse(proxyRelaySocksAddr.Host, out var proxyRelayIp))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_relayEndPoint = new IPEndPoint(proxyRelayIp, proxyRelaySocksAddr.Port);
|
||||||
|
_initialized = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion SOCKS5 Connection Handling
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ public class DnsService : IUdpTest
|
|||||||
// Question: www.google.com, Type A, Class IN
|
// Question: www.google.com, Type A, Class IN
|
||||||
0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F,
|
0x03, 0x77, 0x77, 0x77, 0x06, 0x67, 0x6F, 0x6F,
|
||||||
0x67, 0x6C, 0x65, 0x03, 0x63, 0x6F, 0x6D, 0x00,
|
0x67, 0x6C, 0x65, 0x03, 0x63, 0x6F, 0x6D, 0x00,
|
||||||
0x00, 0x01, 0x00, 0x01
|
0x00, 0x01, 0x00, 0x01,
|
||||||
];
|
];
|
||||||
|
|
||||||
public byte[] BuildUdpRequestPacket()
|
public byte[] BuildUdpRequestPacket()
|
||||||
|
|||||||
@@ -17,13 +17,13 @@ public class McBeService : IUdpTest
|
|||||||
0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78,
|
0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78,
|
||||||
// Client GUID (random 16 bytes)
|
// Client GUID (random 16 bytes)
|
||||||
0x66, 0x0E, 0xAB, 0xBC, 0x61, 0x0D, 0x1F, 0x4E,
|
0x66, 0x0E, 0xAB, 0xBC, 0x61, 0x0D, 0x1F, 0x4E,
|
||||||
0xA4, 0x40, 0x8C, 0x65, 0xC1, 0xBE, 0xF5, 0x4B
|
0xA4, 0x40, 0x8C, 0x65, 0xC1, 0xBE, 0xF5, 0x4B,
|
||||||
];
|
];
|
||||||
|
|
||||||
private static readonly byte[] McBeMagicBytes =
|
private static readonly byte[] McBeMagicBytes =
|
||||||
[
|
[
|
||||||
0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE,
|
0x00, 0xFF, 0xFF, 0x00, 0xFE, 0xFE, 0xFE, 0xFE,
|
||||||
0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78
|
0xFD, 0xFD, 0xFD, 0xFD, 0x12, 0x34, 0x56, 0x78,
|
||||||
];
|
];
|
||||||
|
|
||||||
private static readonly List<string> ValidGameModes =
|
private static readonly List<string> ValidGameModes =
|
||||||
@@ -31,7 +31,7 @@ public class McBeService : IUdpTest
|
|||||||
"Survival",
|
"Survival",
|
||||||
"Creative",
|
"Creative",
|
||||||
"Adventure",
|
"Adventure",
|
||||||
"Spectator"
|
"Spectator",
|
||||||
];
|
];
|
||||||
|
|
||||||
public byte[] BuildUdpRequestPacket()
|
public byte[] BuildUdpRequestPacket()
|
||||||
@@ -61,6 +61,10 @@ public class McBeService : IUdpTest
|
|||||||
return false; // Magic bytes do not match
|
return false; // Magic bytes do not match
|
||||||
}
|
}
|
||||||
var stringLength = (ushort)((mcbeResponseBytes[33] << 8) | mcbeResponseBytes[34]);
|
var stringLength = (ushort)((mcbeResponseBytes[33] << 8) | mcbeResponseBytes[34]);
|
||||||
|
if (mcbeResponseBytes.Length < 35 + stringLength)
|
||||||
|
{
|
||||||
|
return false; // Not enough data for the string
|
||||||
|
}
|
||||||
var stringData = Encoding.UTF8.GetString(mcbeResponseBytes.Skip(35).Take(stringLength).ToArray());
|
var stringData = Encoding.UTF8.GetString(mcbeResponseBytes.Skip(35).Take(stringLength).ToArray());
|
||||||
var stringParts = stringData.Split(';');
|
var stringParts = stringData.Split(';');
|
||||||
// check Game Mode str
|
// check Game Mode str
|
||||||
|
|||||||
@@ -31,10 +31,7 @@ public class StunService : IUdpTest
|
|||||||
if (stunResponseBytes.Length >= 2)
|
if (stunResponseBytes.Length >= 2)
|
||||||
{
|
{
|
||||||
var messageType = (stunResponseBytes[0] << 8) | stunResponseBytes[1];
|
var messageType = (stunResponseBytes[0] << 8) | stunResponseBytes[1];
|
||||||
if (messageType is 0x0101 or 0x0111)
|
return messageType is 0x0101 or 0x0111;
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ namespace ServiceLib.UdpTest;
|
|||||||
public class UdpTestService
|
public class UdpTestService
|
||||||
{
|
{
|
||||||
private const string DefaultUdpTestType = "ntp";
|
private const string DefaultUdpTestType = "ntp";
|
||||||
private readonly IUdpTest _udpTest;
|
|
||||||
|
|
||||||
private static readonly IReadOnlyDictionary<string, Func<IUdpTest>> UdpTestFactories =
|
private static readonly IReadOnlyDictionary<string, Func<IUdpTest>> UdpTestFactories =
|
||||||
new Dictionary<string, Func<IUdpTest>>(StringComparer.OrdinalIgnoreCase)
|
new Dictionary<string, Func<IUdpTest>>(StringComparer.OrdinalIgnoreCase)
|
||||||
@@ -16,6 +15,8 @@ public class UdpTestService
|
|||||||
["mcbe"] = () => new McBeService(),
|
["mcbe"] = () => new McBeService(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
private readonly IUdpTest _udpTest;
|
||||||
|
|
||||||
private UdpTestService(IUdpTest udpTest)
|
private UdpTestService(IUdpTest udpTest)
|
||||||
{
|
{
|
||||||
_udpTest = udpTest;
|
_udpTest = udpTest;
|
||||||
@@ -88,24 +89,26 @@ public class UdpTestService
|
|||||||
return (targetServerHost, _udpTest.GetDefaultTargetPort());
|
return (targetServerHost, _udpTest.GetDefaultTargetPort());
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<TimeSpan> SendUdpRequestAsync(string targetServerHost, int socks5Port, TimeSpan operationTimeout)
|
public async Task<TimeSpan> SendUdpRequestAsync(string targetServerHost, int socks5Port,
|
||||||
|
CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
using var cts = new CancellationTokenSource(operationTimeout);
|
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||||
var cancellationToken = cts.Token;
|
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token);
|
||||||
|
var linkedCt = linkedCts.Token;
|
||||||
var udpRequestPacket = _udpTest.BuildUdpRequestPacket();
|
var udpRequestPacket = _udpTest.BuildUdpRequestPacket();
|
||||||
if (udpRequestPacket == null || udpRequestPacket.Length == 0)
|
if (udpRequestPacket == null || udpRequestPacket.Length == 0)
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Failed to build UDP request packet.");
|
throw new InvalidOperationException("Failed to build UDP request packet.");
|
||||||
}
|
}
|
||||||
using var channel = new Socks5UdpChannel("127.0.0.1", socks5Port);
|
using var channel = new Socks5UdpChannel("127.0.0.1", socks5Port);
|
||||||
if (!await channel.EstablishUdpAssociationAsync(cancellationToken).ConfigureAwait(false))
|
if (!await channel.EstablishUdpAssociationAsync(linkedCt).ConfigureAwait(false))
|
||||||
{
|
{
|
||||||
throw new Exception("Failed to establish UDP association with SOCKS5 proxy.");
|
throw new Exception("Failed to establish UDP association with SOCKS5 proxy.");
|
||||||
}
|
}
|
||||||
|
|
||||||
var (targetHost, targetPort) = ParseHostAndPort(targetServerHost);
|
var (targetHost, targetPort) = ParseHostAndPort(targetServerHost);
|
||||||
|
|
||||||
byte[] udpReceiveResult = null;
|
byte[]? validUdpReceiveResult = null;
|
||||||
|
|
||||||
// Get minimum round trip time from two attempts
|
// Get minimum round trip time from two attempts
|
||||||
var roundTripTime = TimeSpan.MaxValue;
|
var roundTripTime = TimeSpan.MaxValue;
|
||||||
@@ -116,11 +119,15 @@ public class UdpTestService
|
|||||||
{
|
{
|
||||||
var stopwatch = new Stopwatch();
|
var stopwatch = new Stopwatch();
|
||||||
stopwatch.Start();
|
stopwatch.Start();
|
||||||
await channel.SendAsync(targetHost, targetPort, udpRequestPacket).ConfigureAwait(false);
|
await channel.SendAsync(targetHost, targetPort, udpRequestPacket, linkedCt).ConfigureAwait(false);
|
||||||
var (_, receiveResult) = await channel.ReceiveAsync(cancellationToken).ConfigureAwait(false);
|
var (_, receiveResult) = await channel.ReceiveAsync(linkedCt).ConfigureAwait(false);
|
||||||
stopwatch.Stop();
|
stopwatch.Stop();
|
||||||
|
|
||||||
udpReceiveResult = receiveResult;
|
if (!_udpTest.VerifyAndExtractUdpResponse(receiveResult))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
validUdpReceiveResult = receiveResult;
|
||||||
|
|
||||||
var currentRoundTripTime = stopwatch.Elapsed;
|
var currentRoundTripTime = stopwatch.Elapsed;
|
||||||
if (currentRoundTripTime < roundTripTime)
|
if (currentRoundTripTime < roundTripTime)
|
||||||
@@ -128,27 +135,20 @@ public class UdpTestService
|
|||||||
roundTripTime = currentRoundTripTime;
|
roundTripTime = currentRoundTripTime;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||||
{
|
{
|
||||||
if (attempt == 1 && roundTripTime == TimeSpan.MaxValue)
|
throw;
|
||||||
{
|
}
|
||||||
throw;
|
catch (OperationCanceledException)
|
||||||
}
|
{
|
||||||
|
// Timeout, continue to next attempt
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((udpReceiveResult?.Length ?? 0) < 4 + 1 + 4 + 2)
|
if (validUdpReceiveResult != null)
|
||||||
{
|
|
||||||
throw new Exception("Received NTP response is too short.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (udpReceiveResult != null && _udpTest.VerifyAndExtractUdpResponse(udpReceiveResult))
|
|
||||||
{
|
{
|
||||||
return roundTripTime;
|
return roundTripTime;
|
||||||
}
|
}
|
||||||
else
|
throw new Exception("Failed to verify and extract UDP response.");
|
||||||
{
|
|
||||||
throw new Exception("Failed to verify and extract UDP response.");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
namespace ServiceLib.Base;
|
||||||
|
|
||||||
|
public class BulkObservableCollection<T> : ObservableCollection<T>
|
||||||
|
{
|
||||||
|
private bool _suppressNotification;
|
||||||
|
|
||||||
|
public BulkObservableCollection()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public BulkObservableCollection(IEnumerable<T> collection) : base(collection)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public BulkObservableCollection(List<T> list) : base(list)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (!_suppressNotification)
|
||||||
|
{
|
||||||
|
base.OnCollectionChanged(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
|
||||||
|
{
|
||||||
|
if (!_suppressNotification)
|
||||||
|
{
|
||||||
|
base.OnPropertyChanged(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AddRange(IEnumerable<T>? collection)
|
||||||
|
{
|
||||||
|
if (collection == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_suppressNotification = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var item in collection)
|
||||||
|
{
|
||||||
|
Add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_suppressNotification = false;
|
||||||
|
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
|
||||||
|
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
|
||||||
|
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Replace(T oldItem, T newItem)
|
||||||
|
{
|
||||||
|
var index = Items.IndexOf(oldItem);
|
||||||
|
if (index < 0)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Items[index] = newItem;
|
||||||
|
|
||||||
|
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
|
||||||
|
OnCollectionChanged(new NotifyCollectionChangedEventArgs(
|
||||||
|
NotifyCollectionChangedAction.Replace,
|
||||||
|
newItem,
|
||||||
|
oldItem,
|
||||||
|
index));
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void ReplaceRange(IEnumerable<T>? collection)
|
||||||
|
{
|
||||||
|
_suppressNotification = true;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Items.Clear();
|
||||||
|
if (collection != null)
|
||||||
|
{
|
||||||
|
foreach (var item in collection)
|
||||||
|
{
|
||||||
|
Items.Add(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
_suppressNotification = false;
|
||||||
|
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
|
||||||
|
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
|
||||||
|
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace ServiceLib.Base;
|
||||||
|
|
||||||
|
public interface ICloseable
|
||||||
|
{
|
||||||
|
public event EventHandler? RequestClose;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace ServiceLib.Base;
|
||||||
|
|
||||||
|
public interface IWindowDialog
|
||||||
|
{
|
||||||
|
public Task<bool> ShowDialogAsync<TViewModel>(TViewModel vm)
|
||||||
|
where TViewModel : class;
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
namespace ServiceLib.Base;
|
namespace ServiceLib.Base;
|
||||||
|
|
||||||
public class MyReactiveObject : ReactiveObject
|
public class MyReactiveObject : ReactiveObject, IActivatableViewModel
|
||||||
{
|
{
|
||||||
protected static Config? _config;
|
protected static Config? _config;
|
||||||
protected Func<EViewAction, object?, Task<bool>>? _updateView;
|
|
||||||
|
public ViewModelActivator Activator { get; } = new();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Diagnostics.CodeAnalysis;
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
namespace ServiceLib.Common;
|
namespace ServiceLib.Common;
|
||||||
|
|
||||||
@@ -92,7 +93,7 @@ public static class Extension
|
|||||||
|
|
||||||
public static bool IsComplexType(this EConfigType configType)
|
public static bool IsComplexType(this EConfigType configType)
|
||||||
{
|
{
|
||||||
return configType is EConfigType.Custom or EConfigType.PolicyGroup or EConfigType.ProxyChain;
|
return configType is EConfigType.Custom or EConfigType.Outbound or EConfigType.PolicyGroup or EConfigType.ProxyChain;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -118,4 +119,40 @@ public static class Extension
|
|||||||
destination.Add(item);
|
destination.Add(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Replace all cross-platform newline characters with the specified string
|
||||||
|
/// </summary>
|
||||||
|
public static string ReplaceLineBreaks(this string input, string replacement)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(input))
|
||||||
|
{
|
||||||
|
return input;
|
||||||
|
}
|
||||||
|
|
||||||
|
// You must replace \r\n first, and then replace the single characters \r and \n.
|
||||||
|
return input.Replace("\r\n", replacement)
|
||||||
|
.Replace("\r", replacement)
|
||||||
|
.Replace("\n", replacement);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IObservable<TOutput> HandleSafe<TInput, TOutput>(
|
||||||
|
this Interaction<TInput, TOutput> interaction, TInput input,
|
||||||
|
TOutput defaultValue = default!,
|
||||||
|
[CallerMemberName] string memberName = "",
|
||||||
|
[CallerFilePath] string filePath = "",
|
||||||
|
[CallerLineNumber] int lineNumber = 0)
|
||||||
|
{
|
||||||
|
return Signal.Defer(() => interaction.WhenHandled(input))
|
||||||
|
.Catch<TOutput, UnhandledInteractionException<TInput, TOutput>>(ex =>
|
||||||
|
{
|
||||||
|
Logging.SaveLog($"Unhandled interaction exception in {memberName} at {filePath}:{lineNumber}", ex);
|
||||||
|
return Signal.Return(defaultValue);
|
||||||
|
})
|
||||||
|
.Catch<TOutput, Exception>(ex =>
|
||||||
|
{
|
||||||
|
Logging.SaveLog($"Exception occurred while handling interaction in {memberName} at {filePath}:{lineNumber}, input: {input}", ex);
|
||||||
|
return Signal.Return(defaultValue);
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
namespace ServiceLib.Common;
|
||||||
|
|
||||||
|
public static class FakeIPUtils
|
||||||
|
{
|
||||||
|
public static bool TryParseIPv6Range(string? value, out string range, out long poolSize)
|
||||||
|
{
|
||||||
|
range = string.IsNullOrWhiteSpace(value) ? Global.FakeIPv6Ranges.First() : value.Trim();
|
||||||
|
poolSize = 65535;
|
||||||
|
if (!System.Net.IPNetwork.TryParse(range, out var network)
|
||||||
|
|| network.BaseAddress.AddressFamily != AddressFamily.InterNetworkV6
|
||||||
|
|| network.PrefixLength == 128)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
range = network.ToString();
|
||||||
|
var hostBits = 128 - network.PrefixLength;
|
||||||
|
if (hostBits < 16)
|
||||||
|
{
|
||||||
|
// Xray requires the mapping capacity to be smaller than the address pool.
|
||||||
|
poolSize = (1L << hostBits) - 1;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -202,7 +202,7 @@ public static class FileUtils
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void DeleteExpiredFiles(string sourceDir, DateTime dtLine)
|
public static void DeleteExpiredFiles(string sourceDir, DateTime dtLine, string? contains = null)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -214,6 +214,10 @@ public static class FileUtils
|
|||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (contains.IsNotEmpty() && !file.Name.Contains(contains))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
file.Delete();
|
file.Delete();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
using System.Text.Json.Serialization.Metadata;
|
||||||
|
|
||||||
namespace ServiceLib.Common;
|
namespace ServiceLib.Common;
|
||||||
|
|
||||||
public class JsonUtils
|
public class JsonUtils
|
||||||
@@ -7,40 +9,45 @@ public class JsonUtils
|
|||||||
private static readonly JsonSerializerOptions _defaultDeserializeOptions = new()
|
private static readonly JsonSerializerOptions _defaultDeserializeOptions = new()
|
||||||
{
|
{
|
||||||
PropertyNameCaseInsensitive = true,
|
PropertyNameCaseInsensitive = true,
|
||||||
ReadCommentHandling = JsonCommentHandling.Skip
|
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||||
|
TypeInfoResolver = AppJsonContext.Default,
|
||||||
};
|
};
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions _defaultSerializeOptions = new()
|
private static readonly JsonSerializerOptions _defaultSerializeOptions = new()
|
||||||
{
|
{
|
||||||
WriteIndented = true,
|
WriteIndented = true,
|
||||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
|
TypeInfoResolver = AppJsonContext.Default,
|
||||||
};
|
};
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions _defaultSerializeNoIndentedOptions = new()
|
private static readonly JsonSerializerOptions _defaultSerializeNoIndentedOptions = new()
|
||||||
{
|
{
|
||||||
WriteIndented = false,
|
WriteIndented = false,
|
||||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
|
TypeInfoResolver = AppJsonContext.Default,
|
||||||
};
|
};
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions _nullValueSerializeOptions = new()
|
private static readonly JsonSerializerOptions _nullValueSerializeOptions = new()
|
||||||
{
|
{
|
||||||
WriteIndented = true,
|
WriteIndented = true,
|
||||||
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
||||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
|
TypeInfoResolver = AppJsonContext.Default,
|
||||||
};
|
};
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions _nullValueSerializeNoIndentedOptions = new()
|
private static readonly JsonSerializerOptions _nullValueSerializeNoIndentedOptions = new()
|
||||||
{
|
{
|
||||||
WriteIndented = false,
|
WriteIndented = false,
|
||||||
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
||||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||||
|
TypeInfoResolver = AppJsonContext.Default,
|
||||||
};
|
};
|
||||||
|
|
||||||
private static readonly JsonDocumentOptions _defaultDocumentOptions = new()
|
private static readonly JsonDocumentOptions _defaultDocumentOptions = new()
|
||||||
{
|
{
|
||||||
CommentHandling = JsonCommentHandling.Skip
|
CommentHandling = JsonCommentHandling.Skip,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -72,7 +79,7 @@ public class JsonUtils
|
|||||||
{
|
{
|
||||||
return default;
|
return default;
|
||||||
}
|
}
|
||||||
return JsonSerializer.Deserialize<T>(strJson, _defaultDeserializeOptions);
|
return JsonSerializer.Deserialize(strJson, (JsonTypeInfo<T>)_defaultDeserializeOptions.GetTypeInfo(typeof(T)));
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -109,7 +116,7 @@ public class JsonUtils
|
|||||||
/// <param name="indented"></param>
|
/// <param name="indented"></param>
|
||||||
/// <param name="nullValue"></param>
|
/// <param name="nullValue"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static string Serialize(object? obj, bool indented = true, bool nullValue = false)
|
public static string Serialize<T>(T? obj, bool indented = true, bool nullValue = false)
|
||||||
{
|
{
|
||||||
var result = string.Empty;
|
var result = string.Empty;
|
||||||
try
|
try
|
||||||
@@ -125,7 +132,7 @@ public class JsonUtils
|
|||||||
(false, true) => _defaultSerializeOptions,
|
(false, true) => _defaultSerializeOptions,
|
||||||
_ => _defaultSerializeNoIndentedOptions
|
_ => _defaultSerializeNoIndentedOptions
|
||||||
};
|
};
|
||||||
result = JsonSerializer.Serialize(obj, options);
|
result = JsonSerializer.Serialize(obj, (JsonTypeInfo<T>)options.GetTypeInfo(typeof(T)));
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -140,7 +147,7 @@ public class JsonUtils
|
|||||||
/// <param name="obj"></param>
|
/// <param name="obj"></param>
|
||||||
/// <param name="options"></param>
|
/// <param name="options"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static string Serialize(object? obj, JsonSerializerOptions? options)
|
public static string SerializeCamelCase<T>(T? obj)
|
||||||
{
|
{
|
||||||
var result = string.Empty;
|
var result = string.Empty;
|
||||||
try
|
try
|
||||||
@@ -149,7 +156,14 @@ public class JsonUtils
|
|||||||
{
|
{
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
result = JsonSerializer.Serialize(obj, options ?? _defaultSerializeOptions);
|
var options = new JsonSerializerOptions
|
||||||
|
{
|
||||||
|
WriteIndented = true,
|
||||||
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||||
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||||
|
TypeInfoResolver = AppJsonContext.Default,
|
||||||
|
};
|
||||||
|
result = JsonSerializer.Serialize(obj, (JsonTypeInfo<T>)options.GetTypeInfo(typeof(T)));
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -162,9 +176,109 @@ public class JsonUtils
|
|||||||
/// SerializeToNode
|
/// SerializeToNode
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="obj"></param>
|
/// <param name="obj"></param>
|
||||||
|
/// <param name="nullValue"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static JsonNode? SerializeToNode(object? obj, JsonSerializerOptions? options = null)
|
public static JsonNode? SerializeToNode<T>(T? obj, bool nullValue = false)
|
||||||
{
|
{
|
||||||
return JsonSerializer.SerializeToNode(obj, options);
|
var options = nullValue ? _nullValueSerializeOptions : _defaultSerializeOptions;
|
||||||
|
return JsonSerializer.SerializeToNode(obj, (JsonTypeInfo<T>)options.GetTypeInfo(typeof(T)));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static JsonArray? SerializeToArray(IEnumerable<string>? values)
|
||||||
|
{
|
||||||
|
if (values is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
var array = new JsonArray();
|
||||||
|
foreach (var value in values)
|
||||||
|
{
|
||||||
|
var valueNode = JsonSerializer.SerializeToNode(value, (JsonTypeInfo<string>)_defaultSerializeOptions.GetTypeInfo(typeof(string)));
|
||||||
|
array.Add(valueNode);
|
||||||
|
}
|
||||||
|
return array;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[JsonSerializable(typeof(Config))]
|
||||||
|
[JsonSerializable(typeof(RulesItem))]
|
||||||
|
[JsonSerializable(typeof(ProfileItem))]
|
||||||
|
[JsonSerializable(typeof(List<RulesItem>))]
|
||||||
|
[JsonSerializable(typeof(List<ProfileItem>))]
|
||||||
|
[JsonSerializable(typeof(ProfileItemModel))]
|
||||||
|
[JsonSerializable(typeof(List<ProfileItemModel>))]
|
||||||
|
[JsonSerializable(typeof(RoutingTemplate))]
|
||||||
|
[JsonSerializable(typeof(DNSItem))]
|
||||||
|
[JsonSerializable(typeof(SimpleDNSItem))]
|
||||||
|
[JsonSerializable(typeof(IPAPIInfo))]
|
||||||
|
[JsonSerializable(typeof(SsSIP008))]
|
||||||
|
[JsonSerializable(typeof(List<SsServer>))]
|
||||||
|
[JsonSerializable(typeof(SsServer))]
|
||||||
|
[JsonSerializable(typeof(VmessQRCode))]
|
||||||
|
[JsonSerializable(typeof(ClashProxies))]
|
||||||
|
[JsonSerializable(typeof(ClashProviders))]
|
||||||
|
[JsonSerializable(typeof(ClashConnections))]
|
||||||
|
[JsonSerializable(typeof(ProtocolExtraItem))]
|
||||||
|
[JsonSerializable(typeof(TransportExtraItem))]
|
||||||
|
[JsonSerializable(typeof(TrafficItem))]
|
||||||
|
[JsonSerializable(typeof(V2rayMetricsVars))]
|
||||||
|
[JsonSerializable(typeof(V2rayMetricsVarsLink))]
|
||||||
|
[JsonSerializable(typeof(GitHubRelease))]
|
||||||
|
[JsonSerializable(typeof(List<GitHubRelease>))]
|
||||||
|
[JsonSerializable(typeof(ServerStatItem))]
|
||||||
|
[JsonSerializable(typeof(WebDavItem))]
|
||||||
|
[JsonSerializable(typeof(KeyEventItem))]
|
||||||
|
[JsonSerializable(typeof(SubItem))]
|
||||||
|
[JsonSerializable(typeof(SingboxConfig))]
|
||||||
|
[JsonSerializable(typeof(Dns4Sbox))]
|
||||||
|
[JsonSerializable(typeof(Inbound4Sbox))]
|
||||||
|
[JsonSerializable(typeof(List<Inbound4Sbox>))]
|
||||||
|
[JsonSerializable(typeof(Endpoints4Sbox))]
|
||||||
|
[JsonSerializable(typeof(List<Endpoints4Sbox>))]
|
||||||
|
[JsonSerializable(typeof(Outbound4Sbox))]
|
||||||
|
[JsonSerializable(typeof(List<Outbound4Sbox>))]
|
||||||
|
[JsonSerializable(typeof(Rule4Sbox))]
|
||||||
|
[JsonSerializable(typeof(Ruleset4Sbox))]
|
||||||
|
[JsonSerializable(typeof(List<Rule4Sbox>))]
|
||||||
|
[JsonSerializable(typeof(List<Ruleset4Sbox>))]
|
||||||
|
[JsonSerializable(typeof(V2rayConfig))]
|
||||||
|
[JsonSerializable(typeof(FakeDns4Ray))]
|
||||||
|
[JsonSerializable(typeof(Dns4Ray))]
|
||||||
|
[JsonSerializable(typeof(DnsServer4Ray))]
|
||||||
|
[JsonSerializable(typeof(Inbounds4Ray))]
|
||||||
|
[JsonSerializable(typeof(List<Inbounds4Ray>))]
|
||||||
|
[JsonSerializable(typeof(Outbounds4Ray))]
|
||||||
|
[JsonSerializable(typeof(List<Outbounds4Ray>))]
|
||||||
|
[JsonSerializable(typeof(RulesItem4Ray))]
|
||||||
|
[JsonSerializable(typeof(List<RulesItem4Ray>))]
|
||||||
|
[JsonSerializable(typeof(Finalmask4Ray))]
|
||||||
|
[JsonSerializable(typeof(string))]
|
||||||
|
[JsonSerializable(typeof(int))]
|
||||||
|
[JsonSerializable(typeof(long))]
|
||||||
|
[JsonSerializable(typeof(double))]
|
||||||
|
[JsonSerializable(typeof(decimal))]
|
||||||
|
[JsonSerializable(typeof(bool))]
|
||||||
|
[JsonSerializable(typeof(Guid))]
|
||||||
|
[JsonSerializable(typeof(DateTime))]
|
||||||
|
[JsonSerializable(typeof(DateTimeOffset))]
|
||||||
|
[JsonSerializable(typeof(TimeSpan))]
|
||||||
|
[JsonSerializable(typeof(int?))]
|
||||||
|
[JsonSerializable(typeof(long?))]
|
||||||
|
[JsonSerializable(typeof(double?))]
|
||||||
|
[JsonSerializable(typeof(bool?))]
|
||||||
|
[JsonSerializable(typeof(DateTime?))]
|
||||||
|
[JsonSerializable(typeof(Guid?))]
|
||||||
|
[JsonSerializable(typeof(string[]))]
|
||||||
|
[JsonSerializable(typeof(int[]))]
|
||||||
|
[JsonSerializable(typeof(byte[]))]
|
||||||
|
[JsonSerializable(typeof(List<string>))]
|
||||||
|
[JsonSerializable(typeof(List<int>))]
|
||||||
|
[JsonSerializable(typeof(Dictionary<string, string>))]
|
||||||
|
[JsonSerializable(typeof(Dictionary<string, object>))]
|
||||||
|
[JsonSerializable(typeof(object))]
|
||||||
|
[JsonSerializable(typeof(JsonElement))]
|
||||||
|
[JsonSerializable(typeof(JsonDocument))]
|
||||||
|
[JsonSerializable(typeof(JsonNode))]
|
||||||
|
[JsonSerializable(typeof(JsonObject))]
|
||||||
|
[JsonSerializable(typeof(JsonArray))]
|
||||||
|
internal partial class AppJsonContext : JsonSerializerContext;
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
namespace ServiceLib.Common;
|
||||||
|
|
||||||
|
public static class NetworkUtils
|
||||||
|
{
|
||||||
|
private static readonly HashSet<NetworkInterfaceType> _allowedPhysicalInterfaceTypes =
|
||||||
|
[
|
||||||
|
NetworkInterfaceType.Ethernet,
|
||||||
|
NetworkInterfaceType.Wireless80211,
|
||||||
|
NetworkInterfaceType.GigabitEthernet,
|
||||||
|
NetworkInterfaceType.FastEthernetFx,
|
||||||
|
NetworkInterfaceType.FastEthernetT,
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly string[] _allowedPhysicalNamePrefixes =
|
||||||
|
[
|
||||||
|
// Linux
|
||||||
|
"eth", "enp", "ens", "eno", "enx", "wlp", "wlan",
|
||||||
|
|
||||||
|
// macOS
|
||||||
|
"en0", "en1", "en2",
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly string[] _allowedPhysicalNameKeywords =
|
||||||
|
[
|
||||||
|
// Windows / macOS / Generic
|
||||||
|
"ethernet", "wlan", "wi-fi", "wifi", "airport",
|
||||||
|
|
||||||
|
// Chinese
|
||||||
|
"以太网", "无线", "局域网"
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly string[] _virtualNameBlacklistKeywords =
|
||||||
|
[
|
||||||
|
// Generic
|
||||||
|
"virtual", "loopback", "loop back",
|
||||||
|
|
||||||
|
// Common virtual / VPN / tunnel adapters
|
||||||
|
"hyper-v", "vmware", "virtualbox", "vbox", "docker", "veth", "virbr", "cni",
|
||||||
|
"flannel", "cali", "kube", "wintun", "wireguard", "zerotier", "tailscale", "utun",
|
||||||
|
"tap-windows", "tap adapter", "openvpn", "anyconnect", "vpn", "clash", "mihomo", "xray_tun",
|
||||||
|
|
||||||
|
// Windows NDIS filter sub-layers & pseudo-interfaces
|
||||||
|
"wan miniport", "lightweight filter", "filter driver", "packet scheduler", "npcap", "kernel debug",
|
||||||
|
|
||||||
|
// Chinese
|
||||||
|
"虚拟", "回环", "环回"
|
||||||
|
];
|
||||||
|
|
||||||
|
public static bool IsAutoBindInterface(string? bindInterface)
|
||||||
|
{
|
||||||
|
return string.Equals(bindInterface?.TrimEx(), Global.BindInterfaceAuto, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<string> GetBindInterfaceNames()
|
||||||
|
{
|
||||||
|
return GetLocalNetworkInterfaceNames().Prepend(Global.BindInterfaceAuto).AppendEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string? GetRealBindInterfaceName(string? bindInterface)
|
||||||
|
{
|
||||||
|
var trimmed = bindInterface?.TrimEx();
|
||||||
|
if (trimmed.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return IsAutoBindInterface(trimmed) ? GetDefaultPhysicalInterfaceName() : trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Resolves a default physical outbound interface using a heuristic (active IP-enabled physical NICs
|
||||||
|
/// with an IPv4 gateway, preferring Ethernet over Wi-Fi). This does not inspect OS routing metrics;
|
||||||
|
/// in multi-NIC environments with custom routing tables, specify the target interface name manually.
|
||||||
|
/// </summary>
|
||||||
|
public static string? GetDefaultPhysicalInterfaceName()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var upPhysicalNics = NetworkInterface.GetAllNetworkInterfaces()
|
||||||
|
.Where(IsAllowedPhysicalInterface)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (upPhysicalNics.Count == 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var gatewayNics = upPhysicalNics.Where(HasIPv4Gateway).ToList();
|
||||||
|
var candidates = gatewayNics.Count > 0 ? gatewayNics : upPhysicalNics;
|
||||||
|
|
||||||
|
var bestNic = candidates.FirstOrDefault(ni =>
|
||||||
|
ni.NetworkInterfaceType is NetworkInterfaceType.Ethernet or NetworkInterfaceType.GigabitEthernet)
|
||||||
|
?? candidates.FirstOrDefault(ni => ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
|
||||||
|
?? candidates.FirstOrDefault();
|
||||||
|
|
||||||
|
return bestNic?.Name;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Logging.SaveLog("GetDefaultPhysicalInterfaceName", ex);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<string> GetLocalNetworkInterfaceNames()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return NetworkInterface.GetAllNetworkInterfaces()
|
||||||
|
.Where(IsAllowedPhysicalInterface)
|
||||||
|
.Select(x => x.Name)
|
||||||
|
.Where(x => !string.IsNullOrWhiteSpace(x))
|
||||||
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||||
|
.OrderBy(x => x)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Logging.SaveLog("GetLocalNetworkInterfaceNames", ex);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsAllowedPhysicalInterface(NetworkInterface ni)
|
||||||
|
{
|
||||||
|
if (ni.OperationalStatus != OperationalStatus.Up || !SupportsIP(ni))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var interfaceText = $"{ni.Name} {ni.Description}";
|
||||||
|
if (_virtualNameBlacklistKeywords.Any(keyword => interfaceText.Contains(keyword, StringComparison.OrdinalIgnoreCase)))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_allowedPhysicalInterfaceTypes.Contains(ni.NetworkInterfaceType))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_allowedPhysicalNamePrefixes.Any(prefix => ni.Name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return _allowedPhysicalNameKeywords.Any(keyword => interfaceText.Contains(keyword, StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool SupportsIP(NetworkInterface ni)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return ni.Supports(NetworkInterfaceComponent.IPv4) || ni.Supports(NetworkInterfaceComponent.IPv6);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool HasIPv4Gateway(NetworkInterface ni)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return ni.GetIPProperties().GatewayAddresses.Any(g =>
|
||||||
|
g.Address.AddressFamily == AddressFamily.InterNetwork
|
||||||
|
&& !IPAddress.Any.Equals(g.Address)
|
||||||
|
&& !IPAddress.None.Equals(g.Address));
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
using System.Collections.Specialized;
|
|
||||||
using System.Security.Principal;
|
using System.Security.Principal;
|
||||||
using CliWrap;
|
using CliWrap;
|
||||||
using CliWrap.Buffered;
|
using CliWrap.Buffered;
|
||||||
@@ -51,7 +50,7 @@ public class Utils
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
str = str.Replace(Environment.NewLine, string.Empty);
|
str = str.ReplaceLineBreaks(string.Empty);
|
||||||
return new List<string>(str.Split(',', StringSplitOptions.RemoveEmptyEntries));
|
return new List<string>(str.Split(',', StringSplitOptions.RemoveEmptyEntries));
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -114,9 +113,7 @@ public class Utils
|
|||||||
}
|
}
|
||||||
|
|
||||||
plainText = plainText.Trim()
|
plainText = plainText.Trim()
|
||||||
.Replace(Environment.NewLine, "")
|
.ReplaceLineBreaks("")
|
||||||
.Replace("\n", "")
|
|
||||||
.Replace("\r", "")
|
|
||||||
.Replace('_', '/')
|
.Replace('_', '/')
|
||||||
.Replace('-', '+')
|
.Replace('-', '+')
|
||||||
.Replace(" ", "");
|
.Replace(" ", "");
|
||||||
@@ -203,7 +200,9 @@ public class Utils
|
|||||||
var parts = query[1..].Split('&', StringSplitOptions.RemoveEmptyEntries);
|
var parts = query[1..].Split('&', StringSplitOptions.RemoveEmptyEntries);
|
||||||
foreach (var part in parts)
|
foreach (var part in parts)
|
||||||
{
|
{
|
||||||
var keyValue = part.Split('=');
|
// Split on the FIRST '=' only: RFC 3986 lists '=' among the sub-delimiters a query
|
||||||
|
// value may carry, so everything after the first one belongs to the value.
|
||||||
|
var keyValue = part.Split('=', 2);
|
||||||
if (keyValue.Length != 2)
|
if (keyValue.Length != 2)
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
@@ -321,13 +320,37 @@ public class Utils
|
|||||||
return text;
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
return text.Replace(",", ",").Replace(Environment.NewLine, ",");
|
return text.Replace(",", ",")
|
||||||
|
.Replace(" ", "")
|
||||||
|
.ReplaceLineBreaks(",");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static List<string> GetEnumNames<TEnum>() where TEnum : Enum
|
public static string ParseProcess(string text)
|
||||||
{
|
{
|
||||||
return Enum.GetValues(typeof(TEnum))
|
if (text.IsNullOrEmpty())
|
||||||
.Cast<TEnum>()
|
{
|
||||||
|
return string.Empty;
|
||||||
|
}
|
||||||
|
if (text.StartsWith('"'))
|
||||||
|
{
|
||||||
|
text = text[1..];
|
||||||
|
}
|
||||||
|
if (text.EndsWith('"'))
|
||||||
|
{
|
||||||
|
text = text[..^1];
|
||||||
|
}
|
||||||
|
return List2String(text.Replace(",", ",")
|
||||||
|
.Replace("\\", "/")
|
||||||
|
.ReplaceLineBreaks(",")
|
||||||
|
.Split(',', StringSplitOptions.RemoveEmptyEntries)
|
||||||
|
.Select(x => x.TrimEx())
|
||||||
|
.Where(x => x.IsNotEmpty())
|
||||||
|
.ToList());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<string> GetEnumNames<TEnum>() where TEnum : struct, Enum
|
||||||
|
{
|
||||||
|
return Enum.GetValues<TEnum>()
|
||||||
.Select(e => e.ToString())
|
.Select(e => e.ToString())
|
||||||
.ToList();
|
.ToList();
|
||||||
}
|
}
|
||||||
@@ -462,16 +485,46 @@ public class Utils
|
|||||||
|
|
||||||
public static string? DomainStrategy4Sbox(string? strategy)
|
public static string? DomainStrategy4Sbox(string? strategy)
|
||||||
{
|
{
|
||||||
|
if (strategy is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
return strategy switch
|
return strategy switch
|
||||||
{
|
{
|
||||||
not null when strategy.StartsWith("UseIPv4") => "prefer_ipv4",
|
_ when strategy.StartsWith("UseIPv6") => "prefer_ipv6",
|
||||||
not null when strategy.StartsWith("UseIPv6") => "prefer_ipv6",
|
_ when strategy.StartsWith("UseIP") => "prefer_ipv4",
|
||||||
not null when strategy.StartsWith("ForceIPv4") => "ipv4_only",
|
_ when strategy.StartsWith("ForceIPv6") => "ipv6_only",
|
||||||
not null when strategy.StartsWith("ForceIPv6") => "ipv6_only",
|
_ when strategy.StartsWith("ForceIP") => "ipv4_only",
|
||||||
_ => null
|
_ => null
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static List<(string, string)> ParseHeaders(string? headers)
|
||||||
|
{
|
||||||
|
var result = new List<(string, string)>();
|
||||||
|
if (headers.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
var lines = headers.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
foreach (var line in lines)
|
||||||
|
{
|
||||||
|
var parts = line.Split(new[] { ':' }, 2);
|
||||||
|
if (parts.Length != 2)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
var key = parts[0].Trim();
|
||||||
|
var value = parts[1].Trim();
|
||||||
|
if (!string.IsNullOrEmpty(key))
|
||||||
|
{
|
||||||
|
result.Add((key, value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
#endregion Conversion Functions
|
#endregion Conversion Functions
|
||||||
|
|
||||||
#region Data Checks
|
#region Data Checks
|
||||||
@@ -576,6 +629,58 @@ public class Utils
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static bool TryParseRange(string? input, int min, int max, out int from, out int to)
|
||||||
|
{
|
||||||
|
from = to = 0;
|
||||||
|
if (string.IsNullOrWhiteSpace(input))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
var parts = input.Split('-');
|
||||||
|
if (parts.Length == 1)
|
||||||
|
{
|
||||||
|
if (!int.TryParse(parts[0], out from))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
to = from;
|
||||||
|
return from >= min && to <= max;
|
||||||
|
}
|
||||||
|
if (parts.Length != 2
|
||||||
|
|| !int.TryParse(parts[0], out from)
|
||||||
|
|| !int.TryParse(parts[1], out to))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return from >= min && to <= max && from <= to;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool TryParseMaxSplit(string? input, int min, int max, out int from, out int to)
|
||||||
|
{
|
||||||
|
from = to = 0;
|
||||||
|
if (string.IsNullOrWhiteSpace(input))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
var parts = input.Split('-');
|
||||||
|
if (parts.Length == 1)
|
||||||
|
{
|
||||||
|
if (!int.TryParse(parts[0], out from))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
to = from;
|
||||||
|
return from >= min && to <= max;
|
||||||
|
}
|
||||||
|
if (parts.Length != 2
|
||||||
|
|| !int.TryParse(parts[0], out from)
|
||||||
|
|| !int.TryParse(parts[1], out to))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return from >= min && to <= max && from <= to;
|
||||||
|
}
|
||||||
|
|
||||||
public static bool IsPrivateNetwork(string ip)
|
public static bool IsPrivateNetwork(string ip)
|
||||||
{
|
{
|
||||||
if (IPAddress.TryParse(ip, out var address))
|
if (IPAddress.TryParse(ip, out var address))
|
||||||
@@ -645,6 +750,40 @@ public class Utils
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Regex match with a timeout guard. Filter patterns can come from user
|
||||||
|
/// input or subscription content while the tested text (remarks, log
|
||||||
|
/// messages) is attacker-influenced, so an evil pattern like (a+)+$
|
||||||
|
/// would otherwise hang the caller (ReDoS). On timeout or invalid
|
||||||
|
/// pattern, fail open (return true) so no node/message is silently
|
||||||
|
/// dropped; the incident is logged.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsRegexMatch(string? input, string? pattern, int timeoutSeconds = 2)
|
||||||
|
{
|
||||||
|
if (pattern.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (input.IsNullOrEmpty())
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return Regex.IsMatch(input, pattern, RegexOptions.None, TimeSpan.FromSeconds(timeoutSeconds));
|
||||||
|
}
|
||||||
|
catch (RegexMatchTimeoutException ex)
|
||||||
|
{
|
||||||
|
Logging.SaveLog("IsRegexMatch timeout", ex);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (ArgumentException ex)
|
||||||
|
{
|
||||||
|
Logging.SaveLog("IsRegexMatch invalid pattern", ex);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#endregion Data Checks
|
#endregion Data Checks
|
||||||
|
|
||||||
#region Speed Test
|
#region Speed Test
|
||||||
@@ -673,11 +812,11 @@ public class Utils
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static int GetFreePort(int defaultPort = 0)
|
public static int GetFreePort(int defaultPort)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (!(defaultPort == 0 || Utils.PortInUse(defaultPort)))
|
if (!PortInUse(defaultPort))
|
||||||
{
|
{
|
||||||
return defaultPort;
|
return defaultPort;
|
||||||
}
|
}
|
||||||
@@ -716,6 +855,58 @@ public class Utils
|
|||||||
return (endpoints, connections);
|
return (endpoints, connections);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static bool IsLocalIP(string ipAddress)
|
||||||
|
{
|
||||||
|
if (!IPAddress.TryParse(ipAddress, out var targetAddress))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return NetworkInterface.GetAllNetworkInterfaces()
|
||||||
|
.SelectMany(ni => ni.GetIPProperties().UnicastAddresses)
|
||||||
|
.Any(ua => ua.Address.Equals(targetAddress));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool ContainsInterfaceName(string inInterfaceName)
|
||||||
|
{
|
||||||
|
return NetworkInterface.GetAllNetworkInterfaces()
|
||||||
|
.Any(ni => ni.Name.Equals(inInterfaceName, StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether the host holds a globally routable IPv6 address, that is one inside 2000::/3.
|
||||||
|
/// Link-local and unique local addresses are excluded: they never reach the IPv6 internet,
|
||||||
|
/// so a host holding only those has no IPv6 traffic that could bypass the tunnel, and no
|
||||||
|
/// IPv6 path that traffic sent into the tunnel could come back out of.
|
||||||
|
/// </summary>
|
||||||
|
public static bool HasGlobalIPv6Address()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return NetworkInterface.GetAllNetworkInterfaces()
|
||||||
|
.Where(ni => ni.OperationalStatus == OperationalStatus.Up
|
||||||
|
&& ni.NetworkInterfaceType != NetworkInterfaceType.Loopback)
|
||||||
|
.SelectMany(ni => ni.GetIPProperties().UnicastAddresses)
|
||||||
|
.Any(ua => IsGlobalUnicastIPv6(ua.Address));
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsGlobalUnicastIPv6(IPAddress address)
|
||||||
|
{
|
||||||
|
if (address.AddressFamily != AddressFamily.InterNetworkV6)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2000::/3 is the only range currently assigned for global unicast, which leaves out
|
||||||
|
// ::1, fe80::/10, fc00::/7 and ff00::/8 in a single test.
|
||||||
|
return (address.GetAddressBytes()[0] & 0xE0) == 0x20;
|
||||||
|
}
|
||||||
|
|
||||||
#endregion Speed Test
|
#endregion Speed Test
|
||||||
|
|
||||||
#region Miscellaneous
|
#region Miscellaneous
|
||||||
@@ -885,12 +1076,12 @@ public class Utils
|
|||||||
return new Dictionary<string, string>();
|
return new Dictionary<string, string>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<string?> GetCliWrapOutput(string filePath, string? arg)
|
public static async Task<string?> GetCliWrapOutput(string filePath, string? arg, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
return await GetCliWrapOutput(filePath, arg != null ? new List<string>() { arg } : null);
|
return await GetCliWrapOutput(filePath, arg != null ? new List<string>() { arg } : null, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static async Task<string?> GetCliWrapOutput(string filePath, IEnumerable<string>? args)
|
public static async Task<string?> GetCliWrapOutput(string filePath, IEnumerable<string>? args, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -907,7 +1098,7 @@ public class Utils
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var result = await cmd.ExecuteBufferedAsync();
|
var result = await cmd.ExecuteBufferedAsync(cancellationToken);
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
return result.StandardOutput ?? "";
|
return result.StandardOutput ?? "";
|
||||||
@@ -939,7 +1130,7 @@ public class Utils
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Check if it is installed by Windows WinGet
|
//Check if it is installed by Windows WinGet
|
||||||
if (IsWindows() && basePath.Contains("Users") && basePath.Contains("WinGet"))
|
if (IsWindows() && basePath.Contains("WinGet"))
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -1249,7 +1440,11 @@ public class Utils
|
|||||||
if (File.Exists(fileName))
|
if (File.Exists(fileName))
|
||||||
{
|
{
|
||||||
var currentMode = File.GetUnixFileMode(fileName);
|
var currentMode = File.GetUnixFileMode(fileName);
|
||||||
File.SetUnixFileMode(fileName, currentMode | UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute);
|
var executableMode = currentMode | UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute;
|
||||||
|
if (currentMode != executableMode)
|
||||||
|
{
|
||||||
|
File.SetUnixFileMode(fileName, executableMode);
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using YamlDotNet.Core;
|
using YamlDotNet.Core;
|
||||||
using YamlDotNet.Serialization;
|
using YamlDotNet.RepresentationModel;
|
||||||
using YamlDotNet.Serialization.NamingConventions;
|
|
||||||
|
|
||||||
namespace ServiceLib.Common;
|
namespace ServiceLib.Common;
|
||||||
|
|
||||||
@@ -13,45 +12,57 @@ public class YamlUtils
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Deserialize
|
/// Deserialize
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
|
||||||
/// <param name="str"></param>
|
/// <param name="str"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static T FromYaml<T>(string str)
|
public static YamlMappingNode FromYaml(string str)
|
||||||
{
|
{
|
||||||
var deserializer = new DeserializerBuilder()
|
//var deserializer = new DeserializerBuilder()
|
||||||
.WithNamingConvention(PascalCaseNamingConvention.Instance)
|
// .WithNamingConvention(PascalCaseNamingConvention.Instance)
|
||||||
.Build();
|
// .Build();
|
||||||
|
//try
|
||||||
|
//{
|
||||||
|
// var obj = deserializer.Deserialize<T>(str);
|
||||||
|
// return obj;
|
||||||
|
//}
|
||||||
|
//catch (Exception ex)
|
||||||
|
//{
|
||||||
|
// Logging.SaveLog(_tag, ex);
|
||||||
|
// return deserializer.Deserialize<T>("");
|
||||||
|
//}
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var obj = deserializer.Deserialize<T>(str);
|
var yaml = new YamlStream();
|
||||||
return obj;
|
using var reader = new StringReader(str);
|
||||||
|
yaml.Load(reader);
|
||||||
|
var rootNode = (YamlMappingNode)yaml.Documents[0].RootNode;
|
||||||
|
return rootNode;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Logging.SaveLog(_tag, ex);
|
Logging.SaveLog(_tag, ex);
|
||||||
return deserializer.Deserialize<T>("");
|
return new YamlMappingNode();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Serialize
|
/// Serialize
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="obj"></param>
|
/// <param name="node"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static string ToYaml(object? obj)
|
public static string ToYaml(YamlMappingNode? node)
|
||||||
{
|
{
|
||||||
var result = string.Empty;
|
var result = string.Empty;
|
||||||
if (obj == null)
|
if (node == null)
|
||||||
{
|
{
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
var serializer = new SerializerBuilder()
|
|
||||||
.WithNamingConvention(HyphenatedNamingConvention.Instance)
|
|
||||||
.Build();
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
result = serializer.Serialize(obj);
|
var doc = new YamlDocument(node);
|
||||||
|
var stream = new YamlStream(doc);
|
||||||
|
using var writer = new StringWriter();
|
||||||
|
stream.Save(writer, assignAnchors: false);
|
||||||
|
result = writer.ToString();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -64,9 +75,15 @@ public class YamlUtils
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var mergingParser = new MergingParser(new Parser(new StringReader(str)));
|
using var reader = new StringReader(str);
|
||||||
var obj = new DeserializerBuilder().Build().Deserialize(mergingParser);
|
var parser = new Parser(reader);
|
||||||
return ToYaml(obj);
|
var mergingParser = new MergingParser(parser);
|
||||||
|
var yamlStream = new YamlStream();
|
||||||
|
yamlStream.Load(mergingParser);
|
||||||
|
using var writer = new StringWriter();
|
||||||
|
yamlStream.Save(writer, assignAnchors: false);
|
||||||
|
|
||||||
|
return writer.ToString();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ public enum EConfigType
|
|||||||
HTTP = 10,
|
HTTP = 10,
|
||||||
Anytls = 11,
|
Anytls = 11,
|
||||||
Naive = 12,
|
Naive = 12,
|
||||||
|
Outbound = 13,
|
||||||
|
MASQUE = 14,
|
||||||
PolicyGroup = 101,
|
PolicyGroup = 101,
|
||||||
ProxyChain = 102,
|
ProxyChain = 102,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,5 +5,4 @@ public enum ERuleMode
|
|||||||
Rule = 0,
|
Rule = 0,
|
||||||
Global = 1,
|
Global = 1,
|
||||||
Direct = 2,
|
Direct = 2,
|
||||||
Unchanged = 3
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,5 +10,6 @@ public enum ETransport
|
|||||||
h2,
|
h2,
|
||||||
http,
|
http,
|
||||||
quic,
|
quic,
|
||||||
grpc
|
grpc,
|
||||||
|
xdrive
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
namespace ServiceLib.Enums;
|
|
||||||
|
|
||||||
public enum EViewAction
|
|
||||||
{
|
|
||||||
CloseWindow,
|
|
||||||
ShowYesNo,
|
|
||||||
SaveFileDialog,
|
|
||||||
AddBatchRoutingRulesYesNo,
|
|
||||||
SetClipboardData,
|
|
||||||
AddServerViaClipboard,
|
|
||||||
ImportRulesFromClipboard,
|
|
||||||
ProfilesFocus,
|
|
||||||
ShareSub,
|
|
||||||
ShareServer,
|
|
||||||
ScanScreenTask,
|
|
||||||
ScanImageTask,
|
|
||||||
BrowseServer,
|
|
||||||
ImportRulesFromFile,
|
|
||||||
InitSettingFont,
|
|
||||||
PasswordInput,
|
|
||||||
SubEditWindow,
|
|
||||||
RoutingRuleSettingWindow,
|
|
||||||
RoutingRuleDetailsWindow,
|
|
||||||
AddServerWindow,
|
|
||||||
AddServer2Window,
|
|
||||||
AddGroupServerWindow,
|
|
||||||
DNSSettingWindow,
|
|
||||||
RoutingSettingWindow,
|
|
||||||
OptionSettingWindow,
|
|
||||||
FullConfigTemplateWindow,
|
|
||||||
GlobalHotkeySettingWindow,
|
|
||||||
SubSettingWindow,
|
|
||||||
DispatcherRefreshServersBiz,
|
|
||||||
DispatcherRefreshIcon,
|
|
||||||
DispatcherShowMsg,
|
|
||||||
}
|
|
||||||
@@ -2,30 +2,16 @@ namespace ServiceLib.Events;
|
|||||||
|
|
||||||
public static class AppEvents
|
public static class AppEvents
|
||||||
{
|
{
|
||||||
public static readonly EventChannel<Unit> ReloadRequested = new();
|
public static readonly EventChannel<RxVoid> AddServerViaClipboardRequested = new();
|
||||||
public static readonly EventChannel<bool?> ShowHideWindowRequested = new();
|
|
||||||
public static readonly EventChannel<Unit> AddServerViaScanRequested = new();
|
|
||||||
public static readonly EventChannel<Unit> AddServerViaClipboardRequested = new();
|
|
||||||
public static readonly EventChannel<bool> SubscriptionsUpdateRequested = new();
|
|
||||||
public static readonly EventChannel<bool> HasUpdateNotified = new();
|
public static readonly EventChannel<bool> HasUpdateNotified = new();
|
||||||
|
|
||||||
public static readonly EventChannel<Unit> ProfilesRefreshRequested = new();
|
|
||||||
public static readonly EventChannel<Unit> SubscriptionsRefreshRequested = new();
|
|
||||||
public static readonly EventChannel<Unit> ProxiesReloadRequested = new();
|
|
||||||
public static readonly EventChannel<ServerSpeedItem> DispatcherStatisticsRequested = new();
|
public static readonly EventChannel<ServerSpeedItem> DispatcherStatisticsRequested = new();
|
||||||
|
|
||||||
public static readonly EventChannel<string> SendSnackMsgRequested = new();
|
public static readonly EventChannel<string> SendSnackMsgRequested = new();
|
||||||
public static readonly EventChannel<string> SendMsgViewRequested = new();
|
public static readonly EventChannel<string> SendMsgViewRequested = new();
|
||||||
|
|
||||||
public static readonly EventChannel<Unit> AppExitRequested = new();
|
public static readonly EventChannel<RxVoid> AppExitRequested = new();
|
||||||
public static readonly EventChannel<bool> ShutdownRequested = new();
|
public static readonly EventChannel<bool> ShutdownRequested = new();
|
||||||
|
|
||||||
public static readonly EventChannel<Unit> AdjustMainLvColWidthRequested = new();
|
|
||||||
|
|
||||||
public static readonly EventChannel<string> SetDefaultServerRequested = new();
|
|
||||||
|
|
||||||
public static readonly EventChannel<Unit> RoutingsMenuRefreshRequested = new();
|
|
||||||
public static readonly EventChannel<Unit> TestServerRequested = new();
|
|
||||||
public static readonly EventChannel<Unit> InboundDisplayRequested = new();
|
|
||||||
public static readonly EventChannel<ESysProxyType> SysProxyChangeRequested = new();
|
public static readonly EventChannel<ESysProxyType> SysProxyChangeRequested = new();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +1,38 @@
|
|||||||
using System.Reactive.Subjects;
|
|
||||||
|
|
||||||
namespace ServiceLib.Events;
|
namespace ServiceLib.Events;
|
||||||
|
|
||||||
public sealed class EventChannel<T>
|
public sealed class EventChannel<T>
|
||||||
{
|
{
|
||||||
private readonly ISubject<T> _subject = Subject.Synchronize(new Subject<T>());
|
private readonly Signal<T> _signal = new();
|
||||||
|
private readonly Lock _gate = new();
|
||||||
|
private readonly IObservable<T> _observable;
|
||||||
|
|
||||||
|
public EventChannel()
|
||||||
|
{
|
||||||
|
_observable = _signal.Synchronize(_gate);
|
||||||
|
}
|
||||||
|
|
||||||
public IObservable<T> AsObservable()
|
public IObservable<T> AsObservable()
|
||||||
{
|
{
|
||||||
return _subject.AsObservable();
|
return _observable;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Publish(T value)
|
public void Publish(T value)
|
||||||
{
|
{
|
||||||
_subject.OnNext(value);
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_signal.OnNext(value);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Publish()
|
public void Publish()
|
||||||
{
|
{
|
||||||
if (typeof(T) != typeof(Unit))
|
if (typeof(T) != typeof(RxVoid))
|
||||||
{
|
{
|
||||||
throw new InvalidOperationException("Publish() without value is only valid for EventChannel<Unit>.");
|
throw new InvalidOperationException("Publish() without value is only valid for EventChannel<RxVoid>.");
|
||||||
|
}
|
||||||
|
lock (_gate)
|
||||||
|
{
|
||||||
|
_signal.OnNext((T)(object)RxVoid.Default);
|
||||||
}
|
}
|
||||||
_subject.OnNext((T)(object)Unit.Default);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
|
|
||||||
<ReactiveUI />
|
|
||||||
</Weavers>
|
|
||||||
+154
-24
@@ -2,8 +2,6 @@ namespace ServiceLib;
|
|||||||
|
|
||||||
public class Global
|
public class Global
|
||||||
{
|
{
|
||||||
#region const
|
|
||||||
|
|
||||||
public const string AppName = "v2rayN";
|
public const string AppName = "v2rayN";
|
||||||
public const string GithubUrl = "https://github.com";
|
public const string GithubUrl = "https://github.com";
|
||||||
public const string GithubApiUrl = "https://api.github.com/repos";
|
public const string GithubApiUrl = "https://api.github.com/repos";
|
||||||
@@ -42,8 +40,15 @@ public class Global
|
|||||||
public const string KillAsSudoOSXShellFileName = NamespaceSample + "kill_as_sudo_osx_sh";
|
public const string KillAsSudoOSXShellFileName = NamespaceSample + "kill_as_sudo_osx_sh";
|
||||||
public const string KillAsSudoLinuxShellFileName = NamespaceSample + "kill_as_sudo_linux_sh";
|
public const string KillAsSudoLinuxShellFileName = NamespaceSample + "kill_as_sudo_linux_sh";
|
||||||
public const string SingboxFakeIPFilterFileName = NamespaceSample + "singbox_fakeip_filter";
|
public const string SingboxFakeIPFilterFileName = NamespaceSample + "singbox_fakeip_filter";
|
||||||
|
public const string ChromeRootCertFileName = NamespaceSample + "chrome_roots_pem";
|
||||||
|
public const string MozillaRootCertFileName = NamespaceSample + "mozilla_roots_pem";
|
||||||
|
public const string TaskXmlTemplateFileName = NamespaceSample + "TaskXmlTemplate";
|
||||||
|
|
||||||
|
public const string ChromeRootProvider = "chrome";
|
||||||
|
public const string MozillaRootProvider = "mozilla";
|
||||||
|
|
||||||
public const string DefaultSecurity = "auto";
|
public const string DefaultSecurity = "auto";
|
||||||
|
public const string BindInterfaceAuto = "AUTO";
|
||||||
public const string DefaultNetwork = "raw";
|
public const string DefaultNetwork = "raw";
|
||||||
public const string RawHeaderHttp = "http";
|
public const string RawHeaderHttp = "http";
|
||||||
public const string None = "none";
|
public const string None = "none";
|
||||||
@@ -89,20 +94,30 @@ public class Global
|
|||||||
public const string XrayLocalAsset = "XRAY_LOCATION_ASSET";
|
public const string XrayLocalAsset = "XRAY_LOCATION_ASSET";
|
||||||
public const string XrayLocalCert = "XRAY_LOCATION_CERT";
|
public const string XrayLocalCert = "XRAY_LOCATION_CERT";
|
||||||
public const int SpeedTestPageSize = 1000;
|
public const int SpeedTestPageSize = 1000;
|
||||||
|
public const int SpeedTestConcurrencyCountMin = 10;
|
||||||
public const string LinuxBash = "/bin/bash";
|
public const string LinuxBash = "/bin/bash";
|
||||||
public const string StringTrue = "true";
|
public const string StringTrue = "true";
|
||||||
public const string StringFalse = "false";
|
public const string StringFalse = "false";
|
||||||
|
public const int SqliteMaxBatchSize = 10000;
|
||||||
|
public static readonly TimeSpan LocalFetch = TimeSpan.FromSeconds(5);
|
||||||
|
public static readonly TimeSpan DirectFetch = TimeSpan.FromSeconds(10);
|
||||||
|
public static readonly TimeSpan ProxyFetch = TimeSpan.FromSeconds(30);
|
||||||
|
public static readonly TimeSpan DirectDownloadConnect = TimeSpan.FromSeconds(5);
|
||||||
|
public static readonly TimeSpan ProxyDownloadConnect = TimeSpan.FromSeconds(10);
|
||||||
|
|
||||||
public const string SingboxDirectDNSTag = "direct_dns";
|
public const string SingboxDirectDNSTagPrefix = "direct-dns-";
|
||||||
public const string SingboxRemoteDNSTag = "remote_dns";
|
public const string SingboxRemoteDNSTagPrefix = "remote-dns-";
|
||||||
public const string SingboxLocalDNSTag = "local_local";
|
public const string SingboxDirectDNSTag = "direct-dns-1";
|
||||||
public const string SingboxHostsDNSTag = "hosts_dns";
|
public const string SingboxRemoteDNSTag = "remote-dns-1";
|
||||||
public const string SingboxFakeDNSTag = "fake_dns";
|
public const string SingboxDirectDNSTagTemplate = "direct-dns-{0}";
|
||||||
|
public const string SingboxRemoteDNSTagTemplate = "remote-dns-{0}";
|
||||||
|
public const string SingboxLocalDNSTag = "local-local";
|
||||||
|
public const string SingboxHostsDNSTag = "hosts-dns";
|
||||||
|
public const string SingboxFakeDNSTag = "fake-dns";
|
||||||
|
public const string SingboxSrsDownloadHttpClientTag = "srs-download-http-client";
|
||||||
|
|
||||||
public const int Hysteria2DefaultHopInt = 30;
|
public const int Hysteria2DefaultHopInt = 30;
|
||||||
|
|
||||||
public const string PolicyGroupExcludeKeywords = @"剩余|过期|到期|重置|[Rr]emaining|[Ee]xpir|[Rr]eset";
|
public const string PolicyGroupExcludeKeywords = @"剩余|过期|到期|重置|[Rr]emaining|[Ee]xpir|[Rr]eset";
|
||||||
|
|
||||||
public const string PolicyGroupDefaultAllFilter = $"^(?!.*(?:{PolicyGroupExcludeKeywords})).*$";
|
public const string PolicyGroupDefaultAllFilter = $"^(?!.*(?:{PolicyGroupExcludeKeywords})).*$";
|
||||||
|
|
||||||
public static readonly List<string> PolicyGroupDefaultFilterList =
|
public static readonly List<string> PolicyGroupDefaultFilterList =
|
||||||
@@ -210,6 +225,10 @@ public class Global
|
|||||||
|
|
||||||
public const string Hysteria2ProtocolShare = "hy2://";
|
public const string Hysteria2ProtocolShare = "hy2://";
|
||||||
|
|
||||||
|
public const string Hysteria2RealmProtocolShare = "hysteria2+realm://";
|
||||||
|
|
||||||
|
public const string Hysteria2HttpRealmProtocolShare = "hysteria2+realm+http://";
|
||||||
|
|
||||||
public const string NaiveHttpsProtocolShare = "naive+https://";
|
public const string NaiveHttpsProtocolShare = "naive+https://";
|
||||||
|
|
||||||
public const string NaiveQuicProtocolShare = "naive+quic://";
|
public const string NaiveQuicProtocolShare = "naive+quic://";
|
||||||
@@ -244,7 +263,8 @@ public class Global
|
|||||||
{ EConfigType.TUIC, "tuic" },
|
{ EConfigType.TUIC, "tuic" },
|
||||||
{ EConfigType.WireGuard, "wireguard" },
|
{ EConfigType.WireGuard, "wireguard" },
|
||||||
{ EConfigType.Anytls, "anytls" },
|
{ EConfigType.Anytls, "anytls" },
|
||||||
{ EConfigType.Naive, "naive" }
|
{ EConfigType.Naive, "naive" },
|
||||||
|
{ EConfigType.MASQUE, "masque" },
|
||||||
};
|
};
|
||||||
|
|
||||||
public static readonly List<string> VmessSecurities =
|
public static readonly List<string> VmessSecurities =
|
||||||
@@ -317,7 +337,8 @@ public class Global
|
|||||||
"kcp",
|
"kcp",
|
||||||
"grpc",
|
"grpc",
|
||||||
"ws",
|
"ws",
|
||||||
"httpupgrade"
|
"httpupgrade",
|
||||||
|
"xdrive"
|
||||||
];
|
];
|
||||||
|
|
||||||
public static readonly List<string> KcpHeaderTypes =
|
public static readonly List<string> KcpHeaderTypes =
|
||||||
@@ -354,6 +375,7 @@ public class Global
|
|||||||
EConfigType.Trojan,
|
EConfigType.Trojan,
|
||||||
EConfigType.Hysteria2,
|
EConfigType.Hysteria2,
|
||||||
EConfigType.WireGuard,
|
EConfigType.WireGuard,
|
||||||
|
EConfigType.MASQUE,
|
||||||
EConfigType.SOCKS,
|
EConfigType.SOCKS,
|
||||||
EConfigType.HTTP,
|
EConfigType.HTTP,
|
||||||
];
|
];
|
||||||
@@ -369,6 +391,7 @@ public class Global
|
|||||||
EConfigType.Anytls,
|
EConfigType.Anytls,
|
||||||
EConfigType.Naive,
|
EConfigType.Naive,
|
||||||
EConfigType.WireGuard,
|
EConfigType.WireGuard,
|
||||||
|
EConfigType.MASQUE,
|
||||||
EConfigType.SOCKS,
|
EConfigType.SOCKS,
|
||||||
EConfigType.HTTP,
|
EConfigType.HTTP,
|
||||||
];
|
];
|
||||||
@@ -406,6 +429,16 @@ public class Global
|
|||||||
""
|
""
|
||||||
];
|
];
|
||||||
|
|
||||||
|
public static readonly List<string> FragmentPacketsOptions =
|
||||||
|
[
|
||||||
|
"tlshello",
|
||||||
|
"1-1",
|
||||||
|
"1-2",
|
||||||
|
"1-3",
|
||||||
|
"1-4",
|
||||||
|
"1-5"
|
||||||
|
];
|
||||||
|
|
||||||
public static readonly List<string> UserAgent =
|
public static readonly List<string> UserAgent =
|
||||||
[
|
[
|
||||||
"chrome",
|
"chrome",
|
||||||
@@ -423,6 +456,18 @@ public class Global
|
|||||||
"stream-one"
|
"stream-one"
|
||||||
];
|
];
|
||||||
|
|
||||||
|
public static readonly List<string> XdriveServices = ["google-drive", "s3", "local"];
|
||||||
|
|
||||||
|
public static readonly List<string> XdriveProviders =
|
||||||
|
[
|
||||||
|
"Cloudflare R2",
|
||||||
|
"Google Drive",
|
||||||
|
"AWS S3 (Global)",
|
||||||
|
"Yandex Cloud S3",
|
||||||
|
"ArvanCloud S3",
|
||||||
|
"Custom S3"
|
||||||
|
];
|
||||||
|
|
||||||
public static readonly List<string> DomainStrategy =
|
public static readonly List<string> DomainStrategy =
|
||||||
[
|
[
|
||||||
"AsIs",
|
"AsIs",
|
||||||
@@ -454,6 +499,9 @@ public class Global
|
|||||||
"https://doh.dns.sb/dns-query",
|
"https://doh.dns.sb/dns-query",
|
||||||
"https://doh.opendns.com/dns-query",
|
"https://doh.opendns.com/dns-query",
|
||||||
"https://common.dot.dns.yandex.net/dns-query",
|
"https://common.dot.dns.yandex.net/dns-query",
|
||||||
|
"https://1.1.1.1/dns-query",
|
||||||
|
"https://8.8.8.8/dns-query",
|
||||||
|
"https://1.1.1.1/dns-query,https://8.8.8.8/dns-query",
|
||||||
"8.8.8.8",
|
"8.8.8.8",
|
||||||
"1.1.1.1",
|
"1.1.1.1",
|
||||||
"185.222.222.222",
|
"185.222.222.222",
|
||||||
@@ -468,15 +516,36 @@ public class Global
|
|||||||
"localhost"
|
"localhost"
|
||||||
];
|
];
|
||||||
|
|
||||||
|
public static readonly List<string> DomainDNS4PreResolveAddress =
|
||||||
|
[
|
||||||
|
"",
|
||||||
|
"https://doh.pub/dns-query",
|
||||||
|
"https://dns.alidns.com/dns-query",
|
||||||
|
"119.29.29.29",
|
||||||
|
"223.5.5.5",
|
||||||
|
"localhost",
|
||||||
|
"https://cloudflare-dns.com/dns-query",
|
||||||
|
"https://dns.google/dns-query",
|
||||||
|
"8.8.8.8",
|
||||||
|
"1.1.1.1",
|
||||||
|
];
|
||||||
|
|
||||||
|
public static readonly List<LanguageOption> LanguageOptions =
|
||||||
|
[
|
||||||
|
new("zh-Hans", "简体中文"),
|
||||||
|
new("zh-Hant", "繁體中文"),
|
||||||
|
new("en", "English"),
|
||||||
|
new("fa", "فارسی"),
|
||||||
|
new("fr", "Français"),
|
||||||
|
new("ru", "Русский"),
|
||||||
|
new("hu", "Magyar"),
|
||||||
|
new("id", "Bahasa Indonesia"),
|
||||||
|
new("az", "Azərbaycan dili")
|
||||||
|
];
|
||||||
|
|
||||||
public static readonly List<string> Languages =
|
public static readonly List<string> Languages =
|
||||||
[
|
[
|
||||||
"zh-Hans",
|
.. LanguageOptions.Select(t => t.Value)
|
||||||
"zh-Hant",
|
|
||||||
"en",
|
|
||||||
"fa",
|
|
||||||
"fr",
|
|
||||||
"ru",
|
|
||||||
"hu"
|
|
||||||
];
|
];
|
||||||
|
|
||||||
public static readonly List<string> Alpns =
|
public static readonly List<string> Alpns =
|
||||||
@@ -512,7 +581,8 @@ public class Global
|
|||||||
"tun",
|
"tun",
|
||||||
"socks",
|
"socks",
|
||||||
"socks2",
|
"socks2",
|
||||||
"socks3"
|
"socks3",
|
||||||
|
"dns-module"
|
||||||
];
|
];
|
||||||
|
|
||||||
public static readonly List<string> RuleProtocols =
|
public static readonly List<string> RuleProtocols =
|
||||||
@@ -536,7 +606,6 @@ public class Global
|
|||||||
"http",
|
"http",
|
||||||
"tls",
|
"tls",
|
||||||
"quic",
|
"quic",
|
||||||
"fakedns",
|
|
||||||
];
|
];
|
||||||
|
|
||||||
public static readonly List<int> TunMtus =
|
public static readonly List<int> TunMtus =
|
||||||
@@ -556,6 +625,16 @@ public class Global
|
|||||||
"mixed"
|
"mixed"
|
||||||
];
|
];
|
||||||
|
|
||||||
|
public const string TunDnsModeDefault = "Default";
|
||||||
|
|
||||||
|
public static readonly List<string> TunDnsModes =
|
||||||
|
[
|
||||||
|
TunDnsModeDefault,
|
||||||
|
"disabled",
|
||||||
|
"native",
|
||||||
|
"hijack"
|
||||||
|
];
|
||||||
|
|
||||||
public static readonly List<string> PresetMsgFilters =
|
public static readonly List<string> PresetMsgFilters =
|
||||||
[
|
[
|
||||||
"proxy",
|
"proxy",
|
||||||
@@ -620,10 +699,10 @@ public class Global
|
|||||||
{ ECoreType.Xray, "XTLS/Xray-core" },
|
{ ECoreType.Xray, "XTLS/Xray-core" },
|
||||||
{ ECoreType.sing_box, "SagerNet/sing-box" },
|
{ ECoreType.sing_box, "SagerNet/sing-box" },
|
||||||
{ ECoreType.mihomo, "MetaCubeX/mihomo" },
|
{ ECoreType.mihomo, "MetaCubeX/mihomo" },
|
||||||
{ ECoreType.hysteria, "apernet/hysteria" },
|
{ ECoreType.hysteria, "HyNetworks/hysteria" },
|
||||||
{ ECoreType.hysteria2, "apernet/hysteria" },
|
{ ECoreType.hysteria2, "HyNetworks/hysteria" },
|
||||||
{ ECoreType.naiveproxy, "klzgrad/naiveproxy" },
|
{ ECoreType.naiveproxy, "klzgrad/naiveproxy" },
|
||||||
{ ECoreType.tuic, "EAimTY/tuic" },
|
{ ECoreType.tuic, "tuic-protocol/tuic" },
|
||||||
{ ECoreType.juicity, "juicity/juicity" },
|
{ ECoreType.juicity, "juicity/juicity" },
|
||||||
{ ECoreType.brook, "txthinking/brook" },
|
{ ECoreType.brook, "txthinking/brook" },
|
||||||
{ ECoreType.overtls, "ShadowsocksR-Live/overtls" },
|
{ ECoreType.overtls, "ShadowsocksR-Live/overtls" },
|
||||||
@@ -666,6 +745,14 @@ public class Global
|
|||||||
"mcbe:bedrock.talonmc.net",
|
"mcbe:bedrock.talonmc.net",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
public static readonly List<string> DefaultRealmStunList =
|
||||||
|
[
|
||||||
|
"turn.cloudflare.com:3478",
|
||||||
|
"stun.nextcloud.com:3478",
|
||||||
|
"stun.sip.us:3478",
|
||||||
|
"global.stun.twilio.com:3478",
|
||||||
|
];
|
||||||
|
|
||||||
public static readonly List<string> OutboundTags =
|
public static readonly List<string> OutboundTags =
|
||||||
[
|
[
|
||||||
ProxyTag,
|
ProxyTag,
|
||||||
@@ -708,5 +795,48 @@ public class Global
|
|||||||
"reply",
|
"reply",
|
||||||
];
|
];
|
||||||
|
|
||||||
#endregion const
|
public static readonly List<string> FakeIPRanges =
|
||||||
|
[
|
||||||
|
"198.18.0.0/15",
|
||||||
|
"11.0.0.0/8",
|
||||||
|
];
|
||||||
|
|
||||||
|
public static readonly List<string> FakeIPv6Ranges =
|
||||||
|
[
|
||||||
|
"fc00::/18",
|
||||||
|
"2001:2::/48",
|
||||||
|
];
|
||||||
|
|
||||||
|
public static readonly List<string> RootCertProviders =
|
||||||
|
[
|
||||||
|
"system",
|
||||||
|
ChromeRootProvider,
|
||||||
|
MozillaRootProvider,
|
||||||
|
];
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<string> TunIPv4Address =
|
||||||
|
[
|
||||||
|
"172.18.0.1/30",
|
||||||
|
"172.31.0.1/30",
|
||||||
|
"172.20.0.1/30",
|
||||||
|
"172.16.0.1/30",
|
||||||
|
"192.168.100.1/30",
|
||||||
|
"10.10.14.1/30",
|
||||||
|
"10.1.0.1/30",
|
||||||
|
"10.0.0.1/30",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Prefixes must leave room for a peer address (max /126); the sing-box system
|
||||||
|
// stack derives a gateway from the first prefix and rejects single-address prefixes.
|
||||||
|
public static readonly IReadOnlyList<string> TunIPv6Address =
|
||||||
|
[
|
||||||
|
"fc00::172:18:0:1/126",
|
||||||
|
"fc00::172:31:0:1/126",
|
||||||
|
"fc00::172:20:0:1/126",
|
||||||
|
"fc00::172:16:0:1/126",
|
||||||
|
"fc00::192:168:100:1/126",
|
||||||
|
"fc00::10:10:14:1/126",
|
||||||
|
"fc00::10:1:0:1/126",
|
||||||
|
"fc00::10:0:0:1/126",
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
global using System.Collections.Concurrent;
|
global using System.Collections.Concurrent;
|
||||||
|
global using System.Collections.ObjectModel;
|
||||||
|
global using System.Collections.Specialized;
|
||||||
|
global using System.ComponentModel;
|
||||||
global using System.Diagnostics;
|
global using System.Diagnostics;
|
||||||
global using System.Net;
|
global using System.Net;
|
||||||
global using System.Net.NetworkInformation;
|
global using System.Net.NetworkInformation;
|
||||||
global using System.Net.Sockets;
|
global using System.Net.Sockets;
|
||||||
global using System.Reactive;
|
|
||||||
global using System.Reactive.Disposables;
|
|
||||||
global using System.Reactive.Linq;
|
|
||||||
global using System.Reflection;
|
global using System.Reflection;
|
||||||
global using System.Runtime.InteropServices;
|
global using System.Runtime.InteropServices;
|
||||||
global using System.Runtime.Versioning;
|
global using System.Runtime.Versioning;
|
||||||
@@ -16,10 +16,13 @@ global using System.Text.Json;
|
|||||||
global using System.Text.Json.Nodes;
|
global using System.Text.Json.Nodes;
|
||||||
global using System.Text.Json.Serialization;
|
global using System.Text.Json.Serialization;
|
||||||
global using System.Text.RegularExpressions;
|
global using System.Text.RegularExpressions;
|
||||||
global using DynamicData;
|
|
||||||
global using DynamicData.Binding;
|
|
||||||
global using ReactiveUI;
|
global using ReactiveUI;
|
||||||
global using ReactiveUI.Fody.Helpers;
|
global using ReactiveUI.Primitives;
|
||||||
|
global using ReactiveUI.Primitives.Concurrency;
|
||||||
|
global using ReactiveUI.Primitives.Disposables;
|
||||||
|
global using ReactiveUI.Primitives.Extensions;
|
||||||
|
global using ReactiveUI.Primitives.Signals;
|
||||||
|
global using ReactiveUI.SourceGenerators;
|
||||||
global using ServiceLib.Base;
|
global using ServiceLib.Base;
|
||||||
global using ServiceLib.Common;
|
global using ServiceLib.Common;
|
||||||
global using ServiceLib.Enums;
|
global using ServiceLib.Enums;
|
||||||
@@ -28,10 +31,11 @@ global using ServiceLib.Handler;
|
|||||||
global using ServiceLib.Handler.Builder;
|
global using ServiceLib.Handler.Builder;
|
||||||
global using ServiceLib.Handler.Fmt;
|
global using ServiceLib.Handler.Fmt;
|
||||||
global using ServiceLib.Handler.SysProxy;
|
global using ServiceLib.Handler.SysProxy;
|
||||||
|
global using ServiceLib.Handler.Data;
|
||||||
global using ServiceLib.Helper;
|
global using ServiceLib.Helper;
|
||||||
global using ServiceLib.Manager;
|
global using ServiceLib.Manager;
|
||||||
global using ServiceLib.Models.CoreConfigs;
|
|
||||||
global using ServiceLib.Models.Configs;
|
global using ServiceLib.Models.Configs;
|
||||||
|
global using ServiceLib.Models.CoreConfigs;
|
||||||
global using ServiceLib.Models.Dto;
|
global using ServiceLib.Models.Dto;
|
||||||
global using ServiceLib.Models.Entities;
|
global using ServiceLib.Models.Entities;
|
||||||
global using ServiceLib.Resx;
|
global using ServiceLib.Resx;
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
using System.Security.Principal;
|
|
||||||
|
|
||||||
namespace ServiceLib.Handler;
|
namespace ServiceLib.Handler;
|
||||||
|
|
||||||
public static class AutoStartupHandler
|
public static class AutoStartupHandler
|
||||||
@@ -87,6 +85,7 @@ public static class AutoStartupHandler
|
|||||||
[SupportedOSPlatform("windows")]
|
[SupportedOSPlatform("windows")]
|
||||||
public static void AutoStartTaskService(string taskName, string fileName, string description)
|
public static void AutoStartTaskService(string taskName, string fileName, string description)
|
||||||
{
|
{
|
||||||
|
#if false
|
||||||
if (taskName.IsNullOrEmpty())
|
if (taskName.IsNullOrEmpty())
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -117,6 +116,78 @@ public static class AutoStartupHandler
|
|||||||
task.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(fileName.AppendQuotes(), null, Path.GetDirectoryName(fileName)));
|
task.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(fileName.AppendQuotes(), null, Path.GetDirectoryName(fileName)));
|
||||||
|
|
||||||
taskService.RootFolder.RegisterTaskDefinition(taskName, task);
|
taskService.RootFolder.RegisterTaskDefinition(taskName, task);
|
||||||
|
#endif
|
||||||
|
if (string.IsNullOrEmpty(taskName))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RunSchtasks($"/Delete /TN \"{taskName}\" /F");
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(fileName))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var workingDir = Path.GetDirectoryName(fileName) ?? string.Empty;
|
||||||
|
|
||||||
|
var taskXml = EmbedUtils.GetEmbedText(Global.TaskXmlTemplateFileName);
|
||||||
|
|
||||||
|
taskXml = taskXml
|
||||||
|
.Replace("{{DESCRIPTION}}", System.Security.SecurityElement.Escape(description ?? ""))
|
||||||
|
.Replace("{{EXEC_PATH}}", System.Security.SecurityElement.Escape(fileName ?? ""))
|
||||||
|
.Replace("{{ARGUMENTS}}", string.Empty)
|
||||||
|
.Replace("{{WORKING_DIRECTORY}}", System.Security.SecurityElement.Escape(workingDir ?? ""));
|
||||||
|
|
||||||
|
var taskXmlFileName = Utils.GetTempPath($"{Utils.GetGuid(false)}.xml");
|
||||||
|
|
||||||
|
File.WriteAllText(taskXmlFileName, taskXml);
|
||||||
|
|
||||||
|
RunSchtasks(
|
||||||
|
"/Create",
|
||||||
|
"/TN", taskName,
|
||||||
|
"/XML", taskXmlFileName,
|
||||||
|
"/F"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool RunSchtasks(params string[] arguments)
|
||||||
|
{
|
||||||
|
var psi = new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = "schtasks.exe",
|
||||||
|
UseShellExecute = false,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var argument in arguments)
|
||||||
|
{
|
||||||
|
psi.ArgumentList.Add(argument);
|
||||||
|
}
|
||||||
|
|
||||||
|
using var process = Process.Start(psi);
|
||||||
|
|
||||||
|
if (process == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
process.WaitForExit();
|
||||||
|
|
||||||
|
var output = process.StandardOutput.ReadToEnd();
|
||||||
|
var error = process.StandardError.ReadToEnd();
|
||||||
|
if (!string.IsNullOrEmpty(output))
|
||||||
|
{
|
||||||
|
Logging.SaveLog($"RunSchtasks output: {output}");
|
||||||
|
}
|
||||||
|
if (!string.IsNullOrEmpty(error))
|
||||||
|
{
|
||||||
|
Logging.SaveLog($"RunSchtasks error: {error}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return process.ExitCode == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string GetAutoRunNameWindows()
|
private static string GetAutoRunNameWindows()
|
||||||
@@ -180,19 +251,16 @@ public static class AutoStartupHandler
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var launchAgentPath = GetLaunchAgentPathMacOS();
|
// Do not "launchctl unload" the agent: launchd then terminates the job's processes, which is
|
||||||
if (File.Exists(launchAgentPath))
|
// v2rayN itself when it was started at login. The agent only runs at load, so removing the
|
||||||
{
|
// plist is enough to stop the next start.
|
||||||
var args = new[] { "-c", $"launchctl unload -w \"{launchAgentPath}\"" };
|
File.Delete(GetLaunchAgentPathMacOS());
|
||||||
await Utils.GetCliWrapOutput(Global.LinuxBash, args);
|
|
||||||
|
|
||||||
File.Delete(launchAgentPath);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Logging.SaveLog(_tag, ex);
|
Logging.SaveLog(_tag, ex);
|
||||||
}
|
}
|
||||||
|
await Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
[SupportedOSPlatform("macos")]
|
[SupportedOSPlatform("macos")]
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ public record CoreConfigContextBuilderResult(CoreConfigContext Context, NodeVali
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Holds the results of a full context build, including the main context and an optional
|
/// Holds the results of a full context build, including the main context and an optional
|
||||||
/// pre-socks context (e.g. for TUN protection or pre-socks chaining).
|
/// pre-socks context (e.g. for TUN protection or pre-socks chaining).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public record CoreConfigContextBuilderAllResult(
|
public record CoreConfigContextBuilderAllResult(
|
||||||
CoreConfigContextBuilderResult MainResult,
|
CoreConfigContextBuilderResult MainResult,
|
||||||
@@ -17,8 +17,8 @@ public record CoreConfigContextBuilderAllResult(
|
|||||||
public bool Success => MainResult.Success && (PreSocksResult?.Success ?? true);
|
public bool Success => MainResult.Success && (PreSocksResult?.Success ?? true);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Merges all errors and warnings from the main result and the optional pre-socks result
|
/// Merges all errors and warnings from the main result and the optional pre-socks result
|
||||||
/// into a single <see cref="NodeValidatorResult"/> for unified notification.
|
/// into a single <see cref="NodeValidatorResult" /> for unified notification.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public NodeValidatorResult CombinedValidatorResult => new(
|
public NodeValidatorResult CombinedValidatorResult => new(
|
||||||
[.. MainResult.ValidatorResult.Errors, .. PreSocksResult?.ValidatorResult.Errors ?? []],
|
[.. MainResult.ValidatorResult.Errors, .. PreSocksResult?.ValidatorResult.Errors ?? []],
|
||||||
@@ -28,27 +28,30 @@ public record CoreConfigContextBuilderAllResult(
|
|||||||
public class CoreConfigContextBuilder
|
public class CoreConfigContextBuilder
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Builds a <see cref="CoreConfigContext"/> for the given node, resolves its proxy map,
|
/// Builds a <see cref="CoreConfigContext" /> for the given node, resolves its proxy map,
|
||||||
/// and processes outbound nodes referenced by routing rules.
|
/// and processes outbound nodes referenced by routing rules.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static async Task<CoreConfigContextBuilderResult> Build(Config config, ProfileItem node)
|
public static async Task<CoreConfigContextBuilderResult> Build(Config config, ProfileItem node)
|
||||||
{
|
{
|
||||||
var runCoreType = AppManager.Instance.GetCoreType(node, node.ConfigType);
|
var runCoreType = AppManager.Instance.GetCoreType(node, node.ConfigType);
|
||||||
var coreType = runCoreType == ECoreType.sing_box ? ECoreType.sing_box : ECoreType.Xray;
|
var coreType = runCoreType == ECoreType.sing_box ? ECoreType.sing_box : ECoreType.Xray;
|
||||||
var context = new CoreConfigContext()
|
var context = new CoreConfigContext
|
||||||
{
|
{
|
||||||
Node = node,
|
Node = node,
|
||||||
RunCoreType = runCoreType,
|
RunCoreType = runCoreType,
|
||||||
AllProxiesMap = [],
|
AllProxiesMap = [],
|
||||||
AppConfig = config,
|
AppConfig = config,
|
||||||
FullConfigTemplate = await AppManager.Instance.GetFullConfigTemplateItem(coreType),
|
FullConfigTemplate = await ConfigDbQuery.GetFullConfigTemplateItem(coreType),
|
||||||
IsTunEnabled = config.TunModeItem.EnableTun,
|
IsTunEnabled = config.TunModeItem.EnableTun,
|
||||||
SimpleDnsItem = config.SimpleDNSItem,
|
SimpleDnsItem = config.SimpleDNSItem,
|
||||||
ProtectDomainList = [],
|
ProtectDomainList = [],
|
||||||
RawDnsItem = await AppManager.Instance.GetDNSItem(coreType),
|
RawDnsItem = await ConfigDbQuery.GetDNSItem(coreType),
|
||||||
RoutingItem = await ConfigHandler.GetDefaultRouting(config),
|
RoutingItem = await ConfigDbHandler.GetDefaultRouting(),
|
||||||
IsWindows = Utils.IsWindows(),
|
IsWindows = Utils.IsWindows(),
|
||||||
IsMacOS = Utils.IsMacOS(),
|
IsMacOS = Utils.IsMacOS(),
|
||||||
|
IsLinux = Utils.IsLinux(),
|
||||||
|
HasGlobalIPv6Address = Utils.HasGlobalIPv6Address(),
|
||||||
|
ProtectCoreTypeList = config.TunModeItem.EnableTun ? [ECoreType.Xray, ECoreType.sing_box] : []
|
||||||
};
|
};
|
||||||
var validatorResult = NodeValidatorResult.Empty();
|
var validatorResult = NodeValidatorResult.Empty();
|
||||||
var (actNode, nodeValidatorResult) = await ResolveNodeAsync(context, node);
|
var (actNode, nodeValidatorResult) = await ResolveNodeAsync(context, node);
|
||||||
@@ -61,7 +64,8 @@ public class CoreConfigContextBuilder
|
|||||||
if (!(context.RoutingItem?.RuleSet.IsNullOrEmpty() ?? true))
|
if (!(context.RoutingItem?.RuleSet.IsNullOrEmpty() ?? true))
|
||||||
{
|
{
|
||||||
var rules = JsonUtils.Deserialize<List<RulesItem>>(context.RoutingItem?.RuleSet) ?? [];
|
var rules = JsonUtils.Deserialize<List<RulesItem>>(context.RoutingItem?.RuleSet) ?? [];
|
||||||
foreach (var ruleItem in rules.Where(ruleItem => ruleItem.Enabled && !Global.OutboundTags.Contains(ruleItem.OutboundTag)))
|
foreach (var ruleItem in rules.Where(ruleItem =>
|
||||||
|
ruleItem.Enabled && !Global.OutboundTags.Contains(ruleItem.OutboundTag)))
|
||||||
{
|
{
|
||||||
if (ruleItem.OutboundTag.IsNullOrEmpty())
|
if (ruleItem.OutboundTag.IsNullOrEmpty())
|
||||||
{
|
{
|
||||||
@@ -69,10 +73,11 @@ public class CoreConfigContextBuilder
|
|||||||
ruleItem.OutboundTag = Global.ProxyTag;
|
ruleItem.OutboundTag = Global.ProxyTag;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
var ruleOutboundNode = await AppManager.Instance.GetProfileItemViaRemarks(ruleItem.OutboundTag);
|
var ruleOutboundNode = await ConfigDbQuery.GetProfileItemViaRemarks(ruleItem.OutboundTag);
|
||||||
if (ruleOutboundNode == null)
|
if (ruleOutboundNode == null)
|
||||||
{
|
{
|
||||||
validatorResult.Warnings.Add(string.Format(ResUI.MsgRoutingRuleOutboundNodeNotFound, ruleItem.Remarks, ruleItem.OutboundTag));
|
validatorResult.Warnings.Add(string.Format(ResUI.MsgRoutingRuleOutboundNodeNotFound,
|
||||||
|
ruleItem.Remarks, ruleItem.OutboundTag));
|
||||||
ruleItem.OutboundTag = Global.ProxyTag;
|
ruleItem.OutboundTag = Global.ProxyTag;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -83,7 +88,8 @@ public class CoreConfigContextBuilder
|
|||||||
if (!ruleNodeValidatorResult.Success)
|
if (!ruleNodeValidatorResult.Success)
|
||||||
{
|
{
|
||||||
validatorResult.Warnings.AddRange(ruleNodeValidatorResult.Errors.Select(e =>
|
validatorResult.Warnings.AddRange(ruleNodeValidatorResult.Errors.Select(e =>
|
||||||
string.Format(ResUI.MsgRoutingRuleOutboundNodeError, ruleItem.Remarks, ruleItem.OutboundTag, e)));
|
string.Format(ResUI.MsgRoutingRuleOutboundNodeError, ruleItem.Remarks, ruleItem.OutboundTag,
|
||||||
|
e)));
|
||||||
ruleItem.OutboundTag = Global.ProxyTag;
|
ruleItem.OutboundTag = Global.ProxyTag;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -91,28 +97,62 @@ public class CoreConfigContextBuilder
|
|||||||
context.AllProxiesMap[$"remark:{ruleItem.OutboundTag}"] = actRuleNode;
|
context.AllProxiesMap[$"remark:{ruleItem.OutboundTag}"] = actRuleNode;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (context.IsTunEnabled && context.AppConfig.TunModeItem.RouteExcludeAddress is { Count: > 0 })
|
if (context.IsTunEnabled && context.AppConfig.TunModeItem.RouteExcludeAddress is { Count: > 0 })
|
||||||
{
|
{
|
||||||
|
var appConfig = JsonUtils.DeepCopy(config);
|
||||||
|
var routeExcludeAddressList = new List<string>();
|
||||||
foreach (var addr in context.AppConfig.TunModeItem.RouteExcludeAddress)
|
foreach (var addr in context.AppConfig.TunModeItem.RouteExcludeAddress)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
IPNetwork2.Parse(addr);
|
IPNetwork2.Parse(addr);
|
||||||
|
routeExcludeAddressList.Add(addr);
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
validatorResult.Errors.Add(string.Format(ResUI.MsgTunRouteExcludeInvalidAddress, addr));
|
validatorResult.Warnings.Add(string.Format(ResUI.MsgTunRouteExcludeInvalidAddress, addr));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
appConfig.TunModeItem.RouteExcludeAddress = routeExcludeAddressList;
|
||||||
|
context = context with { AppConfig = appConfig };
|
||||||
|
}
|
||||||
|
if (!context.AppConfig.CoreBasicItem.SendThrough.IsNullOrEmpty()
|
||||||
|
&& !Utils.IsLocalIP(context.AppConfig.CoreBasicItem.SendThrough))
|
||||||
|
{
|
||||||
|
validatorResult.Warnings.Add(string.Format(ResUI.MsgInvalidProperty, ResUI.TbSettingsSendThrough));
|
||||||
|
var appConfig = JsonUtils.DeepCopy(context.AppConfig);
|
||||||
|
appConfig.CoreBasicItem.SendThrough = string.Empty;
|
||||||
|
context = context with { AppConfig = appConfig };
|
||||||
|
}
|
||||||
|
var bindInterface = context.AppConfig.CoreBasicItem.BindInterface?.TrimEx();
|
||||||
|
if (bindInterface.IsNotEmpty())
|
||||||
|
{
|
||||||
|
if (NetworkUtils.IsAutoBindInterface(bindInterface))
|
||||||
|
{
|
||||||
|
bindInterface = NetworkUtils.GetDefaultPhysicalInterfaceName()?.TrimEx();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bindInterface.IsNullOrEmpty()
|
||||||
|
|| !Utils.ContainsInterfaceName(bindInterface)
|
||||||
|
|| !(context.IsTunEnabled || context.IsWindows))
|
||||||
|
{
|
||||||
|
validatorResult.Warnings.Add(string.Format(ResUI.MsgInvalidProperty, ResUI.TbSettingsBindInterface));
|
||||||
|
bindInterface = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
var appConfig = JsonUtils.DeepCopy(context.AppConfig);
|
||||||
|
appConfig.CoreBasicItem.BindInterface = bindInterface;
|
||||||
|
context = context with { AppConfig = appConfig };
|
||||||
}
|
}
|
||||||
|
|
||||||
return new CoreConfigContextBuilderResult(context, validatorResult);
|
return new CoreConfigContextBuilderResult(context, validatorResult);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Builds the main <see cref="CoreConfigContext"/> for <paramref name="node"/> and, when
|
/// Builds the main <see cref="CoreConfigContext" /> for <paramref name="node" /> and, when
|
||||||
/// the main build succeeds, also builds the optional pre-socks context required for TUN
|
/// the main build succeeds, also builds the optional pre-socks context required for TUN
|
||||||
/// protection or pre-socks proxy chaining.
|
/// protection or pre-socks proxy chaining.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static async Task<CoreConfigContextBuilderAllResult> BuildAll(Config config, ProfileItem node)
|
public static async Task<CoreConfigContextBuilderAllResult> BuildAll(Config config, ProfileItem node)
|
||||||
{
|
{
|
||||||
@@ -132,16 +172,31 @@ public class CoreConfigContextBuilder
|
|||||||
{
|
{
|
||||||
Context = mainResult.Context with
|
Context = mainResult.Context with
|
||||||
{
|
{
|
||||||
IsTunEnabled = false, // main core doesn't handle tun directly when pre-socks is used
|
IsTunEnabled = false,
|
||||||
|
// main core doesn't handle tun directly when pre-socks is used
|
||||||
ProtectDomainList = [.. mainResult.Context.ProtectDomainList, .. preResult.Context.ProtectDomainList],
|
ProtectDomainList = [.. mainResult.Context.ProtectDomainList, .. preResult.Context.ProtectDomainList],
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
if (mainResult.Context.IsTunEnabled
|
||||||
|
&& mainResult.Context.AppConfig.TunModeItem.StrictRoute)
|
||||||
|
{
|
||||||
|
var appConfig = JsonUtils.DeepCopy(mainResult.Context.AppConfig);
|
||||||
|
appConfig.CoreBasicItem.BindInterface = string.Empty;
|
||||||
|
appConfig.CoreBasicItem.SendThrough = string.Empty;
|
||||||
|
resolvedMainResult = resolvedMainResult with
|
||||||
|
{
|
||||||
|
Context = resolvedMainResult.Context with
|
||||||
|
{
|
||||||
|
AppConfig = appConfig,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
return new CoreConfigContextBuilderAllResult(resolvedMainResult, preResult);
|
return new CoreConfigContextBuilderAllResult(resolvedMainResult, preResult);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Determines whether a pre-socks context is required for <paramref name="nodeContext"/>
|
/// Determines whether a pre-socks context is required for <paramref name="nodeContext" />
|
||||||
/// and, if so, builds and returns it. Returns <c>null</c> when no pre-socks core is needed.
|
/// and, if so, builds and returns it. Returns <c>null</c> when no pre-socks core is needed.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static async Task<CoreConfigContextBuilderResult?> BuildPreSocksIfNeeded(CoreConfigContext nodeContext)
|
private static async Task<CoreConfigContextBuilderResult?> BuildPreSocksIfNeeded(CoreConfigContext nodeContext)
|
||||||
{
|
{
|
||||||
@@ -149,16 +204,21 @@ public class CoreConfigContextBuilder
|
|||||||
var node = nodeContext.Node;
|
var node = nodeContext.Node;
|
||||||
var coreType = AppManager.Instance.GetCoreType(node, node.ConfigType);
|
var coreType = AppManager.Instance.GetCoreType(node, node.ConfigType);
|
||||||
|
|
||||||
var preSocksItem = ConfigHandler.GetPreSocksItem(config, node, coreType);
|
var preSocksItem = GetPreSocksItem(config, node, coreType);
|
||||||
if (preSocksItem != null)
|
if (preSocksItem != null)
|
||||||
{
|
{
|
||||||
var preSocksResult = await Build(nodeContext.AppConfig, preSocksItem);
|
var preSocksResult = await Build(nodeContext.AppConfig, preSocksItem);
|
||||||
|
|
||||||
|
var protectCoreTypeList = new HashSet<ECoreType>(nodeContext.ProtectCoreTypeList) { nodeContext.RunCoreType };
|
||||||
|
|
||||||
return preSocksResult with
|
return preSocksResult with
|
||||||
{
|
{
|
||||||
Context = preSocksResult.Context with
|
Context = preSocksResult.Context with
|
||||||
{
|
{
|
||||||
ProtectDomainList = [.. nodeContext.ProtectDomainList ?? [], .. preSocksResult.Context.ProtectDomainList ?? []],
|
ProtectDomainList =
|
||||||
}
|
[.. nodeContext.ProtectDomainList, .. preSocksResult.Context.ProtectDomainList],
|
||||||
|
ProtectCoreTypeList = protectCoreTypeList,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,8 +226,8 @@ public class CoreConfigContextBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Resolves a node into the context, optionally wrapping it in a subscription-level proxy chain.
|
/// Resolves a node into the context, optionally wrapping it in a subscription-level proxy chain.
|
||||||
/// Returns the effective (possibly replaced) node and the validation result.
|
/// Returns the effective (possibly replaced) node and the validation result.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static async Task<(ProfileItem, NodeValidatorResult)> ResolveNodeAsync(CoreConfigContext context,
|
public static async Task<(ProfileItem, NodeValidatorResult)> ResolveNodeAsync(CoreConfigContext context,
|
||||||
ProfileItem node,
|
ProfileItem node,
|
||||||
@@ -202,12 +262,13 @@ public class CoreConfigContextBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// If the node's subscription defines prev/next profiles, creates a virtual
|
/// If the node's subscription defines prev/next profiles, creates a virtual
|
||||||
/// <see cref="EConfigType.ProxyChain"/> node that wraps them together.
|
/// <see cref="EConfigType.ProxyChain" /> node that wraps them together.
|
||||||
/// Returns <c>null</c> as the chain item when no chain is needed.
|
/// Returns <c>null</c> as the chain item when no chain is needed.
|
||||||
/// Any warnings (e.g. missing prev/next profile) are returned in the validator result.
|
/// Any warnings (e.g. missing prev/next profile) are returned in the validator result.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static async Task<(ProfileItem? ChainNode, NodeValidatorResult ValidatorResult)> BuildSubscriptionChainNodeAsync(ProfileItem node)
|
private static async Task<(ProfileItem? ChainNode, NodeValidatorResult ValidatorResult)>
|
||||||
|
BuildSubscriptionChainNodeAsync(ProfileItem node)
|
||||||
{
|
{
|
||||||
var result = NodeValidatorResult.Empty();
|
var result = NodeValidatorResult.Empty();
|
||||||
|
|
||||||
@@ -216,7 +277,7 @@ public class CoreConfigContextBuilder
|
|||||||
return (null, result);
|
return (null, result);
|
||||||
}
|
}
|
||||||
|
|
||||||
var subItem = await AppManager.Instance.GetSubItem(node.Subid);
|
var subItem = await ConfigDbQuery.GetSubItem(node.Subid);
|
||||||
if (subItem == null)
|
if (subItem == null)
|
||||||
{
|
{
|
||||||
return (null, result);
|
return (null, result);
|
||||||
@@ -227,7 +288,7 @@ public class CoreConfigContextBuilder
|
|||||||
|
|
||||||
if (!subItem.PrevProfile.IsNullOrEmpty())
|
if (!subItem.PrevProfile.IsNullOrEmpty())
|
||||||
{
|
{
|
||||||
prevNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.PrevProfile);
|
prevNode = await ConfigDbQuery.GetProfileItemViaRemarks(subItem.PrevProfile);
|
||||||
if (prevNode == null)
|
if (prevNode == null)
|
||||||
{
|
{
|
||||||
result.Warnings.Add(string.Format(ResUI.MsgSubscriptionPrevProfileNotFound, subItem.PrevProfile));
|
result.Warnings.Add(string.Format(ResUI.MsgSubscriptionPrevProfileNotFound, subItem.PrevProfile));
|
||||||
@@ -235,7 +296,7 @@ public class CoreConfigContextBuilder
|
|||||||
}
|
}
|
||||||
if (!subItem.NextProfile.IsNullOrEmpty())
|
if (!subItem.NextProfile.IsNullOrEmpty())
|
||||||
{
|
{
|
||||||
nextNode = await AppManager.Instance.GetProfileItemViaRemarks(subItem.NextProfile);
|
nextNode = await ConfigDbQuery.GetProfileItemViaRemarks(subItem.NextProfile);
|
||||||
if (nextNode == null)
|
if (nextNode == null)
|
||||||
{
|
{
|
||||||
result.Warnings.Add(string.Format(ResUI.MsgSubscriptionNextProfileNotFound, subItem.NextProfile));
|
result.Warnings.Add(string.Format(ResUI.MsgSubscriptionNextProfileNotFound, subItem.NextProfile));
|
||||||
@@ -248,7 +309,7 @@ public class CoreConfigContextBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Build new proxy chain node
|
// Build new proxy chain node
|
||||||
var chainNode = new ProfileItem()
|
var chainNode = new ProfileItem
|
||||||
{
|
{
|
||||||
IndexId = $"inner-{Utils.GetGuid(false)}",
|
IndexId = $"inner-{Utils.GetGuid(false)}",
|
||||||
ConfigType = EConfigType.ProxyChain,
|
ConfigType = EConfigType.ProxyChain,
|
||||||
@@ -266,8 +327,8 @@ public class CoreConfigContextBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Dispatches registration to either <see cref="RegisterGroupNodeAsync"/> or
|
/// Dispatches registration to either <see cref="RegisterGroupNodeAsync" /> or
|
||||||
/// <see cref="RegisterSingleNodeAsync"/> based on the node's config type.
|
/// <see cref="RegisterSingleNodeAsync" /> based on the node's config type.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static async Task<NodeValidatorResult> RegisterNodeAsync(CoreConfigContext context, ProfileItem node)
|
private static async Task<NodeValidatorResult> RegisterNodeAsync(CoreConfigContext context, ProfileItem node)
|
||||||
{
|
{
|
||||||
@@ -275,17 +336,14 @@ public class CoreConfigContextBuilder
|
|||||||
{
|
{
|
||||||
return await RegisterGroupNodeAsync(context, node);
|
return await RegisterGroupNodeAsync(context, node);
|
||||||
}
|
}
|
||||||
else
|
return await RegisterSingleNodeAsync(context, node);
|
||||||
{
|
|
||||||
return RegisterSingleNodeAsync(context, node);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Validates a single (non-group) node and, on success, adds it to the proxy map
|
/// Validates a single (non-group) node and, on success, adds it to the proxy map
|
||||||
/// and records any domain addresses that should bypass the proxy.
|
/// and records any domain addresses that should bypass the proxy.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static NodeValidatorResult RegisterSingleNodeAsync(CoreConfigContext context, ProfileItem node)
|
private static async Task<NodeValidatorResult> RegisterSingleNodeAsync(CoreConfigContext context, ProfileItem node)
|
||||||
{
|
{
|
||||||
if (node.ConfigType.IsGroupType())
|
if (node.ConfigType.IsGroupType())
|
||||||
{
|
{
|
||||||
@@ -293,6 +351,29 @@ public class CoreConfigContextBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
var nodeValidatorResult = NodeValidator.Validate(node, context.RunCoreType);
|
var nodeValidatorResult = NodeValidator.Validate(node, context.RunCoreType);
|
||||||
|
|
||||||
|
if (node.ConfigType == EConfigType.Outbound)
|
||||||
|
{
|
||||||
|
var addressFileName = node.Address;
|
||||||
|
if (!File.Exists(addressFileName))
|
||||||
|
{
|
||||||
|
addressFileName = Utils.GetConfigPath(addressFileName);
|
||||||
|
}
|
||||||
|
if (!File.Exists(addressFileName))
|
||||||
|
{
|
||||||
|
nodeValidatorResult.Errors.Add(string.Format(ResUI.MsgCustomOutboundFileNotFound, node.Remarks, addressFileName));
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var fileContent = await File.ReadAllTextAsync(addressFileName);
|
||||||
|
context.CustomOutboundContent[node.IndexId] = fileContent;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
nodeValidatorResult.Errors.Add(string.Format(ResUI.MsgCustomOutboundFileNotFound, node.Remarks, addressFileName));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var msgs = new List<string>([.. nodeValidatorResult.Errors, .. nodeValidatorResult.Warnings]);
|
var msgs = new List<string>([.. nodeValidatorResult.Errors, .. nodeValidatorResult.Warnings]);
|
||||||
if (msgs.Count > 0)
|
if (msgs.Count > 0)
|
||||||
{
|
{
|
||||||
@@ -316,7 +397,7 @@ public class CoreConfigContextBuilder
|
|||||||
{
|
{
|
||||||
var echQuerySni = node.Sni;
|
var echQuerySni = node.Sni;
|
||||||
if (node.StreamSecurity == Global.StreamSecurity
|
if (node.StreamSecurity == Global.StreamSecurity
|
||||||
&& node.EchConfigList?.Contains("://") == true)
|
&& node.EchConfigList.Contains("://"))
|
||||||
{
|
{
|
||||||
var idx = node.EchConfigList.IndexOf('+');
|
var idx = node.EchConfigList.IndexOf('+');
|
||||||
echQuerySni = idx > 0 ? node.EchConfigList[..idx] : node.Sni;
|
echQuerySni = idx > 0 ? node.EchConfigList[..idx] : node.Sni;
|
||||||
@@ -347,8 +428,8 @@ public class CoreConfigContextBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Entry point for registering a group node. Initialises the visited/ancestor sets
|
/// Entry point for registering a group node. Initialises the visited/ancestor sets
|
||||||
/// and delegates to <see cref="TraverseGroupNodeAsync"/>.
|
/// and delegates to <see cref="TraverseGroupNodeAsync" />.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static async Task<NodeValidatorResult> RegisterGroupNodeAsync(CoreConfigContext context,
|
private static async Task<NodeValidatorResult> RegisterGroupNodeAsync(CoreConfigContext context,
|
||||||
ProfileItem node)
|
ProfileItem node)
|
||||||
@@ -364,9 +445,9 @@ public class CoreConfigContextBuilder
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Recursively walks the children of a group node, registering valid leaf nodes
|
/// Recursively walks the children of a group node, registering valid leaf nodes
|
||||||
/// and nested groups. Detects cycles via <paramref name="ancestorsGroup"/> and
|
/// and nested groups. Detects cycles via <paramref name="ancestorsGroup" /> and
|
||||||
/// deduplicates shared nodes via <paramref name="globalVisitedGroup"/>.
|
/// deduplicates shared nodes via <paramref name="globalVisitedGroup" />.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static async Task<NodeValidatorResult> TraverseGroupNodeAsync(
|
private static async Task<NodeValidatorResult> TraverseGroupNodeAsync(
|
||||||
CoreConfigContext context,
|
CoreConfigContext context,
|
||||||
@@ -394,7 +475,7 @@ public class CoreConfigContextBuilder
|
|||||||
|
|
||||||
if (!childNode.ConfigType.IsGroupType())
|
if (!childNode.ConfigType.IsGroupType())
|
||||||
{
|
{
|
||||||
var childNodeResult = RegisterSingleNodeAsync(context, childNode);
|
var childNodeResult = await RegisterSingleNodeAsync(context, childNode);
|
||||||
childNodeValidatorResult.Warnings.AddRange(childNodeResult.Warnings.Select(w =>
|
childNodeValidatorResult.Warnings.AddRange(childNodeResult.Warnings.Select(w =>
|
||||||
string.Format(ResUI.MsgGroupChildNodeWarning, node.Remarks, childNode.Remarks, w)));
|
string.Format(ResUI.MsgGroupChildNodeWarning, node.Remarks, childNode.Remarks, w)));
|
||||||
childNodeValidatorResult.Errors.AddRange(childNodeResult.Errors.Select(e =>
|
childNodeValidatorResult.Errors.AddRange(childNodeResult.Errors.Select(e =>
|
||||||
@@ -430,14 +511,52 @@ public class CoreConfigContextBuilder
|
|||||||
childNodeValidatorResult.Errors.Add(string.Format(ResUI.MsgGroupNoValidChildNode, node.Remarks));
|
childNodeValidatorResult.Errors.Add(string.Format(ResUI.MsgGroupNoValidChildNode, node.Remarks));
|
||||||
return childNodeValidatorResult;
|
return childNodeValidatorResult;
|
||||||
}
|
}
|
||||||
else
|
childNodeValidatorResult.Warnings.AddRange(childNodeValidatorResult.Errors);
|
||||||
{
|
childNodeValidatorResult.Errors.Clear();
|
||||||
childNodeValidatorResult.Warnings.AddRange(childNodeValidatorResult.Errors);
|
|
||||||
childNodeValidatorResult.Errors.Clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
node.SetProtocolExtra(node.GetProtocolExtra() with { ChildItems = Utils.List2String(childIndexIdList), });
|
node.SetProtocolExtra(node.GetProtocolExtra() with { ChildItems = Utils.List2String(childIndexIdList) });
|
||||||
context.AllProxiesMap[node.IndexId] = node;
|
context.AllProxiesMap[node.IndexId] = node;
|
||||||
return childNodeValidatorResult;
|
return childNodeValidatorResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get a SOCKS server profile for pre-SOCKS functionality
|
||||||
|
/// Used when TUN mode is enabled or when a custom config has a pre-SOCKS port
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="config">Current configuration</param>
|
||||||
|
/// <param name="node">Server node that might need pre-SOCKS</param>
|
||||||
|
/// <param name="coreType">Core type being used</param>
|
||||||
|
/// <returns>A SOCKS profile item or null if not needed</returns>
|
||||||
|
private static ProfileItem? GetPreSocksItem(Config config, ProfileItem node, ECoreType coreType)
|
||||||
|
{
|
||||||
|
ProfileItem? itemSocks = null;
|
||||||
|
var enableLegacyProtect = config.TunModeItem.EnableLegacyProtect;
|
||||||
|
if (node.ConfigType != EConfigType.Custom
|
||||||
|
&& coreType != ECoreType.sing_box
|
||||||
|
&& config.TunModeItem.EnableTun
|
||||||
|
&& enableLegacyProtect)
|
||||||
|
{
|
||||||
|
itemSocks = new ProfileItem()
|
||||||
|
{
|
||||||
|
CoreType = ECoreType.sing_box,
|
||||||
|
ConfigType = EConfigType.SOCKS,
|
||||||
|
Address = Global.Loopback,
|
||||||
|
Port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else if (node.ConfigType == EConfigType.Custom
|
||||||
|
&& node.PreSocksPort is > 0 and <= 65535)
|
||||||
|
{
|
||||||
|
var customPreCoreType = AppManager.Instance.GetCoreType(null, EConfigType.Custom);
|
||||||
|
var preCoreType = (enableLegacyProtect && config.TunModeItem.EnableTun) ? ECoreType.sing_box : customPreCoreType;
|
||||||
|
itemSocks = new ProfileItem()
|
||||||
|
{
|
||||||
|
CoreType = preCoreType,
|
||||||
|
ConfigType = EConfigType.SOCKS,
|
||||||
|
Address = Global.Loopback,
|
||||||
|
Port = node.PreSocksPort.Value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return itemSocks;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,15 @@ public class NodeValidator
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (item.ConfigType is EConfigType.Outbound)
|
||||||
|
{
|
||||||
|
if (item.CoreType != coreType)
|
||||||
|
{
|
||||||
|
v.Error(string.Format(ResUI.MsgCoreNotSupportProtocol, coreType.ToString(), item.ConfigType));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (item.ConfigType.IsGroupType())
|
if (item.ConfigType.IsGroupType())
|
||||||
{
|
{
|
||||||
// Group logic is handled in ValidateGroupNode
|
// Group logic is handled in ValidateGroupNode
|
||||||
@@ -43,8 +52,8 @@ public class NodeValidator
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Basic Property Validation
|
// Basic Property Validation
|
||||||
v.Assert(!item.Address.IsNullOrEmpty(), string.Format(ResUI.MsgInvalidProperty, "Address"));
|
v.Assert(!item.Address.IsNullOrEmpty(), string.Format(ResUI.MsgInvalidProperty, ResUI.TbAddress));
|
||||||
v.Assert(item.Port is > 0 and <= 65535, string.Format(ResUI.MsgInvalidProperty, "Port"));
|
v.Assert(item.Port is > 0 and <= 65535, string.Format(ResUI.MsgInvalidProperty, ResUI.TbPort));
|
||||||
|
|
||||||
// Network & Core Logic
|
// Network & Core Logic
|
||||||
var net = item.GetNetwork();
|
var net = item.GetNetwork();
|
||||||
@@ -75,25 +84,25 @@ public class NodeValidator
|
|||||||
{
|
{
|
||||||
case EConfigType.VMess:
|
case EConfigType.VMess:
|
||||||
v.Assert(!item.Password.IsNullOrEmpty() && Utils.IsGuidByParse(item.Password),
|
v.Assert(!item.Password.IsNullOrEmpty() && Utils.IsGuidByParse(item.Password),
|
||||||
string.Format(ResUI.MsgInvalidProperty, "Password"));
|
string.Format(ResUI.MsgInvalidProperty, ResUI.TbId));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case EConfigType.VLESS:
|
case EConfigType.VLESS:
|
||||||
v.Assert(
|
v.Assert(
|
||||||
!item.Password.IsNullOrEmpty()
|
!item.Password.IsNullOrEmpty()
|
||||||
&& (Utils.IsGuidByParse(item.Password) || item.Password.Length <= 30),
|
&& (Utils.IsGuidByParse(item.Password) || item.Password.Length <= 30),
|
||||||
string.Format(ResUI.MsgInvalidProperty, "Password")
|
string.Format(ResUI.MsgInvalidProperty, ResUI.TbId5)
|
||||||
);
|
);
|
||||||
v.Assert(Global.Flows.Contains(protocolExtra.Flow ?? string.Empty),
|
v.Assert(Global.Flows.Contains(protocolExtra.Flow ?? string.Empty),
|
||||||
string.Format(ResUI.MsgInvalidProperty, "Flow"));
|
string.Format(ResUI.MsgInvalidProperty, ResUI.TbFlow5));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case EConfigType.Shadowsocks:
|
case EConfigType.Shadowsocks:
|
||||||
v.Assert(!item.Password.IsNullOrEmpty(), string.Format(ResUI.MsgInvalidProperty, "Password"));
|
v.Assert(!item.Password.IsNullOrEmpty(), string.Format(ResUI.MsgInvalidProperty, ResUI.TbId3));
|
||||||
v.Assert(
|
v.Assert(
|
||||||
!string.IsNullOrEmpty(protocolExtra.SsMethod) &&
|
!string.IsNullOrEmpty(protocolExtra.SsMethod) &&
|
||||||
Global.SsSecuritiesInSingbox.Contains(protocolExtra.SsMethod),
|
Global.SsSecuritiesInSingbox.Contains(protocolExtra.SsMethod),
|
||||||
string.Format(ResUI.MsgInvalidProperty, "SsMethod"));
|
string.Format(ResUI.MsgInvalidProperty, ResUI.TbSecurity3));
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,44 +115,41 @@ public class NodeValidator
|
|||||||
|
|
||||||
if (item.GetNetwork() is nameof(ETransport.ws)
|
if (item.GetNetwork() is nameof(ETransport.ws)
|
||||||
&& item.EchConfigList.IsNullOrEmpty()
|
&& item.EchConfigList.IsNullOrEmpty()
|
||||||
&& item.GetAlpn()?.FirstOrDefault() == "h3")
|
&& item.GetAlpn()?.FirstOrDefault() is "h3" or "h2")
|
||||||
{
|
{
|
||||||
v.Warning(
|
v.Warning(
|
||||||
"WebSocket but ALPN is set to h3, the core may ignore the ALPN setting or cause unexpected issues.");
|
$"WebSocket but ALPN is set to {item.Alpn}, the core may ignore the ALPN setting or cause unexpected issues.");
|
||||||
}
|
}
|
||||||
|
|
||||||
// TLS & Security
|
// TLS & Security
|
||||||
if (item.StreamSecurity == Global.StreamSecurity)
|
if (item.StreamSecurity == Global.StreamSecurity)
|
||||||
{
|
{
|
||||||
if (!item.Cert.IsNullOrEmpty() && CertPemManager.ParsePemChain(item.Cert).Count == 0 &&
|
var isCertProvided = !item.Cert.IsNullOrEmpty();
|
||||||
!item.CertSha.IsNullOrEmpty())
|
if (!item.Cert.IsNullOrEmpty() && CertPemManager.ParsePemChain(item.Cert).Count == 0)
|
||||||
{
|
{
|
||||||
v.Error(string.Format(ResUI.MsgInvalidProperty, "TLS Certificate"));
|
v.Error(string.Format(ResUI.MsgInvalidProperty, ResUI.TbFullCertTips));
|
||||||
}
|
isCertProvided = false;
|
||||||
|
|
||||||
// Check for deprecated allowInsecure property when TLS is enabled
|
|
||||||
if (item.GetAllowInsecure()
|
|
||||||
&& item.Cert.IsNullOrEmpty()
|
|
||||||
&& item.CertSha.IsNullOrEmpty())
|
|
||||||
{
|
|
||||||
v.Warning(ResUI.MsgAllowInsecureDeprecated);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((coreType == ECoreType.Xray
|
if ((coreType == ECoreType.Xray
|
||||||
&& item.GetAllowInsecure()
|
&& item.GetAllowInsecure()
|
||||||
&& item.Cert.IsNullOrEmpty()
|
&& !isCertProvided
|
||||||
&& item.CertSha.IsNullOrEmpty())
|
&& item.CertSha.IsNullOrEmpty())
|
||||||
|| (coreType == ECoreType.sing_box
|
|| (coreType == ECoreType.sing_box
|
||||||
&& item.GetAllowInsecure()
|
&& item.GetAllowInsecure()
|
||||||
&& item.Cert.IsNullOrEmpty()))
|
&& !isCertProvided))
|
||||||
{
|
{
|
||||||
v.Warning("Insecure configuration detected: AllowInsecure is enabled but no certificate is provided. This may cause MITM attacks.");
|
if (coreType == ECoreType.Xray)
|
||||||
|
{
|
||||||
|
v.Warning(ResUI.MsgAllowInsecureDeprecated);
|
||||||
|
}
|
||||||
|
v.Warning(ResUI.MsgInsecureConfiguration);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (item.StreamSecurity == Global.StreamSecurityReality)
|
if (item.StreamSecurity == Global.StreamSecurityReality)
|
||||||
{
|
{
|
||||||
v.Assert(!item.PublicKey.IsNullOrEmpty(), string.Format(ResUI.MsgInvalidProperty, "PublicKey"));
|
v.Assert(!item.PublicKey.IsNullOrEmpty(), string.Format(ResUI.MsgInvalidProperty, ResUI.TbPublicKey));
|
||||||
}
|
}
|
||||||
|
|
||||||
var transport = item.GetTransportExtra();
|
var transport = item.GetTransportExtra();
|
||||||
@@ -151,7 +157,7 @@ public class NodeValidator
|
|||||||
{
|
{
|
||||||
if (JsonUtils.ParseJson(transport.XhttpExtra) is not JsonObject)
|
if (JsonUtils.ParseJson(transport.XhttpExtra) is not JsonObject)
|
||||||
{
|
{
|
||||||
v.Error(string.Format(ResUI.MsgInvalidProperty, "XHTTP Extra"));
|
v.Error(string.Format(ResUI.MsgInvalidProperty, ResUI.TransportExtra));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,7 +165,7 @@ public class NodeValidator
|
|||||||
{
|
{
|
||||||
if (JsonUtils.ParseJson(item.Finalmask) is not JsonObject)
|
if (JsonUtils.ParseJson(item.Finalmask) is not JsonObject)
|
||||||
{
|
{
|
||||||
v.Error(string.Format(ResUI.MsgInvalidProperty, "Finalmask"));
|
v.Error(string.Format(ResUI.MsgInvalidProperty, ResUI.TbFinalmask));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,14 +5,14 @@ public static class ConnectionHandler
|
|||||||
private static readonly string _tag = "ConnectionHandler";
|
private static readonly string _tag = "ConnectionHandler";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Runs ping and IP checks and returns a formatted result string.
|
/// Runs ping and IP checks.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static async Task<string> RunAvailabilityCheck()
|
public static async Task<AvailabilityCheckResult> RunAvailabilityCheck()
|
||||||
{
|
{
|
||||||
var time = await GetRealPingTimeInfo();
|
var time = await GetRealPingTimeInfo();
|
||||||
var ip = time > 0 ? await GetIPInfo() : Global.None;
|
var ip = time > 0 ? await GetIPInfo() : Global.None;
|
||||||
|
|
||||||
return string.Format(ResUI.TestMeOutput, time, ip);
|
return new AvailabilityCheckResult(time, ip);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -20,9 +20,12 @@ public static class ConnectionHandler
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
private static async Task<string?> GetIPInfo()
|
private static async Task<string?> GetIPInfo()
|
||||||
{
|
{
|
||||||
var webProxy = await GetWebProxy();
|
using var downloadHandle = new DownloadService
|
||||||
|
{
|
||||||
var ipInfo = await GetIPInfo(webProxy);
|
Handler = HttpClientHelper.CreateSocketsHttpHandler(true, new()),
|
||||||
|
DisposeHandler = true,
|
||||||
|
};
|
||||||
|
var ipInfo = await GetIPInfo(downloadHandle);
|
||||||
return ipInfo?.ToString() ?? Global.None;
|
return ipInfo?.ToString() ?? Global.None;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,11 +37,9 @@ public static class ConnectionHandler
|
|||||||
var responseTime = -1;
|
var responseTime = -1;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var webProxy = await GetWebProxy();
|
|
||||||
|
|
||||||
for (var i = 0; i < 2; i++)
|
for (var i = 0; i < 2; i++)
|
||||||
{
|
{
|
||||||
responseTime = await GetRealPingTime(webProxy, 10);
|
responseTime = await GetRealPingTime(true);
|
||||||
if (responseTime > 0)
|
if (responseTime > 0)
|
||||||
{
|
{
|
||||||
break;
|
break;
|
||||||
@@ -54,64 +55,72 @@ public static class ConnectionHandler
|
|||||||
return responseTime;
|
return responseTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Creates local SOCKS proxy instance.
|
|
||||||
/// </summary>
|
|
||||||
private static async Task<WebProxy?> GetWebProxy()
|
|
||||||
{
|
|
||||||
var port = AppManager.Instance.GetLocalPort(EInboundProtocol.socks);
|
|
||||||
return new WebProxy($"socks5://{Global.Loopback}:{port}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Measures response time by sending HTTP requests through proxy.
|
/// Measures response time by sending HTTP requests through proxy.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static async Task<int> GetRealPingTime(IWebProxy? webProxy, int downloadTimeout)
|
public static async Task<int> GetRealPingTime(bool useProxy, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
var url = AppManager.Instance.Config.SpeedTestItem.SpeedPingTestUrl;
|
|
||||||
var responseTime = -1;
|
var responseTime = -1;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var cts = new CancellationTokenSource();
|
using var client = HttpClientHelper.Instance.GetHttpClient(useProxy);
|
||||||
cts.CancelAfter(TimeSpan.FromSeconds(downloadTimeout));
|
responseTime = await GetRealPingTime(client, cancellationToken);
|
||||||
using var client = new HttpClient(new SocketsHttpHandler()
|
}
|
||||||
{
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
Proxy = webProxy,
|
{
|
||||||
UseProxy = webProxy != null
|
throw;
|
||||||
});
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Ignore
|
||||||
|
}
|
||||||
|
return responseTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<int> GetRealPingTime(HttpClient client, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var url = ConfigTextHandler.Config.SpeedTestItem.SpeedPingTestUrl;
|
||||||
|
var responseTime = -1;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var timeoutCts = new CancellationTokenSource();
|
||||||
|
timeoutCts.CancelAfter(Global.LocalFetch);
|
||||||
|
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
|
||||||
|
var linkedToken = linkedCts.Token;
|
||||||
|
|
||||||
List<int> oneTime = [];
|
List<int> oneTime = [];
|
||||||
for (var i = 0; i < 2; i++)
|
for (var i = 0; i < 2; i++)
|
||||||
{
|
{
|
||||||
var timer = Stopwatch.StartNew();
|
var timer = Stopwatch.StartNew();
|
||||||
await client.GetAsync(url, cts.Token).ConfigureAwait(false);
|
await client.GetAsync(url, linkedToken).ConfigureAwait(false);
|
||||||
timer.Stop();
|
timer.Stop();
|
||||||
oneTime.Add((int)timer.Elapsed.TotalMilliseconds);
|
oneTime.Add((int)timer.Elapsed.TotalMilliseconds);
|
||||||
await Task.Delay(100, cts.Token);
|
await Task.Delay(100, linkedToken);
|
||||||
}
|
}
|
||||||
responseTime = oneTime.Where(x => x > 0).OrderBy(x => x).FirstOrDefault();
|
responseTime = oneTime.Where(x => x > 0).OrderBy(x => x).FirstOrDefault();
|
||||||
}
|
}
|
||||||
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
|
// Ignore
|
||||||
}
|
}
|
||||||
return responseTime;
|
return responseTime;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
public static async Task<IpInfoResult?> GetIPInfo(DownloadService downloadHandle, CancellationToken cancellationToken = default)
|
||||||
/// Gets IP and country information through specified proxy.
|
|
||||||
/// </summary>
|
|
||||||
public static async Task<IpInfoResult?> GetIPInfo(IWebProxy? webProxy)
|
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var url = AppManager.Instance.Config.SpeedTestItem.IPAPIUrl;
|
var url = ConfigTextHandler.Config.SpeedTestItem.IPAPIUrl;
|
||||||
if (url.IsNullOrEmpty())
|
if (url.IsNullOrEmpty())
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var downloadHandle = new DownloadService();
|
var result = await downloadHandle.TryDownloadString(url, cancellationToken);
|
||||||
var result = await downloadHandle.TryDownloadString(url, webProxy, "");
|
|
||||||
if (result == null)
|
if (result == null)
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
@@ -128,6 +137,10 @@ public static class ConnectionHandler
|
|||||||
|
|
||||||
return new IpInfoResult(country, ip);
|
return new IpInfoResult(country, ip);
|
||||||
}
|
}
|
||||||
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
throw;
|
||||||
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ public static class CoreConfigHandler
|
|||||||
|
|
||||||
public static async Task<RetResult> GenerateClientConfig(CoreConfigContext context, string? fileName)
|
public static async Task<RetResult> GenerateClientConfig(CoreConfigContext context, string? fileName)
|
||||||
{
|
{
|
||||||
var config = AppManager.Instance.Config;
|
var config = ConfigTextHandler.Config;
|
||||||
var result = new RetResult();
|
var result = new RetResult();
|
||||||
var node = context.Node;
|
var node = context.Node;
|
||||||
|
|
||||||
@@ -17,7 +17,7 @@ public static class CoreConfigHandler
|
|||||||
{
|
{
|
||||||
result = node.CoreType switch
|
result = node.CoreType switch
|
||||||
{
|
{
|
||||||
ECoreType.mihomo => await new CoreConfigClashService(config).GenerateClientCustomConfig(node, fileName),
|
ECoreType.mihomo => await new CoreConfigClashService(config, context.IsTunEnabled).GenerateClientCustomConfig(node, fileName),
|
||||||
_ => await GenerateClientCustomConfig(node, fileName)
|
_ => await GenerateClientCustomConfig(node, fileName)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -65,7 +65,9 @@ public static class CoreConfigHandler
|
|||||||
}
|
}
|
||||||
if (!File.Exists(addressFileName))
|
if (!File.Exists(addressFileName))
|
||||||
{
|
{
|
||||||
ret.Msg = ResUI.FailedGenDefaultConfiguration;
|
var message = $"{ResUI.FailedReadConfiguration}: {addressFileName}";
|
||||||
|
Logging.SaveLog($"{_tag}: {message}");
|
||||||
|
ret.Msg = message;
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
File.Copy(addressFileName, fileName);
|
File.Copy(addressFileName, fileName);
|
||||||
@@ -74,7 +76,9 @@ public static class CoreConfigHandler
|
|||||||
//check again
|
//check again
|
||||||
if (!File.Exists(fileName))
|
if (!File.Exists(fileName))
|
||||||
{
|
{
|
||||||
ret.Msg = ResUI.FailedGenDefaultConfiguration;
|
var message = $"{ResUI.FailedReadConfiguration}: {fileName}";
|
||||||
|
Logging.SaveLog($"{_tag}: {message}");
|
||||||
|
ret.Msg = message;
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+870
-588
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user