mirror of
https://github.com/EasyTier/EasyTier.git
synced 2026-10-30 08:05:42 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf0b2bcce8 | ||
|
|
3832020d50 | ||
|
|
ee9b51ff8a | ||
|
|
ed8df2d58f | ||
|
|
f66010e6f9 | ||
|
|
d5c4700d32 | ||
|
|
969ecfc4ca | ||
|
|
8f862997eb |
Generated
+39
-22
@@ -2273,6 +2273,7 @@ dependencies = [
|
||||
"gethostname 0.5.0",
|
||||
"git-version",
|
||||
"globwalk",
|
||||
"guarden",
|
||||
"hickory-client",
|
||||
"hickory-proto",
|
||||
"hickory-resolver",
|
||||
@@ -2456,6 +2457,7 @@ dependencies = [
|
||||
"dashmap",
|
||||
"easytier",
|
||||
"futures",
|
||||
"guarden",
|
||||
"jsonwebtoken",
|
||||
"mimalloc",
|
||||
"mockall",
|
||||
@@ -3590,6 +3592,28 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "guarden"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca87812d87fa82896df1adfb5c111cdeaae3edb6da028f5df002dcbd7df71454"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"guarden-macros",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "guarden-macros"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8b42f4b8de91cbd793ce8e6cf8d4821ef02d2d5b4468e0a55a36c65c5581de53"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "h2"
|
||||
version = "0.4.7"
|
||||
@@ -3705,12 +3729,6 @@ version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.2"
|
||||
@@ -4026,7 +4044,7 @@ dependencies = [
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2 0.6.1",
|
||||
"socket2 0.5.10",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -4695,9 +4713,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.172"
|
||||
version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libdbus-sys"
|
||||
@@ -5043,14 +5061,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.0.2"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec"
|
||||
checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
|
||||
dependencies = [
|
||||
"hermit-abi 0.3.9",
|
||||
"libc",
|
||||
"wasi 0.11.0+wasi-snapshot-preview1",
|
||||
"windows-sys 0.52.0",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6551,7 +6568,7 @@ checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"concurrent-queue",
|
||||
"hermit-abi 0.5.2",
|
||||
"hermit-abi",
|
||||
"pin-project-lite",
|
||||
"rustix 1.0.7",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -8650,12 +8667,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.1"
|
||||
version = "0.6.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881"
|
||||
checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9774,9 +9791,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.48.0"
|
||||
version = "1.52.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408"
|
||||
checksum = "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
@@ -9784,7 +9801,7 @@ dependencies = [
|
||||
"parking_lot",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2 0.6.1",
|
||||
"socket2 0.6.3",
|
||||
"tokio-macros",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
@@ -9792,9 +9809,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tokio-macros"
|
||||
version = "2.6.0"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"
|
||||
checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
||||
@@ -12,6 +12,7 @@ serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
guarden = "0.1"
|
||||
|
||||
# Axum web framework
|
||||
axum = { version = "0.8.4", features = ["macros"] }
|
||||
|
||||
@@ -10,9 +10,9 @@ use easytier::{
|
||||
common::config::{
|
||||
ConfigFileControl, ConfigLoader, NetworkIdentity, PeerConfig, TomlConfigLoader,
|
||||
},
|
||||
defer,
|
||||
instance_manager::NetworkInstanceManager,
|
||||
};
|
||||
use guarden::defer;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::any;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Tauri + Vue + TS</title>
|
||||
</head>
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
"private": true,
|
||||
"packageManager": "pnpm@9.12.1+sha512.e5a7e52a4183a02d5931057f7a0dbff9d5e9ce3161e33fa68ae392125b79282a8a8a470a51dfc8a0ed86221442eb2fb57019b0990ed24fab519bf0e1bc5ccfc4",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"build:deps": "pnpm --filter tauri-plugin-vpnservice-api build && pnpm --filter easytier-frontend-lib build",
|
||||
"dev": "pnpm run build:deps && vite",
|
||||
"build": "pnpm run build:deps && vue-tsc --noEmit && vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri",
|
||||
"lint": "eslint . --ignore-pattern src-tauri",
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface ServiceMode extends WebClientConfig {
|
||||
rpc_portal: string
|
||||
file_log_level: 'off' | 'warn' | 'info' | 'debug' | 'trace'
|
||||
file_log_dir: string
|
||||
installed_core_version?: string
|
||||
}
|
||||
|
||||
export interface RemoteMode {
|
||||
|
||||
@@ -16,7 +16,7 @@ import { useToast, useConfirm } from 'primevue'
|
||||
import { loadMode, saveMode, WebClientConfig, type Mode } from '~/composables/mode'
|
||||
import { saveLastNetworkInstanceId, loadLastNetworkInstanceId } from '~/composables/config'
|
||||
import ModeSwitcher from '~/components/ModeSwitcher.vue'
|
||||
import { getServiceStatus } from '~/composables/backend'
|
||||
import { getEasytierVersion, getServiceStatus } from '~/composables/backend'
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const confirm = useConfirm()
|
||||
@@ -85,6 +85,20 @@ async function onUninstallService() {
|
||||
});
|
||||
}
|
||||
|
||||
function stripModeMetadata(mode: Mode) {
|
||||
if (mode.mode !== 'service') {
|
||||
return mode
|
||||
}
|
||||
|
||||
const serviceConfig = { ...mode }
|
||||
delete serviceConfig.installed_core_version
|
||||
return serviceConfig
|
||||
}
|
||||
|
||||
function modeConfigChanged(next: Mode) {
|
||||
return JSON.stringify(stripModeMetadata(next)) !== JSON.stringify(stripModeMetadata(currentMode.value))
|
||||
}
|
||||
|
||||
async function onStopService() {
|
||||
isModeSaving.value = true
|
||||
manualDisconnect.value = true
|
||||
@@ -134,13 +148,14 @@ async function initWithMode(mode: Mode) {
|
||||
}
|
||||
url = mode.remote_rpc_address
|
||||
break;
|
||||
case 'service':
|
||||
case 'service': {
|
||||
if (!mode.config_dir || !mode.file_log_dir || !mode.file_log_level || !mode.rpc_portal) {
|
||||
toast.add({ severity: 'error', summary: t('error'), detail: t('mode.service_config_empty'), life: 10000 })
|
||||
return initWithMode({ ...mode, mode: 'normal' });
|
||||
}
|
||||
let serviceStatus = await getServiceStatus()
|
||||
if (serviceStatus === "NotInstalled" || JSON.stringify(mode) !== JSON.stringify(currentMode.value)) {
|
||||
const coreVersion = await getEasytierVersion()
|
||||
if (serviceStatus === "NotInstalled" || modeConfigChanged(mode) || mode.installed_core_version !== coreVersion) {
|
||||
mode.config_server_url = mode.config_server_url || undefined
|
||||
await initService({
|
||||
config_dir: mode.config_dir,
|
||||
@@ -149,6 +164,7 @@ async function initWithMode(mode: Mode) {
|
||||
rpc_portal: mode.rpc_portal,
|
||||
config_server: mode.config_server_url,
|
||||
})
|
||||
mode.installed_core_version = coreVersion
|
||||
serviceStatus = await getServiceStatus()
|
||||
}
|
||||
if (serviceStatus === "Stopped") {
|
||||
@@ -157,6 +173,7 @@ async function initWithMode(mode: Mode) {
|
||||
url = "tcp://" + mode.rpc_portal.replace("0.0.0.0", "127.0.0.1")
|
||||
retrys = 5
|
||||
break;
|
||||
}
|
||||
case 'normal':
|
||||
url = mode.rpc_portal;
|
||||
break;
|
||||
|
||||
@@ -33,6 +33,7 @@ const host = process.env.TAURI_DEV_HOST
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig(async () => ({
|
||||
base: './',
|
||||
resolve: {
|
||||
alias: {
|
||||
'~/': `${path.resolve(__dirname, 'src')}/`,
|
||||
|
||||
@@ -5,7 +5,7 @@ edition.workspace = true
|
||||
description = "Config server for easytier. easytier-core gets config from this and web frontend use it as restful api server."
|
||||
|
||||
[dependencies]
|
||||
easytier = { path = "../easytier" }
|
||||
easytier = { path = "../easytier", default-features = false, features = ["websocket"] }
|
||||
tracing = { version = "0.1", features = ["log"] }
|
||||
anyhow = { version = "1.0" }
|
||||
thiserror = "1.0"
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc -b && vite build",
|
||||
"test": "vitest run",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -43,10 +44,11 @@
|
||||
"typescript": "~5.6.3",
|
||||
"vite": "^5.4.21",
|
||||
"vite-plugin-dts": "^4.3.0",
|
||||
"vitest": "^2.1.9",
|
||||
"vue-tsc": "^2.1.10"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"vue": "^3.5.12",
|
||||
"primevue": "^4.3.9"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import InputGroup from 'primevue/inputgroup'
|
||||
import InputGroupAddon from 'primevue/inputgroupaddon'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { buildUrlInputValue, getHostInputValue, parseHostInputOnBlur, parseUrlInput } from '../modules/url-input'
|
||||
|
||||
const props = defineProps<{
|
||||
placeholder?: string
|
||||
@@ -32,73 +33,11 @@ onMounted(() => {
|
||||
}
|
||||
})
|
||||
|
||||
const parseUrl = (val: string | null | undefined): { proto: string; host: string; port: number | null } => {
|
||||
const getValidPort = (portStr: string, proto: string) => {
|
||||
const p = parseInt(portStr)
|
||||
return isNaN(p) ? (props.protos[proto] ?? 11010) : p
|
||||
}
|
||||
const parseByPattern = (input: string) => {
|
||||
const trimmed = input.trim()
|
||||
if (!trimmed) {
|
||||
return null
|
||||
}
|
||||
const match = trimmed.match(/^(\w+):\/\/(.*)$/)
|
||||
const proto = match ? match[1] : 'tcp'
|
||||
const rest = match ? match[2] : trimmed
|
||||
const authority = rest.split(/[/?#]/)[0]
|
||||
if (!authority) {
|
||||
return null
|
||||
}
|
||||
const hostAndMaybePort = authority.includes('@') ? authority.slice(authority.lastIndexOf('@') + 1) : authority
|
||||
if (hostAndMaybePort.startsWith('[')) {
|
||||
const ipv6End = hostAndMaybePort.indexOf(']')
|
||||
if (ipv6End > 0) {
|
||||
const host = hostAndMaybePort.slice(0, ipv6End + 1)
|
||||
const remain = hostAndMaybePort.slice(ipv6End + 1)
|
||||
// null = no explicit port in URL; do not fabricate a default
|
||||
const port: number | null = remain.startsWith(':') ? getValidPort(remain.slice(1), proto) : null
|
||||
return { proto, host, port }
|
||||
}
|
||||
}
|
||||
const portMatch = hostAndMaybePort.match(/^(.*):(\d+)$/)
|
||||
const host = portMatch ? portMatch[1] : hostAndMaybePort
|
||||
// null = no explicit port in URL; buildUrlValue will omit the port entirely,
|
||||
// preserving the protocol's implied standard port (e.g. 443 for wss://).
|
||||
const port: number | null = portMatch ? parseInt(portMatch[2]) : null
|
||||
return { proto, host, port }
|
||||
}
|
||||
|
||||
if (!val) {
|
||||
return { proto: 'tcp', host: '', port: props.protos['tcp'] ?? 11010 }
|
||||
}
|
||||
const parsedByPattern = parseByPattern(val)
|
||||
if (parsedByPattern) {
|
||||
return parsedByPattern
|
||||
}
|
||||
return { proto: 'tcp', host: '', port: null }
|
||||
}
|
||||
|
||||
const internalValue = ref(parseUrl(url.value))
|
||||
const internalValue = ref(parseUrlInput(url.value, props.protos))
|
||||
const defaultHost = '0.0.0.0'
|
||||
|
||||
const buildUrlValue = (value: { proto: string, host: string, port: number | null }, forceDefaultHost = false) => {
|
||||
const proto = value.proto || 'tcp'
|
||||
const rawHost = (value.host ?? '').trim()
|
||||
const host = rawHost || (forceDefaultHost ? defaultHost : '')
|
||||
if (!host) {
|
||||
return null
|
||||
}
|
||||
// Omit port when the protocol uses no port (protos value = 0), or when the
|
||||
// original URL had no explicit port (port === null) – avoids overwriting an
|
||||
// implicit standard port (e.g. 443 for wss) with an EasyTier default (11012).
|
||||
if (props.protos[proto] === 0 || value.port === null) {
|
||||
return `${proto}://${host}`
|
||||
}
|
||||
return `${proto}://${host}:${value.port}`
|
||||
}
|
||||
|
||||
const syncUrlFromInternal = (forceDefaultHost = false) => {
|
||||
const nextUrl = buildUrlValue(internalValue.value, forceDefaultHost)
|
||||
const nextUrl = buildUrlInputValue(internalValue.value, props.protos, forceDefaultHost)
|
||||
if (!nextUrl || nextUrl === url.value) {
|
||||
return
|
||||
}
|
||||
@@ -107,6 +46,10 @@ const syncUrlFromInternal = (forceDefaultHost = false) => {
|
||||
|
||||
const onHostBlur = () => {
|
||||
hostFocused.value = false
|
||||
const parsedHost = parseHostInputOnBlur(internalValue.value.host ?? '', internalValue.value.proto, props.protos)
|
||||
if (parsedHost) {
|
||||
internalValue.value = parsedHost
|
||||
}
|
||||
syncUrlFromInternal(true)
|
||||
}
|
||||
|
||||
@@ -123,12 +66,20 @@ const isNoPortProto = computed(() => {
|
||||
return props.protos[internalValue.value.proto] === 0
|
||||
})
|
||||
|
||||
const hostInputValue = computed({
|
||||
get: () => getHostInputValue(internalValue.value),
|
||||
set: (value: string) => {
|
||||
internalValue.value.host = value
|
||||
internalValue.value.suffix = undefined
|
||||
},
|
||||
})
|
||||
|
||||
// Sync from external
|
||||
watch(() => url.value, (newVal) => {
|
||||
if (hostFocused.value) {
|
||||
return
|
||||
}
|
||||
const parsed = parseUrl(newVal)
|
||||
const parsed = parseUrlInput(newVal, props.protos)
|
||||
const internalHost = internalValue.value.host ?? ''
|
||||
const sameHost = parsed.host === internalHost || (!internalHost.trim() && parsed.host === defaultHost)
|
||||
if (parsed.proto !== internalValue.value.proto ||
|
||||
@@ -140,6 +91,9 @@ watch(() => url.value, (newVal) => {
|
||||
|
||||
// Sync to external
|
||||
watch(internalValue, () => {
|
||||
if (hostFocused.value) {
|
||||
return
|
||||
}
|
||||
syncUrlFromInternal(false)
|
||||
}, { deep: true })
|
||||
|
||||
@@ -165,6 +119,8 @@ const onProtoChange = (newProto: string) => {
|
||||
internalValue.value.port = newDefault
|
||||
}
|
||||
internalValue.value.proto = newProto
|
||||
internalValue.value.suffix = undefined
|
||||
internalValue.value.hasExplicitPort = true
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -174,7 +130,7 @@ const onProtoChange = (newProto: string) => {
|
||||
<AutoComplete :model-value="internalValue.proto" :suggestions="filteredProtos" dropdown
|
||||
class="max-w-32 proto-autocomplete-in-group" @complete="searchProtos"
|
||||
@update:model-value="onProtoChange" />
|
||||
<InputText v-model="internalValue.host" :placeholder="placeholder || '0.0.0.0'" class="grow"
|
||||
<InputText v-model="hostInputValue" :placeholder="placeholder || '0.0.0.0'" class="grow"
|
||||
@focus="onHostFocus" @blur="onHostBlur" />
|
||||
<template v-if="!isNoPortProto">
|
||||
<InputGroupAddon>
|
||||
@@ -204,7 +160,7 @@ const onProtoChange = (newProto: string) => {
|
||||
</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
<label>{{ t('web.common.address') || 'Address' }}</label>
|
||||
<InputText v-model="internalValue.host" :placeholder="placeholder || '0.0.0.0'" class="w-full"
|
||||
<InputText v-model="hostInputValue" :placeholder="placeholder || '0.0.0.0'" class="w-full"
|
||||
@focus="onHostFocus" @blur="onHostBlur" />
|
||||
</div>
|
||||
<div v-if="!isNoPortProto" class="flex flex-col gap-2">
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildUrlInputValue, getHostInputValue, parseHostInputOnBlur, parseUrlInput, type ProtoPorts } from './url-input'
|
||||
|
||||
const protos: ProtoPorts = {
|
||||
tcp: 11010,
|
||||
udp: 11010,
|
||||
wg: 11011,
|
||||
ws: 11011,
|
||||
wss: 11012,
|
||||
quic: 11012,
|
||||
faketcp: 11013,
|
||||
http: 80,
|
||||
https: 443,
|
||||
txt: 0,
|
||||
srv: 0,
|
||||
}
|
||||
|
||||
function normalizeUrl(input: string, defaultProto = 'tcp') {
|
||||
return buildUrlInputValue(parseUrlInput(input, protos, defaultProto), protos, true)
|
||||
}
|
||||
|
||||
describe('parseUrlInput', () => {
|
||||
it.each([
|
||||
['https://raw.githubusercontent.com/aaa/bb/cc.txt', {
|
||||
proto: 'https',
|
||||
host: 'raw.githubusercontent.com',
|
||||
port: null,
|
||||
suffix: '/aaa/bb/cc.txt',
|
||||
hasExplicitPort: false,
|
||||
}],
|
||||
['https://host:4443/path?x=1#hash', {
|
||||
proto: 'https',
|
||||
host: 'host',
|
||||
port: 4443,
|
||||
suffix: '/path?x=1#hash',
|
||||
hasExplicitPort: true,
|
||||
}],
|
||||
['[::1]:11010/path', {
|
||||
proto: 'tcp',
|
||||
host: '[::1]',
|
||||
port: 11010,
|
||||
suffix: '/path',
|
||||
hasExplicitPort: true,
|
||||
}],
|
||||
[' http://host/path ', {
|
||||
proto: 'http',
|
||||
host: 'host',
|
||||
port: null,
|
||||
suffix: '/path',
|
||||
hasExplicitPort: false,
|
||||
}],
|
||||
])('parses %s', (input, expected) => {
|
||||
expect(parseUrlInput(input, protos)).toEqual(expected)
|
||||
})
|
||||
|
||||
it('parses IPv6 host without an explicit port', () => {
|
||||
expect(parseUrlInput('[::1]', protos)).toEqual({
|
||||
proto: 'tcp',
|
||||
host: '[::1]',
|
||||
port: null,
|
||||
suffix: '',
|
||||
hasExplicitPort: false,
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['host:', 'host'],
|
||||
['host:notaport', 'host'],
|
||||
])('falls back to the default port for invalid port input %s', (input, host) => {
|
||||
expect(parseUrlInput(input, protos)).toEqual({
|
||||
proto: 'tcp',
|
||||
host,
|
||||
port: 11010,
|
||||
suffix: '',
|
||||
hasExplicitPort: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the explicit proto for an input without authority', () => {
|
||||
expect(parseUrlInput('https://', protos)).toEqual({
|
||||
proto: 'https',
|
||||
host: '',
|
||||
port: null,
|
||||
suffix: '',
|
||||
hasExplicitPort: false,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildUrlInputValue', () => {
|
||||
it.each([
|
||||
['https://host', 'https://host'],
|
||||
['http://host', 'http://host'],
|
||||
['https://host:4443/path', 'https://host:4443/path'],
|
||||
['https://host:443/path', 'https://host:443/path'],
|
||||
['tcp://host', 'tcp://host'],
|
||||
['wss://host', 'wss://host'],
|
||||
['http://host/path?x=1#hash', 'http://host/path?x=1#hash'],
|
||||
['https://host?x=1', 'https://host?x=1'],
|
||||
['https://host#hash', 'https://host#hash'],
|
||||
['txt://example.com/path.txt', 'txt://example.com/path.txt'],
|
||||
['srv://_easytier._tcp.example.com', 'srv://_easytier._tcp.example.com'],
|
||||
['custom://host/path', 'custom://host/path'],
|
||||
])('normalizes %s to %s', (input, expected) => {
|
||||
expect(normalizeUrl(input)).toBe(expected)
|
||||
})
|
||||
|
||||
it('returns null for empty host unless default host is forced', () => {
|
||||
const parsed = parseUrlInput('', protos)
|
||||
|
||||
expect(buildUrlInputValue(parsed, protos, false)).toBeNull()
|
||||
expect(buildUrlInputValue(parsed, protos, true)).toBe('tcp://0.0.0.0:11010')
|
||||
})
|
||||
|
||||
it('does not build a broken URL for a protocol without authority', () => {
|
||||
const parsed = parseUrlInput('https://', protos)
|
||||
|
||||
expect(buildUrlInputValue(parsed, protos, false)).toBeNull()
|
||||
expect(buildUrlInputValue(parsed, protos, true)).toBe('https://0.0.0.0')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseHostInputOnBlur', () => {
|
||||
it('infers https for a pasted host:port/path when the current proto is tcp', () => {
|
||||
const parsed = parseHostInputOnBlur('raw.githubusercontent.com:4443/aaa/bb/cc.txt', 'tcp', protos)
|
||||
|
||||
expect(parsed).toEqual({
|
||||
proto: 'https',
|
||||
host: 'raw.githubusercontent.com',
|
||||
port: 4443,
|
||||
suffix: '/aaa/bb/cc.txt',
|
||||
hasExplicitPort: true,
|
||||
})
|
||||
expect(buildUrlInputValue(parsed!, protos, true)).toBe('https://raw.githubusercontent.com:4443/aaa/bb/cc.txt')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['raw.githubusercontent.com/aaa/bb/cc.txt', 'tcp', 'https://raw.githubusercontent.com/aaa/bb/cc.txt'],
|
||||
['raw.githubusercontent.com:4443/aaa/bb/cc.txt', 'https', 'https://raw.githubusercontent.com:4443/aaa/bb/cc.txt'],
|
||||
['https://raw.githubusercontent.com:4443/aaa/bb/cc.txt', 'tcp', 'https://raw.githubusercontent.com:4443/aaa/bb/cc.txt'],
|
||||
[' https://raw.githubusercontent.com/aaa/bb/cc.txt ', 'tcp', 'https://raw.githubusercontent.com/aaa/bb/cc.txt'],
|
||||
])('normalizes pasted host input %s with current proto %s', (input, currentProto, expected) => {
|
||||
const parsed = parseHostInputOnBlur(input, currentProto, protos)
|
||||
|
||||
expect(buildUrlInputValue(parsed!, protos, true)).toBe(expected)
|
||||
})
|
||||
|
||||
it('keeps ordinary host:port input on the current tcp protocol', () => {
|
||||
const parsed = parseHostInputOnBlur('example.com:11010', 'tcp', protos)
|
||||
|
||||
expect(buildUrlInputValue(parsed!, protos, true)).toBe('tcp://example.com:11010')
|
||||
})
|
||||
|
||||
it('returns null for a simple host without port or suffix', () => {
|
||||
expect(parseHostInputOnBlur('example.com', 'tcp', protos)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getHostInputValue', () => {
|
||||
it('shows host and suffix while keeping the port in the port field', () => {
|
||||
const parsed = parseUrlInput('https://raw.githubusercontent.com:4443/aaa/bb/cc.txt', protos)
|
||||
|
||||
expect(getHostInputValue(parsed)).toBe('raw.githubusercontent.com/aaa/bb/cc.txt')
|
||||
})
|
||||
|
||||
it('shows query and hash in the host input suffix', () => {
|
||||
const parsed = parseUrlInput('https://host/path?x=1#hash', protos)
|
||||
|
||||
expect(getHostInputValue(parsed)).toBe('host/path?x=1#hash')
|
||||
})
|
||||
})
|
||||
|
||||
describe('round trip scenarios', () => {
|
||||
it.each([
|
||||
['https://raw.githubusercontent.com/aaa/bb/cc.txt'],
|
||||
['https://raw.githubusercontent.com:4443/aaa/bb/cc.txt'],
|
||||
['http://host/path?x=1#hash'],
|
||||
['tcp://example.com:11010'],
|
||||
['txt://example.com/path.txt'],
|
||||
['srv://_easytier._tcp.example.com'],
|
||||
])('keeps %s stable after parse and build', (input) => {
|
||||
expect(normalizeUrl(input)).toBe(input)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,105 @@
|
||||
export interface UrlInputParts {
|
||||
proto: string
|
||||
host: string
|
||||
port: number | null
|
||||
suffix?: string
|
||||
hasExplicitPort?: boolean
|
||||
}
|
||||
|
||||
export type ProtoPorts = Record<string, number>
|
||||
|
||||
const fallbackProto = 'tcp'
|
||||
const fallbackPort = 11010
|
||||
const defaultHost = '0.0.0.0'
|
||||
|
||||
function defaultPortFor(protos: ProtoPorts, proto: string) {
|
||||
return protos[proto] ?? fallbackPort
|
||||
}
|
||||
|
||||
function getValidPort(portStr: string, protos: ProtoPorts, proto: string) {
|
||||
const p = parseInt(portStr)
|
||||
return isNaN(p) ? defaultPortFor(protos, proto) : p
|
||||
}
|
||||
|
||||
export function parseUrlInput(val: string | null | undefined, protos: ProtoPorts, defaultProto = fallbackProto): UrlInputParts {
|
||||
const parseByPattern = (input: string) => {
|
||||
const trimmed = input.trim()
|
||||
if (!trimmed) {
|
||||
return null
|
||||
}
|
||||
|
||||
const match = trimmed.match(/^(\w+):\/\/(.*)$/)
|
||||
const proto = match ? match[1] : defaultProto
|
||||
const rest = match ? match[2] : trimmed
|
||||
const suffixStart = rest.search(/[/?#]/)
|
||||
const authority = suffixStart >= 0 ? rest.slice(0, suffixStart) : rest
|
||||
const suffix = suffixStart >= 0 ? rest.slice(suffixStart) : ''
|
||||
if (!authority) {
|
||||
return { proto, host: '', port: null, suffix, hasExplicitPort: false }
|
||||
}
|
||||
|
||||
const hostAndMaybePort = authority.includes('@') ? authority.slice(authority.lastIndexOf('@') + 1) : authority
|
||||
if (hostAndMaybePort.startsWith('[')) {
|
||||
const ipv6End = hostAndMaybePort.indexOf(']')
|
||||
if (ipv6End > 0) {
|
||||
const host = hostAndMaybePort.slice(0, ipv6End + 1)
|
||||
const remain = hostAndMaybePort.slice(ipv6End + 1)
|
||||
const hasExplicitPort = remain.startsWith(':')
|
||||
const port = hasExplicitPort ? getValidPort(remain.slice(1), protos, proto) : null
|
||||
return { proto, host, port, suffix, hasExplicitPort }
|
||||
}
|
||||
}
|
||||
|
||||
const portMatch = hostAndMaybePort.match(/^(.*):(\d+)$/)
|
||||
if (portMatch) {
|
||||
return { proto, host: portMatch[1], port: parseInt(portMatch[2]), suffix, hasExplicitPort: true }
|
||||
}
|
||||
|
||||
const invalidPortMatch = hostAndMaybePort.match(/^([^:]+):[^:]*$/)
|
||||
const host = invalidPortMatch ? invalidPortMatch[1] : hostAndMaybePort
|
||||
const port = invalidPortMatch ? defaultPortFor(protos, proto) : null
|
||||
return { proto, host, port, suffix, hasExplicitPort: false }
|
||||
}
|
||||
|
||||
if (!val) {
|
||||
return { proto: defaultProto, host: '', port: defaultPortFor(protos, defaultProto) }
|
||||
}
|
||||
const parsedByPattern = parseByPattern(val)
|
||||
if (parsedByPattern) {
|
||||
return parsedByPattern
|
||||
}
|
||||
return { proto: defaultProto, host: '', port: defaultPortFor(protos, defaultProto) }
|
||||
}
|
||||
|
||||
export function buildUrlInputValue(value: UrlInputParts, protos: ProtoPorts, forceDefaultHost = false) {
|
||||
const proto = value.proto || fallbackProto
|
||||
const rawHost = (value.host ?? '').trim()
|
||||
const host = rawHost || (forceDefaultHost ? defaultHost : '')
|
||||
if (!host) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (protos[proto] === 0 || value.port === null) {
|
||||
return `${proto}://${host}${value.suffix ?? ''}`
|
||||
}
|
||||
|
||||
let port = value.port
|
||||
if (isNaN(parseInt(port as any))) {
|
||||
port = defaultPortFor(protos, proto)
|
||||
}
|
||||
|
||||
return `${proto}://${host}:${port}${value.suffix ?? ''}`
|
||||
}
|
||||
|
||||
export function parseHostInputOnBlur(rawHost: string, currentProto: string, protos: ProtoPorts) {
|
||||
const inferredProto = rawHost.includes('/') && currentProto === fallbackProto ? 'https' : currentProto
|
||||
const parsedHost = parseUrlInput(rawHost, protos, inferredProto)
|
||||
if (parsedHost.host && (parsedHost.proto !== currentProto || parsedHost.hasExplicitPort || parsedHost.suffix)) {
|
||||
return parsedHost
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function getHostInputValue(value: UrlInputParts) {
|
||||
return `${value.host ?? ''}${value.suffix ?? ''}`
|
||||
}
|
||||
@@ -4,8 +4,9 @@
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc -b && vite build",
|
||||
"build:deps": "pnpm --filter easytier-frontend-lib build",
|
||||
"dev": "pnpm run build:deps && vite",
|
||||
"build": "pnpm run build:deps && vue-tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -32,4 +33,4 @@
|
||||
"vite-plugin-singlefile": "^2.0.3",
|
||||
"vue-tsc": "^2.1.10"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,8 @@ time = "0.3"
|
||||
toml = "0.8.12"
|
||||
chrono = { version = "0.4.37", features = ["serde"] }
|
||||
|
||||
guarden = "0.1"
|
||||
|
||||
delegate = "0.13.5"
|
||||
|
||||
itertools = "0.14.0"
|
||||
|
||||
@@ -39,6 +39,15 @@ core_clap:
|
||||
ipv6:
|
||||
en: "ipv6 address of this vpn node, can be used together with ipv4 for dual-stack operation"
|
||||
zh-CN: "此VPN节点的IPv6地址,可与IPv4一起使用以进行双栈操作"
|
||||
ipv6_public_addr_provider:
|
||||
en: "share this node's public IPv6 subnet with other peers so they can obtain public IPv6 addresses (Linux only)"
|
||||
zh-CN: "将此节点的公网 IPv6 子网共享给其他节点,使它们也能获得公网 IPv6 地址(仅 Linux 支持)"
|
||||
ipv6_public_addr_auto:
|
||||
en: "auto-obtain a public IPv6 address from a peer that shares its IPv6 subnet"
|
||||
zh-CN: "自动从共享了 IPv6 子网的对等节点获取一个公网 IPv6 地址"
|
||||
ipv6_public_addr_prefix:
|
||||
en: "manually specify the public IPv6 subnet to share, instead of auto-detecting from system routes"
|
||||
zh-CN: "手动指定要共享的公网 IPv6 子网,不自动从系统路由检测"
|
||||
dhcp:
|
||||
en: "automatically determine and set IP address by Easytier, and the IP address starts from 10.0.0.1 by default. Warning, if there is an IP conflict in the network when using DHCP, the IP will be automatically changed."
|
||||
zh-CN: "由Easytier自动确定并设置IP地址,默认从10.0.0.1开始。警告:在使用DHCP时,如果网络中出现IP冲突,IP将自动更改。"
|
||||
|
||||
@@ -170,6 +170,15 @@ pub trait ConfigLoader: Send + Sync {
|
||||
fn get_ipv6(&self) -> Option<cidr::Ipv6Inet>;
|
||||
fn set_ipv6(&self, addr: Option<cidr::Ipv6Inet>);
|
||||
|
||||
fn get_ipv6_public_addr_provider(&self) -> bool;
|
||||
fn set_ipv6_public_addr_provider(&self, enabled: bool);
|
||||
|
||||
fn get_ipv6_public_addr_auto(&self) -> bool;
|
||||
fn set_ipv6_public_addr_auto(&self, enabled: bool);
|
||||
|
||||
fn get_ipv6_public_addr_prefix(&self) -> Option<cidr::Ipv6Cidr>;
|
||||
fn set_ipv6_public_addr_prefix(&self, prefix: Option<cidr::Ipv6Cidr>);
|
||||
|
||||
fn get_dhcp(&self) -> bool;
|
||||
fn set_dhcp(&self, dhcp: bool);
|
||||
|
||||
@@ -519,6 +528,9 @@ struct Config {
|
||||
instance_id: Option<uuid::Uuid>,
|
||||
ipv4: Option<String>,
|
||||
ipv6: Option<String>,
|
||||
ipv6_public_addr_provider: Option<bool>,
|
||||
ipv6_public_addr_auto: Option<bool>,
|
||||
ipv6_public_addr_prefix: Option<String>,
|
||||
dhcp: Option<bool>,
|
||||
network_identity: Option<NetworkIdentity>,
|
||||
listeners: Option<Vec<url::Url>>,
|
||||
@@ -700,6 +712,43 @@ impl ConfigLoader for TomlConfigLoader {
|
||||
self.config.lock().unwrap().ipv6 = addr.map(|addr| addr.to_string());
|
||||
}
|
||||
|
||||
fn get_ipv6_public_addr_provider(&self) -> bool {
|
||||
self.config
|
||||
.lock()
|
||||
.unwrap()
|
||||
.ipv6_public_addr_provider
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn set_ipv6_public_addr_provider(&self, enabled: bool) {
|
||||
self.config.lock().unwrap().ipv6_public_addr_provider = Some(enabled);
|
||||
}
|
||||
|
||||
fn get_ipv6_public_addr_auto(&self) -> bool {
|
||||
self.config
|
||||
.lock()
|
||||
.unwrap()
|
||||
.ipv6_public_addr_auto
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn set_ipv6_public_addr_auto(&self, enabled: bool) {
|
||||
self.config.lock().unwrap().ipv6_public_addr_auto = Some(enabled);
|
||||
}
|
||||
|
||||
fn get_ipv6_public_addr_prefix(&self) -> Option<cidr::Ipv6Cidr> {
|
||||
let locked_config = self.config.lock().unwrap();
|
||||
locked_config
|
||||
.ipv6_public_addr_prefix
|
||||
.as_ref()
|
||||
.and_then(|s| s.parse().ok())
|
||||
}
|
||||
|
||||
fn set_ipv6_public_addr_prefix(&self, prefix: Option<cidr::Ipv6Cidr>) {
|
||||
self.config.lock().unwrap().ipv6_public_addr_prefix =
|
||||
prefix.map(|prefix| prefix.to_string());
|
||||
}
|
||||
|
||||
fn get_dhcp(&self) -> bool {
|
||||
self.config.lock().unwrap().dhcp.unwrap_or_default()
|
||||
}
|
||||
@@ -1312,6 +1361,26 @@ source = "user"
|
||||
assert!(!explicit_user.dump().contains("[source]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ipv6_public_addr_config_roundtrip() {
|
||||
let config = TomlConfigLoader::default();
|
||||
let prefix: cidr::Ipv6Cidr = "2001:db8:100::/64".parse().unwrap();
|
||||
|
||||
config.set_ipv6_public_addr_provider(true);
|
||||
config.set_ipv6_public_addr_auto(true);
|
||||
config.set_ipv6_public_addr_prefix(Some(prefix));
|
||||
|
||||
assert!(config.get_ipv6_public_addr_provider());
|
||||
assert!(config.get_ipv6_public_addr_auto());
|
||||
assert_eq!(config.get_ipv6_public_addr_prefix(), Some(prefix));
|
||||
|
||||
let dumped = config.dump();
|
||||
let loaded = TomlConfigLoader::new_from_str(&dumped).unwrap();
|
||||
assert!(loaded.get_ipv6_public_addr_provider());
|
||||
assert!(loaded.get_ipv6_public_addr_auto());
|
||||
assert_eq!(loaded.get_ipv6_public_addr_prefix(), Some(prefix));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn full_example_test() {
|
||||
let config_str = r#"
|
||||
|
||||
@@ -121,9 +121,8 @@ pub async fn socket_addrs(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::defer;
|
||||
|
||||
use super::*;
|
||||
use guarden::defer;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_socket_addrs() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use std::{
|
||||
collections::{HashMap, hash_map::DefaultHasher},
|
||||
collections::{BTreeSet, HashMap, hash_map::DefaultHasher},
|
||||
hash::Hasher,
|
||||
net::{IpAddr, SocketAddr},
|
||||
sync::{Arc, Mutex},
|
||||
@@ -68,6 +68,8 @@ pub enum GlobalCtxEvent {
|
||||
|
||||
DhcpIpv4Changed(Option<cidr::Ipv4Inet>, Option<cidr::Ipv4Inet>), // (old, new)
|
||||
DhcpIpv4Conflicted(Option<cidr::Ipv4Inet>),
|
||||
PublicIpv6Changed(Option<cidr::Ipv6Inet>, Option<cidr::Ipv6Inet>), // (old, new)
|
||||
PublicIpv6RoutesUpdated(Vec<cidr::Ipv6Inet>, Vec<cidr::Ipv6Inet>), // (added, removed)
|
||||
|
||||
PortForwardAdded(PortForwardConfigPb),
|
||||
|
||||
@@ -200,6 +202,8 @@ pub struct GlobalCtx {
|
||||
|
||||
cached_ipv4: AtomicCell<Option<cidr::Ipv4Inet>>,
|
||||
cached_ipv6: AtomicCell<Option<cidr::Ipv6Inet>>,
|
||||
public_ipv6_lease: AtomicCell<Option<cidr::Ipv6Inet>>,
|
||||
public_ipv6_routes: Mutex<BTreeSet<std::net::Ipv6Addr>>,
|
||||
cached_proxy_cidrs: AtomicCell<Option<Vec<ProxyNetworkConfig>>>,
|
||||
|
||||
ip_collector: Mutex<Option<Arc<IPCollector>>>,
|
||||
@@ -209,6 +213,7 @@ pub struct GlobalCtx {
|
||||
stun_info_collection: Mutex<Arc<dyn StunInfoCollectorTrait>>,
|
||||
|
||||
running_listeners: Mutex<Vec<url::Url>>,
|
||||
advertised_ipv6_public_addr_prefix: Mutex<Option<cidr::Ipv6Cidr>>,
|
||||
|
||||
flags: ArcSwap<Flags>,
|
||||
|
||||
@@ -295,6 +300,8 @@ impl GlobalCtx {
|
||||
event_bus,
|
||||
cached_ipv4: AtomicCell::new(None),
|
||||
cached_ipv6: AtomicCell::new(None),
|
||||
public_ipv6_lease: AtomicCell::new(None),
|
||||
public_ipv6_routes: Mutex::new(BTreeSet::new()),
|
||||
cached_proxy_cidrs: AtomicCell::new(None),
|
||||
|
||||
ip_collector: Mutex::new(Some(Arc::new(IPCollector::new(
|
||||
@@ -307,6 +314,7 @@ impl GlobalCtx {
|
||||
stun_info_collection: Mutex::new(stun_info_collector),
|
||||
|
||||
running_listeners: Mutex::new(Vec::new()),
|
||||
advertised_ipv6_public_addr_prefix: Mutex::new(None),
|
||||
|
||||
flags: ArcSwap::new(Arc::new(flags)),
|
||||
|
||||
@@ -381,6 +389,45 @@ impl GlobalCtx {
|
||||
self.cached_ipv6.store(None);
|
||||
}
|
||||
|
||||
pub fn get_public_ipv6_lease(&self) -> Option<cidr::Ipv6Inet> {
|
||||
self.public_ipv6_lease.load()
|
||||
}
|
||||
|
||||
pub fn set_public_ipv6_lease(&self, addr: Option<cidr::Ipv6Inet>) {
|
||||
self.public_ipv6_lease.store(addr);
|
||||
}
|
||||
|
||||
pub fn set_public_ipv6_routes(&self, routes: BTreeSet<cidr::Ipv6Inet>) {
|
||||
*self.public_ipv6_routes.lock().unwrap() =
|
||||
routes.into_iter().map(|route| route.address()).collect();
|
||||
}
|
||||
|
||||
pub fn is_ip_local_ipv6(&self, ip: &std::net::Ipv6Addr) -> bool {
|
||||
self.get_ipv6().map(|x| x.address() == *ip).unwrap_or(false)
|
||||
|| self
|
||||
.get_public_ipv6_lease()
|
||||
.map(|x| x.address() == *ip)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn is_ip_easytier_managed_ipv6(&self, ip: &std::net::Ipv6Addr) -> bool {
|
||||
self.is_ip_local_ipv6(ip) || self.public_ipv6_routes.lock().unwrap().contains(ip)
|
||||
}
|
||||
|
||||
pub fn get_advertised_ipv6_public_addr_prefix(&self) -> Option<cidr::Ipv6Cidr> {
|
||||
*self.advertised_ipv6_public_addr_prefix.lock().unwrap()
|
||||
}
|
||||
|
||||
pub fn set_advertised_ipv6_public_addr_prefix(&self, prefix: Option<cidr::Ipv6Cidr>) -> bool {
|
||||
let mut guard = self.advertised_ipv6_public_addr_prefix.lock().unwrap();
|
||||
if *guard == prefix {
|
||||
return false;
|
||||
}
|
||||
|
||||
*guard = prefix;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn get_id(&self) -> uuid::Uuid {
|
||||
self.config.get_id()
|
||||
}
|
||||
@@ -395,7 +442,7 @@ impl GlobalCtx {
|
||||
pub fn is_ip_local_virtual_ip(&self, ip: &IpAddr) -> bool {
|
||||
match ip {
|
||||
IpAddr::V4(v4) => self.get_ipv4().map(|x| x.address() == *v4).unwrap_or(false),
|
||||
IpAddr::V6(v6) => self.get_ipv6().map(|x| x.address() == *v6).unwrap_or(false),
|
||||
IpAddr::V6(v6) => self.is_ip_local_ipv6(v6),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,23 +692,23 @@ impl GlobalCtx {
|
||||
pub fn should_deny_proxy(&self, dst_addr: &SocketAddr, is_udp: bool) -> bool {
|
||||
let _g = self.net_ns.guard();
|
||||
let ip = dst_addr.ip();
|
||||
// first check if ip is virtual ip
|
||||
// first check if ip is an EasyTier-managed local address
|
||||
// then try bind this ip, if succ means it is local ip
|
||||
let dst_is_local_virtual_ip = self.is_ip_local_virtual_ip(&ip);
|
||||
let dst_is_local_et_ip = self.is_ip_local_virtual_ip(&ip);
|
||||
// this is an expensive operation, should be called sparingly
|
||||
// 1. tcp/kcp/quic call this only after proxy conn is established
|
||||
// 2. udp cache the result in nat entry
|
||||
let dst_is_local_phy_ip = std::net::UdpSocket::bind(format!("{}:0", ip)).is_ok();
|
||||
|
||||
tracing::trace!(
|
||||
"check should_deny_proxy: dst_addr={}, dst_is_local_virtual_ip={}, dst_is_local_phy_ip={}, is_udp={}",
|
||||
"check should_deny_proxy: dst_addr={}, dst_is_local_et_ip={}, dst_is_local_phy_ip={}, is_udp={}",
|
||||
dst_addr,
|
||||
dst_is_local_virtual_ip,
|
||||
dst_is_local_et_ip,
|
||||
dst_is_local_phy_ip,
|
||||
is_udp
|
||||
);
|
||||
|
||||
if dst_is_local_virtual_ip || dst_is_local_phy_ip {
|
||||
if dst_is_local_et_ip || dst_is_local_phy_ip {
|
||||
// if is local ip, make sure the port is not one of the listening ports
|
||||
self.is_port_in_running_listeners(dst_addr.port(), is_udp)
|
||||
|| (!is_udp && protected_port::is_protected_tcp_port(dst_addr.port()))
|
||||
@@ -770,6 +817,7 @@ pub mod tests {
|
||||
assert!(feature_flags.support_conn_list_sync);
|
||||
assert!(feature_flags.avoid_relay_data);
|
||||
assert!(feature_flags.is_public_server);
|
||||
assert!(!feature_flags.ipv6_public_addr_provider);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -789,6 +837,40 @@ pub mod tests {
|
||||
protected_port::clear_protected_tcp_ports_for_test();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn virtual_ipv6_and_public_ipv6_lease_are_stored_separately() {
|
||||
let config = TomlConfigLoader::default();
|
||||
let global_ctx = GlobalCtx::new(config);
|
||||
let virtual_ipv6 = "fd00::1/64".parse().unwrap();
|
||||
let public_ipv6 = "2001:db8::2/64".parse().unwrap();
|
||||
|
||||
global_ctx.set_ipv6(Some(virtual_ipv6));
|
||||
global_ctx.set_public_ipv6_lease(Some(public_ipv6));
|
||||
|
||||
assert_eq!(global_ctx.get_ipv6(), Some(virtual_ipv6));
|
||||
assert_eq!(global_ctx.get_public_ipv6_lease(), Some(public_ipv6));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_ipv6_lease_is_treated_as_local_ip() {
|
||||
protected_port::clear_protected_tcp_ports_for_test();
|
||||
|
||||
let config = TomlConfigLoader::default();
|
||||
let global_ctx = GlobalCtx::new(config);
|
||||
let public_ipv6 = "2001:db8::2/64".parse().unwrap();
|
||||
let listener: url::Url = "tcp://[2001:db8::2]:11010".parse().unwrap();
|
||||
global_ctx.set_public_ipv6_lease(Some(public_ipv6));
|
||||
global_ctx.add_running_listener(listener);
|
||||
|
||||
let ip = std::net::IpAddr::V6(public_ipv6.address());
|
||||
let socket = SocketAddr::from((public_ipv6.address(), 11010));
|
||||
|
||||
assert!(global_ctx.is_ip_local_virtual_ip(&ip));
|
||||
assert!(global_ctx.should_deny_proxy(&socket, false));
|
||||
|
||||
protected_port::clear_protected_tcp_ports_for_test();
|
||||
}
|
||||
|
||||
pub fn get_mock_global_ctx_with_network(
|
||||
network_identy: Option<NetworkIdentity>,
|
||||
) -> ArcGlobalCtx {
|
||||
|
||||
@@ -166,3 +166,14 @@ pub type IfConfiger = DummyIfConfiger;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use windows::RegistryManager;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn list_ipv6_route_messages()
|
||||
-> Result<Vec<netlink_packet_route::route::RouteMessage>, Error> {
|
||||
netlink::NetlinkIfConfiger::list_ipv6_route_messages()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn get_interface_index(name: &str) -> Result<u32, Error> {
|
||||
netlink::NetlinkIfConfiger::get_interface_index(name)
|
||||
}
|
||||
|
||||
@@ -160,7 +160,7 @@ impl From<RouteMessage> for Route {
|
||||
pub struct NetlinkIfConfiger {}
|
||||
|
||||
impl NetlinkIfConfiger {
|
||||
fn get_interface_index(name: &str) -> Result<u32, Error> {
|
||||
pub(crate) fn get_interface_index(name: &str) -> Result<u32, Error> {
|
||||
let name = CString::new(name).with_context(|| "failed to convert interface name")?;
|
||||
match unsafe { libc::if_nametoindex(name.as_ptr()) } {
|
||||
0 => Err(std::io::Error::last_os_error().into()),
|
||||
@@ -311,7 +311,7 @@ impl NetlinkIfConfiger {
|
||||
Self::set_flags_op(name, SIOCGIFFLAGS, InterfaceFlags::empty())
|
||||
}
|
||||
|
||||
fn list_routes() -> Result<Vec<RouteMessage>, Error> {
|
||||
fn list_route_messages(address_family: AddressFamily) -> Result<Vec<RouteMessage>, Error> {
|
||||
let mut message = RouteMessage::default();
|
||||
|
||||
message.header.table = RouteHeader::RT_TABLE_UNSPEC;
|
||||
@@ -320,7 +320,7 @@ impl NetlinkIfConfiger {
|
||||
message.header.scope = RouteScope::Universe;
|
||||
message.header.kind = RouteType::Unicast;
|
||||
|
||||
message.header.address_family = AddressFamily::Inet;
|
||||
message.header.address_family = address_family;
|
||||
message.header.destination_prefix_length = 0;
|
||||
message.header.source_prefix_length = 0;
|
||||
|
||||
@@ -367,6 +367,14 @@ impl NetlinkIfConfiger {
|
||||
|
||||
Ok(ret_vec)
|
||||
}
|
||||
|
||||
fn list_routes() -> Result<Vec<RouteMessage>, Error> {
|
||||
Self::list_route_messages(AddressFamily::Inet)
|
||||
}
|
||||
|
||||
pub(crate) fn list_ipv6_route_messages() -> Result<Vec<RouteMessage>, Error> {
|
||||
Self::list_route_messages(AddressFamily::Inet6)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@@ -551,12 +559,9 @@ impl IfConfiguerTrait for NetlinkIfConfiger {
|
||||
message.header.scope = RouteScope::Universe;
|
||||
message.header.kind = RouteType::Unicast;
|
||||
|
||||
// Add metric (cost) if specified
|
||||
if let Some(cost) = cost {
|
||||
message
|
||||
.attributes
|
||||
.push(RouteAttribute::Priority(cost as u32));
|
||||
}
|
||||
message
|
||||
.attributes
|
||||
.push(RouteAttribute::Priority(cost.unwrap_or(65535) as u32));
|
||||
|
||||
message
|
||||
.attributes
|
||||
@@ -564,9 +569,11 @@ impl IfConfiguerTrait for NetlinkIfConfiger {
|
||||
name,
|
||||
)?));
|
||||
|
||||
message
|
||||
.attributes
|
||||
.push(RouteAttribute::Destination(RouteAddress::Inet6(address)));
|
||||
if cidr_prefix != 0 {
|
||||
message
|
||||
.attributes
|
||||
.push(RouteAttribute::Destination(RouteAddress::Inet6(address)));
|
||||
}
|
||||
|
||||
send_netlink_req_and_wait_one_resp(RouteNetlinkMessage::NewRoute(message), false)
|
||||
}
|
||||
@@ -577,7 +584,7 @@ impl IfConfiguerTrait for NetlinkIfConfiger {
|
||||
address: std::net::Ipv6Addr,
|
||||
cidr_prefix: u8,
|
||||
) -> Result<(), Error> {
|
||||
let routes = Self::list_routes()?;
|
||||
let routes = Self::list_route_messages(AddressFamily::Inet6)?;
|
||||
let ifidx = NetlinkIfConfiger::get_interface_index(name)?;
|
||||
|
||||
for msg in routes {
|
||||
@@ -598,29 +605,82 @@ impl IfConfiguerTrait for NetlinkIfConfiger {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
|
||||
const DUMMY_IFACE_NAME: &str = "dummy";
|
||||
|
||||
fn run_cmd(cmd: &str) -> String {
|
||||
let output = std::process::Command::new("sh")
|
||||
let output = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(cmd)
|
||||
.output()
|
||||
.expect("failed to execute process");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"command failed: {cmd}\nstdout: {}\nstderr: {}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap()
|
||||
}
|
||||
|
||||
fn run_ip(args: &[&str]) {
|
||||
let output = Command::new("ip")
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("failed to execute ip process");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"ip command failed: {:?}\nstdout: {}\nstderr: {}",
|
||||
args,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
}
|
||||
|
||||
fn test_iface_name(tag: &str) -> String {
|
||||
format!("et{}{:x}", tag, std::process::id() & 0xffff)
|
||||
}
|
||||
|
||||
struct ScopedDummyLink {
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl ScopedDummyLink {
|
||||
fn new(name: &str) -> Self {
|
||||
let _ = Command::new("ip").args(["link", "del", name]).output();
|
||||
run_ip(&["link", "add", name, "type", "dummy"]);
|
||||
run_ip(&["link", "set", name, "up"]);
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ScopedDummyLink {
|
||||
fn drop(&mut self) {
|
||||
let _ = Command::new("ip")
|
||||
.args(["link", "del", &self.name])
|
||||
.output();
|
||||
}
|
||||
}
|
||||
|
||||
struct PrepareEnv {}
|
||||
impl PrepareEnv {
|
||||
fn new() -> Self {
|
||||
let _ = run_cmd(&format!("sudo ip link add {} type dummy", DUMMY_IFACE_NAME));
|
||||
let _ = Command::new("ip")
|
||||
.args(["link", "del", DUMMY_IFACE_NAME])
|
||||
.output();
|
||||
let _ = run_cmd(&format!("ip link add {} type dummy", DUMMY_IFACE_NAME));
|
||||
PrepareEnv {}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PrepareEnv {
|
||||
fn drop(&mut self) {
|
||||
let _ = run_cmd(&format!("sudo ip link del {}", DUMMY_IFACE_NAME));
|
||||
let _ = Command::new("ip")
|
||||
.args(["link", "del", DUMMY_IFACE_NAME])
|
||||
.output();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -701,4 +761,128 @@ mod tests {
|
||||
.collect::<Vec<_>>();
|
||||
assert!(!routes.contains(&IpAddr::V4("10.5.5.0".parse().unwrap())));
|
||||
}
|
||||
|
||||
#[serial_test::serial]
|
||||
#[tokio::test]
|
||||
async fn ipv6_addr_readback_test() {
|
||||
let iface = test_iface_name("a");
|
||||
let _link = ScopedDummyLink::new(&iface);
|
||||
run_ip(&["-6", "addr", "add", "2001:db8:1234::2/64", "dev", &iface]);
|
||||
|
||||
let addrs = NetlinkIfConfiger::list_addresses(&iface).unwrap();
|
||||
assert!(addrs.iter().any(|addr| {
|
||||
addr.address() == IpAddr::V6("2001:db8:1234::2".parse().unwrap())
|
||||
&& addr.network_length() == 64
|
||||
}));
|
||||
}
|
||||
|
||||
#[serial_test::serial]
|
||||
#[tokio::test]
|
||||
async fn ipv6_route_readback_test() {
|
||||
let wan_if = test_iface_name("rw");
|
||||
let lan_if = test_iface_name("rl");
|
||||
let _wan = ScopedDummyLink::new(&wan_if);
|
||||
let _lan = ScopedDummyLink::new(&lan_if);
|
||||
run_ip(&[
|
||||
"-6",
|
||||
"addr",
|
||||
"add",
|
||||
"2001:db8:100:ffff::2/64",
|
||||
"dev",
|
||||
&wan_if,
|
||||
]);
|
||||
run_ip(&[
|
||||
"-6",
|
||||
"route",
|
||||
"add",
|
||||
"default",
|
||||
"from",
|
||||
"2001:db8:100::/56",
|
||||
"dev",
|
||||
&wan_if,
|
||||
]);
|
||||
run_ip(&["-6", "route", "add", "2001:db8:100::/56", "dev", &lan_if]);
|
||||
|
||||
let wan_ifindex = NetlinkIfConfiger::get_interface_index(&wan_if).unwrap();
|
||||
let lan_ifindex = NetlinkIfConfiger::get_interface_index(&lan_if).unwrap();
|
||||
let routes = NetlinkIfConfiger::list_ipv6_route_messages().unwrap();
|
||||
|
||||
assert!(routes.iter().any(|route| {
|
||||
route.header.kind == RouteType::Unicast
|
||||
&& route.header.source_prefix_length == 56
|
||||
&& route.attributes.iter().any(|attr| {
|
||||
matches!(
|
||||
attr,
|
||||
RouteAttribute::Source(RouteAddress::Inet6(addr))
|
||||
if *addr == "2001:db8:100::".parse::<std::net::Ipv6Addr>().unwrap()
|
||||
)
|
||||
})
|
||||
&& route
|
||||
.attributes
|
||||
.iter()
|
||||
.any(|attr| matches!(attr, RouteAttribute::Oif(index) if *index == wan_ifindex))
|
||||
&& !route
|
||||
.attributes
|
||||
.iter()
|
||||
.any(|attr| matches!(attr, RouteAttribute::Destination(_)))
|
||||
}));
|
||||
|
||||
assert!(routes.iter().any(|route| {
|
||||
route.header.kind == RouteType::Unicast
|
||||
&& route.header.destination_prefix_length == 56
|
||||
&& route.attributes.iter().any(|attr| {
|
||||
matches!(
|
||||
attr,
|
||||
RouteAttribute::Destination(RouteAddress::Inet6(addr))
|
||||
if *addr == "2001:db8:100::".parse::<std::net::Ipv6Addr>().unwrap()
|
||||
)
|
||||
})
|
||||
&& route
|
||||
.attributes
|
||||
.iter()
|
||||
.any(|attr| matches!(attr, RouteAttribute::Oif(index) if *index == lan_ifindex))
|
||||
}));
|
||||
}
|
||||
|
||||
#[serial_test::serial]
|
||||
#[tokio::test]
|
||||
async fn ipv6_route_remove_test() {
|
||||
let iface = test_iface_name("rr");
|
||||
let _link = ScopedDummyLink::new(&iface);
|
||||
let ifcfg = NetlinkIfConfiger {};
|
||||
let route_addr = "2001:db8:200::".parse::<std::net::Ipv6Addr>().unwrap();
|
||||
|
||||
ifcfg
|
||||
.add_ipv6_route(&iface, route_addr, 56, None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let ifindex = NetlinkIfConfiger::get_interface_index(&iface).unwrap();
|
||||
let has_route = |routes: &[RouteMessage]| {
|
||||
routes.iter().any(|route| {
|
||||
route.header.destination_prefix_length == 56
|
||||
&& route.attributes.iter().any(|attr| {
|
||||
matches!(
|
||||
attr,
|
||||
RouteAttribute::Destination(RouteAddress::Inet6(addr)) if *addr == route_addr
|
||||
)
|
||||
})
|
||||
&& route
|
||||
.attributes
|
||||
.iter()
|
||||
.any(|attr| matches!(attr, RouteAttribute::Oif(index) if *index == ifindex))
|
||||
})
|
||||
};
|
||||
|
||||
let routes = NetlinkIfConfiger::list_ipv6_route_messages().unwrap();
|
||||
assert!(has_route(&routes));
|
||||
|
||||
ifcfg
|
||||
.remove_ipv6_route(&iface, route_addr, 56)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let routes = NetlinkIfConfiger::list_ipv6_route_messages().unwrap();
|
||||
assert!(!has_route(&routes));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +64,24 @@ async fn resolve_mapped_listener_addrs(listener: &url::Url) -> Result<Vec<Socket
|
||||
socket_addrs(listener, || mapped_listener_port(listener)).await
|
||||
}
|
||||
|
||||
fn is_usable_public_ipv6_candidate(ip: &Ipv6Addr, global_ctx: &ArcGlobalCtx) -> bool {
|
||||
is_usable_public_ipv6_candidate_with_mode(ip, global_ctx, TESTING.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
fn is_usable_public_ipv6_candidate_with_mode(
|
||||
ip: &Ipv6Addr,
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
testing: bool,
|
||||
) -> bool {
|
||||
!global_ctx.is_ip_easytier_managed_ipv6(ip)
|
||||
&& (testing
|
||||
|| (!ip.is_loopback()
|
||||
&& !ip.is_unspecified()
|
||||
&& !ip.is_unique_local()
|
||||
&& !ip.is_unicast_link_local()
|
||||
&& !ip.is_multicast()))
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait PeerManagerForDirectConnector {
|
||||
async fn list_peers(&self) -> Vec<PeerId>;
|
||||
@@ -190,34 +208,28 @@ impl DirectConnectorManagerData {
|
||||
.with_context(|| format!("failed to bind local socket for {}", remote_url))?,
|
||||
);
|
||||
let connector_ip = self
|
||||
.peer_manager
|
||||
.get_global_ctx()
|
||||
.global_ctx
|
||||
.get_stun_info_collector()
|
||||
.get_stun_info()
|
||||
.public_ip
|
||||
.iter()
|
||||
.find(|x| x.contains(':'))
|
||||
.ok_or(anyhow::anyhow!(
|
||||
"failed to get public ipv6 address from stun info"
|
||||
))?
|
||||
.parse::<Ipv6Addr>()
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"failed to parse public ipv6 address from stun info: {:?}",
|
||||
self.peer_manager
|
||||
.get_global_ctx()
|
||||
.get_stun_info_collector()
|
||||
.get_stun_info()
|
||||
)
|
||||
})?;
|
||||
let connector_addr =
|
||||
SocketAddr::new(IpAddr::V6(connector_ip), local_socket.local_addr()?.port());
|
||||
.filter_map(|ip| ip.parse::<Ipv6Addr>().ok())
|
||||
.find(|ip| !self.global_ctx.is_ip_easytier_managed_ipv6(ip));
|
||||
|
||||
// ask remote to send v6 hole punch packet
|
||||
// and no matter what the result is, continue to connect
|
||||
let _ = self
|
||||
.remote_send_udp_hole_punch_packet(dst_peer_id, connector_addr, remote_url)
|
||||
.await;
|
||||
if let Some(connector_ip) = connector_ip {
|
||||
let connector_addr =
|
||||
SocketAddr::new(IpAddr::V6(connector_ip), local_socket.local_addr()?.port());
|
||||
let _ = self
|
||||
.remote_send_udp_hole_punch_packet(dst_peer_id, connector_addr, remote_url)
|
||||
.await;
|
||||
} else {
|
||||
tracing::debug!(
|
||||
?remote_url,
|
||||
"skip remote IPv6 hole-punch packet; no non-EasyTier public IPv6 in STUN info"
|
||||
);
|
||||
}
|
||||
|
||||
let udp_connector = UdpTunnelConnector::new(remote_url.clone());
|
||||
let remote_addr = SocketAddr::from_url(remote_url.clone(), IpVersion::V6).await?;
|
||||
@@ -479,14 +491,7 @@ impl DirectConnectorManagerData {
|
||||
.iter()
|
||||
.chain(ip_list.public_ipv6.iter())
|
||||
.filter_map(|x| Ipv6Addr::from_str(&x.to_string()).ok())
|
||||
.filter(|x| {
|
||||
TESTING.load(Ordering::Relaxed)
|
||||
|| (!x.is_loopback()
|
||||
&& !x.is_unspecified()
|
||||
&& !x.is_unique_local()
|
||||
&& !x.is_unicast_link_local()
|
||||
&& !x.is_multicast())
|
||||
})
|
||||
.filter(|x| is_usable_public_ipv6_candidate(x, &self.global_ctx))
|
||||
.collect::<HashSet<_>>()
|
||||
.iter()
|
||||
.for_each(|ip| {
|
||||
@@ -515,6 +520,11 @@ impl DirectConnectorManagerData {
|
||||
);
|
||||
}
|
||||
});
|
||||
} else if self.global_ctx.is_ip_easytier_managed_ipv6(s_addr.ip()) {
|
||||
tracing::debug!(
|
||||
?listener,
|
||||
"skip EasyTier-managed IPv6 as direct-connect target"
|
||||
);
|
||||
} else if !s_addr.ip().is_loopback() || TESTING.load(Ordering::Relaxed) {
|
||||
if self
|
||||
.global_ctx
|
||||
@@ -790,9 +800,10 @@ impl DirectConnectorManager {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
|
||||
use crate::{
|
||||
common::global_ctx::tests::get_mock_global_ctx,
|
||||
connector::direct::{
|
||||
DirectConnectorManager, DirectConnectorManagerData, DstListenerUrlBlackListItem,
|
||||
},
|
||||
@@ -802,12 +813,41 @@ mod tests {
|
||||
wait_route_appear_with_cost,
|
||||
},
|
||||
proto::peer_rpc::GetIpListResponse,
|
||||
tunnel::{IpScheme, TunnelScheme, matches_scheme},
|
||||
};
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
|
||||
use super::{TESTING, mapped_listener_port, resolve_mapped_listener_addrs};
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_ipv6_candidate_rejects_easytier_managed_addr_even_in_tests() {
|
||||
let global_ctx = get_mock_global_ctx();
|
||||
let managed_ipv6: cidr::Ipv6Inet = "2001:db8::2/128".parse().unwrap();
|
||||
global_ctx.set_public_ipv6_routes(BTreeSet::from([managed_ipv6]));
|
||||
|
||||
assert!(!super::is_usable_public_ipv6_candidate_with_mode(
|
||||
&"2001:db8::2".parse().unwrap(),
|
||||
&global_ctx,
|
||||
true,
|
||||
));
|
||||
assert!(super::is_usable_public_ipv6_candidate_with_mode(
|
||||
&"::1".parse().unwrap(),
|
||||
&global_ctx,
|
||||
true,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udp_ipv6_url_matches_hole_punch_branch_condition() {
|
||||
let remote_url: url::Url = "udp://[2001:db8::1]:11010".parse().unwrap();
|
||||
let takes_udp_ipv6_hole_punch_branch =
|
||||
matches_scheme!(remote_url, TunnelScheme::Ip(IpScheme::Udp))
|
||||
&& matches!(remote_url.host(), Some(url::Host::Ipv6(_)));
|
||||
|
||||
assert!(takes_udp_ipv6_hole_punch_branch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_listener_port_uses_ip_scheme_defaults() {
|
||||
assert_eq!(
|
||||
|
||||
+180
-15
@@ -1,19 +1,17 @@
|
||||
use std::{
|
||||
net::{SocketAddr, SocketAddrV4, SocketAddrV6},
|
||||
sync::Arc,
|
||||
};
|
||||
use std::net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
|
||||
|
||||
use crate::{
|
||||
common::{error::Error, global_ctx::ArcGlobalCtx, idn, network::IPCollector},
|
||||
common::{dns::socket_addrs, error::Error, global_ctx::ArcGlobalCtx, idn},
|
||||
connector::dns_connector::DnsTunnelConnector,
|
||||
proto::common::PeerFeatureFlag,
|
||||
tunnel::{
|
||||
self, FromUrl, IpScheme, IpVersion, TunnelConnector, TunnelError, TunnelScheme,
|
||||
self, IpScheme, IpVersion, TunnelConnector, TunnelError, TunnelScheme,
|
||||
ring::RingTunnelConnector, tcp::TcpTunnelConnector, udp::UdpTunnelConnector,
|
||||
},
|
||||
utils::BoxExt,
|
||||
};
|
||||
use http_connector::HttpTunnelConnector;
|
||||
use rand::seq::SliceRandom;
|
||||
|
||||
pub mod direct;
|
||||
pub mod manual;
|
||||
@@ -56,7 +54,7 @@ pub(crate) fn should_background_p2p_with_peer(
|
||||
async fn set_bind_addr_for_peer_connector(
|
||||
connector: &mut (impl TunnelConnector + ?Sized),
|
||||
is_ipv4: bool,
|
||||
ip_collector: &Arc<IPCollector>,
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
) {
|
||||
if cfg!(any(
|
||||
target_os = "android",
|
||||
@@ -69,7 +67,7 @@ async fn set_bind_addr_for_peer_connector(
|
||||
return;
|
||||
}
|
||||
|
||||
let ips = ip_collector.collect_ip_addrs().await;
|
||||
let ips = global_ctx.get_ip_collector().collect_ip_addrs().await;
|
||||
if is_ipv4 {
|
||||
let mut bind_addrs = vec![];
|
||||
for ipv4 in ips.interface_ipv4s {
|
||||
@@ -80,7 +78,11 @@ async fn set_bind_addr_for_peer_connector(
|
||||
} else {
|
||||
let mut bind_addrs = vec![];
|
||||
for ipv6 in ips.interface_ipv6s.iter().chain(ips.public_ipv6.iter()) {
|
||||
let socket_addr = SocketAddrV6::new(std::net::Ipv6Addr::from(*ipv6), 0, 0, 0).into();
|
||||
let ipv6 = std::net::Ipv6Addr::from(*ipv6);
|
||||
if global_ctx.is_ip_easytier_managed_ipv6(&ipv6) {
|
||||
continue;
|
||||
}
|
||||
let socket_addr = SocketAddrV6::new(ipv6, 0, 0, 0).into();
|
||||
bind_addrs.push(socket_addr);
|
||||
}
|
||||
connector.set_bind_addrs(bind_addrs);
|
||||
@@ -88,6 +90,144 @@ async fn set_bind_addr_for_peer_connector(
|
||||
let _ = connector;
|
||||
}
|
||||
|
||||
struct ResolvedConnectorAddr {
|
||||
addr: SocketAddr,
|
||||
ip_version: IpVersion,
|
||||
}
|
||||
|
||||
fn connector_default_port(url: &url::Url) -> Option<u16> {
|
||||
url.try_into()
|
||||
.ok()
|
||||
.and_then(|s: TunnelScheme| s.try_into().ok())
|
||||
.map(IpScheme::default_port)
|
||||
}
|
||||
|
||||
fn addr_matches_ip_version(addr: &SocketAddr, ip_version: IpVersion) -> bool {
|
||||
match ip_version {
|
||||
IpVersion::V4 => addr.is_ipv4(),
|
||||
IpVersion::V6 => addr.is_ipv6(),
|
||||
IpVersion::Both => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn infer_effective_ip_version(addrs: &[SocketAddr], requested_ip_version: IpVersion) -> IpVersion {
|
||||
match requested_ip_version {
|
||||
IpVersion::Both if addrs.iter().all(SocketAddr::is_ipv4) => IpVersion::V4,
|
||||
IpVersion::Both if addrs.iter().all(SocketAddr::is_ipv6) => IpVersion::V6,
|
||||
_ => requested_ip_version,
|
||||
}
|
||||
}
|
||||
|
||||
async fn easytier_managed_ipv6_source_for_dst(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
dst_addr: SocketAddrV6,
|
||||
) -> Result<Option<Ipv6Addr>, Error> {
|
||||
let socket = {
|
||||
let _g = global_ctx.net_ns.guard();
|
||||
tokio::net::UdpSocket::bind("[::]:0").await?
|
||||
};
|
||||
socket.connect(SocketAddr::V6(dst_addr)).await?;
|
||||
|
||||
let IpAddr::V6(local_ip) = socket.local_addr()?.ip() else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
Ok(global_ctx
|
||||
.is_ip_easytier_managed_ipv6(&local_ip)
|
||||
.then_some(local_ip))
|
||||
}
|
||||
|
||||
async fn ipv6_connector_reject_reason(
|
||||
url: &url::Url,
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
v6_addr: SocketAddrV6,
|
||||
skip_source_validation_errors: bool,
|
||||
) -> Result<Option<String>, Error> {
|
||||
if global_ctx.is_ip_easytier_managed_ipv6(v6_addr.ip()) {
|
||||
return Ok(Some(format!(
|
||||
"{} resolves to EasyTier-managed IPv6 {}",
|
||||
url,
|
||||
v6_addr.ip()
|
||||
)));
|
||||
}
|
||||
|
||||
match easytier_managed_ipv6_source_for_dst(global_ctx, v6_addr).await {
|
||||
Ok(Some(local_ip)) => Ok(Some(format!(
|
||||
"{} would use EasyTier-managed IPv6 {} as local source for {}",
|
||||
url, local_ip, v6_addr
|
||||
))),
|
||||
Ok(None) => Ok(None),
|
||||
Err(err) if skip_source_validation_errors => Ok(Some(format!(
|
||||
"{} IPv6 candidate {} could not be validated: {}",
|
||||
url, v6_addr, err
|
||||
))),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_connector_socket_addr(
|
||||
url: &url::Url,
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
ip_version: IpVersion,
|
||||
) -> Result<ResolvedConnectorAddr, Error> {
|
||||
let addrs = socket_addrs(url, || connector_default_port(url))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
TunnelError::InvalidAddr(format!(
|
||||
"failed to resolve socket addr, url: {}, error: {}",
|
||||
url, e
|
||||
))
|
||||
})?;
|
||||
|
||||
let mut usable_addrs = Vec::new();
|
||||
let mut rejected_ipv6_reason = None;
|
||||
let skip_source_validation_errors = ip_version == IpVersion::Both;
|
||||
for addr in addrs
|
||||
.into_iter()
|
||||
.filter(|addr| addr_matches_ip_version(addr, ip_version))
|
||||
{
|
||||
if let SocketAddr::V6(v6_addr) = addr
|
||||
&& let Some(reason) = ipv6_connector_reject_reason(
|
||||
url,
|
||||
global_ctx,
|
||||
v6_addr,
|
||||
skip_source_validation_errors,
|
||||
)
|
||||
.await?
|
||||
{
|
||||
rejected_ipv6_reason = Some(reason);
|
||||
continue;
|
||||
}
|
||||
|
||||
usable_addrs.push(addr);
|
||||
}
|
||||
|
||||
if usable_addrs.is_empty() {
|
||||
if let Some(reason) = rejected_ipv6_reason {
|
||||
return Err(Error::InvalidUrl(format!(
|
||||
"{}, refusing overlay-backed underlay connection",
|
||||
reason
|
||||
)));
|
||||
}
|
||||
|
||||
return Err(Error::TunnelError(TunnelError::NoDnsRecordFound(
|
||||
ip_version,
|
||||
)));
|
||||
}
|
||||
|
||||
let effective_ip_version = infer_effective_ip_version(&usable_addrs, ip_version);
|
||||
|
||||
let addr = usable_addrs
|
||||
.choose(&mut rand::thread_rng())
|
||||
.copied()
|
||||
.ok_or_else(|| Error::TunnelError(TunnelError::NoDnsRecordFound(ip_version)))?;
|
||||
|
||||
Ok(ResolvedConnectorAddr {
|
||||
addr,
|
||||
ip_version: effective_ip_version,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn create_connector_by_url(
|
||||
url: &str,
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
@@ -98,9 +238,11 @@ pub async fn create_connector_by_url(
|
||||
let scheme = (&url)
|
||||
.try_into()
|
||||
.map_err(|_| TunnelError::InvalidProtocol(url.scheme().to_owned()))?;
|
||||
let mut effective_connector_ip_version = ip_version;
|
||||
let mut connector: Box<dyn TunnelConnector + 'static> = match scheme {
|
||||
TunnelScheme::Ip(scheme) => {
|
||||
let dst_addr = SocketAddr::from_url(url.clone(), ip_version).await?;
|
||||
let resolved_addr = resolve_connector_socket_addr(&url, global_ctx, ip_version).await?;
|
||||
effective_connector_ip_version = resolved_addr.ip_version;
|
||||
let mut connector: Box<dyn TunnelConnector> = match scheme {
|
||||
IpScheme::Tcp => TcpTunnelConnector::new(url).boxed(),
|
||||
IpScheme::Udp => UdpTunnelConnector::new(url).boxed(),
|
||||
@@ -125,11 +267,12 @@ pub async fn create_connector_by_url(
|
||||
#[cfg(feature = "faketcp")]
|
||||
IpScheme::FakeTcp => tunnel::fake_tcp::FakeTcpTunnelConnector::new(url).boxed(),
|
||||
};
|
||||
connector.set_resolved_addr(resolved_addr.addr);
|
||||
if global_ctx.config.get_flags().bind_device {
|
||||
set_bind_addr_for_peer_connector(
|
||||
&mut connector,
|
||||
dst_addr.is_ipv4(),
|
||||
&global_ctx.get_ip_collector(),
|
||||
resolved_addr.addr.is_ipv4(),
|
||||
global_ctx,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -151,16 +294,38 @@ pub async fn create_connector_by_url(
|
||||
DnsTunnelConnector::new(url, global_ctx.clone()).boxed()
|
||||
}
|
||||
};
|
||||
connector.set_ip_version(ip_version);
|
||||
connector.set_ip_version(effective_connector_ip_version);
|
||||
|
||||
Ok(connector)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::proto::common::PeerFeatureFlag;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::{should_background_p2p_with_peer, should_try_p2p_with_peer};
|
||||
use crate::{
|
||||
common::global_ctx::tests::get_mock_global_ctx, proto::common::PeerFeatureFlag,
|
||||
tunnel::IpVersion,
|
||||
};
|
||||
|
||||
use super::{
|
||||
create_connector_by_url, should_background_p2p_with_peer, should_try_p2p_with_peer,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn connector_rejects_easytier_managed_ipv6_destination() {
|
||||
let global_ctx = get_mock_global_ctx();
|
||||
let public_route: cidr::Ipv6Inet = "2001:db8::2/128".parse().unwrap();
|
||||
global_ctx.set_public_ipv6_routes(BTreeSet::from([public_route]));
|
||||
|
||||
let ret =
|
||||
create_connector_by_url("tcp://[2001:db8::2]:11010", &global_ctx, IpVersion::V6).await;
|
||||
|
||||
assert!(matches!(
|
||||
ret,
|
||||
Err(crate::common::error::Error::InvalidUrl(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lazy_background_p2p_requires_need_p2p() {
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::{
|
||||
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
use dashmap::{DashMap, DashSet};
|
||||
use guarden::defer;
|
||||
use rand::seq::SliceRandom as _;
|
||||
use tokio::{net::UdpSocket, sync::Mutex, task::JoinSet};
|
||||
use tracing::{Instrument, Level, instrument};
|
||||
@@ -15,7 +16,6 @@ use crate::{
|
||||
common::{
|
||||
PeerId, error::Error, global_ctx::ArcGlobalCtx, join_joinset_background, netns::NetNS, upnp,
|
||||
},
|
||||
defer,
|
||||
peers::peer_manager::PeerManager,
|
||||
proto::common::NatType,
|
||||
tunnel::{
|
||||
@@ -719,25 +719,31 @@ async fn check_udp_socket_local_addr(
|
||||
) -> Result<(), Error> {
|
||||
let socket = UdpSocket::bind("0.0.0.0:0").await?;
|
||||
socket.connect(remote_mapped_addr).await?;
|
||||
if let Ok(local_addr) = socket.local_addr() {
|
||||
// local_addr should not be equal to virtual ipv4 or virtual ipv6
|
||||
match local_addr.ip() {
|
||||
IpAddr::V4(ip) => {
|
||||
if global_ctx.get_ipv4().map(|ip| ip.address()) == Some(ip) {
|
||||
return Err(anyhow::anyhow!("local address is virtual ipv4").into());
|
||||
}
|
||||
}
|
||||
IpAddr::V6(ip) => {
|
||||
if global_ctx.get_ipv6().map(|ip| ip.address()) == Some(ip) {
|
||||
return Err(anyhow::anyhow!("local address is virtual ipv6").into());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(local_addr) = socket.local_addr()
|
||||
&& let Some(err) = easytier_managed_local_addr_error(&global_ctx, local_addr)
|
||||
{
|
||||
return Err(anyhow::anyhow!(err).into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn easytier_managed_local_addr_error(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
local_addr: SocketAddr,
|
||||
) -> Option<&'static str> {
|
||||
// local_addr should not be equal to an EasyTier-managed virtual/public address.
|
||||
match local_addr.ip() {
|
||||
IpAddr::V4(ip) if global_ctx.get_ipv4().map(|ip| ip.address()) == Some(ip) => {
|
||||
Some("local address is virtual ipv4")
|
||||
}
|
||||
IpAddr::V6(ip) if global_ctx.is_ip_easytier_managed_ipv6(&ip) => {
|
||||
Some("local address is easytier-managed ipv6")
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn try_connect_with_socket(
|
||||
global_ctx: ArcGlobalCtx,
|
||||
socket: Arc<UdpSocket>,
|
||||
@@ -763,11 +769,29 @@ pub(crate) async fn try_connect_with_socket(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{collections::BTreeSet, net::SocketAddr};
|
||||
|
||||
use crate::common::global_ctx::tests::get_mock_global_ctx;
|
||||
|
||||
use super::{
|
||||
MAX_PUBLIC_UDP_HOLE_PUNCH_LISTENERS, should_create_public_listener,
|
||||
should_retry_public_listener_selection,
|
||||
MAX_PUBLIC_UDP_HOLE_PUNCH_LISTENERS, easytier_managed_local_addr_error,
|
||||
should_create_public_listener, should_retry_public_listener_selection,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn local_addr_check_rejects_easytier_public_ipv6_route() {
|
||||
let global_ctx = get_mock_global_ctx();
|
||||
let public_route: cidr::Ipv6Inet = "2001:db8::4/128".parse().unwrap();
|
||||
global_ctx.set_public_ipv6_routes(BTreeSet::from([public_route]));
|
||||
|
||||
let local_addr: SocketAddr = "[2001:db8::4]:1234".parse().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
easytier_managed_local_addr_error(&global_ctx, local_addr),
|
||||
Some("local address is easytier-managed ipv6")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_selection_prefers_reuse_before_cap() {
|
||||
assert!(!should_create_public_listener(1, true, true, false, false));
|
||||
|
||||
@@ -9,6 +9,7 @@ use std::{
|
||||
};
|
||||
|
||||
use anyhow::Context;
|
||||
use guarden::defer;
|
||||
use rand::{Rng, seq::SliceRandom};
|
||||
use tokio::{net::UdpSocket, sync::RwLock};
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
@@ -22,7 +23,6 @@ use crate::{
|
||||
},
|
||||
handle_rpc_result,
|
||||
},
|
||||
defer,
|
||||
peers::peer_manager::PeerManager,
|
||||
proto::{
|
||||
peer_rpc::{
|
||||
|
||||
+40
-1
@@ -12,7 +12,6 @@ use crate::{
|
||||
constants::EASYTIER_VERSION,
|
||||
log,
|
||||
},
|
||||
defer,
|
||||
instance_manager::NetworkInstanceManager,
|
||||
launcher::add_proxy_network_to_config,
|
||||
proto::common::{CompressionAlgoPb, SecureModeConfig},
|
||||
@@ -23,6 +22,7 @@ use crate::{
|
||||
use anyhow::Context;
|
||||
use cidr::IpCidr;
|
||||
use clap::{CommandFactory, Parser};
|
||||
use guarden::defer;
|
||||
use rust_i18n::t;
|
||||
use std::{
|
||||
net::{IpAddr, SocketAddr},
|
||||
@@ -171,6 +171,31 @@ struct NetworkOptions {
|
||||
)]
|
||||
ipv6: Option<String>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
env = "ET_IPV6_PUBLIC_ADDR_PROVIDER",
|
||||
help = t!("core_clap.ipv6_public_addr_provider").to_string(),
|
||||
num_args = 0..=1,
|
||||
default_missing_value = "true"
|
||||
)]
|
||||
ipv6_public_addr_provider: Option<bool>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
env = "ET_IPV6_PUBLIC_ADDR_AUTO",
|
||||
help = t!("core_clap.ipv6_public_addr_auto").to_string(),
|
||||
num_args = 0..=1,
|
||||
default_missing_value = "true"
|
||||
)]
|
||||
ipv6_public_addr_auto: Option<bool>,
|
||||
|
||||
#[arg(
|
||||
long,
|
||||
env = "ET_IPV6_PUBLIC_ADDR_PREFIX",
|
||||
help = t!("core_clap.ipv6_public_addr_prefix").to_string()
|
||||
)]
|
||||
ipv6_public_addr_prefix: Option<String>,
|
||||
|
||||
#[arg(
|
||||
short,
|
||||
long,
|
||||
@@ -875,6 +900,20 @@ impl NetworkOptions {
|
||||
})?))
|
||||
}
|
||||
|
||||
if let Some(enabled) = self.ipv6_public_addr_provider {
|
||||
cfg.set_ipv6_public_addr_provider(enabled);
|
||||
}
|
||||
|
||||
if let Some(enabled) = self.ipv6_public_addr_auto {
|
||||
cfg.set_ipv6_public_addr_auto(enabled);
|
||||
}
|
||||
|
||||
if let Some(prefix) = &self.ipv6_public_addr_prefix {
|
||||
cfg.set_ipv6_public_addr_prefix(Some(prefix.parse().with_context(|| {
|
||||
format!("failed to parse ipv6 public address prefix: {}", prefix)
|
||||
})?));
|
||||
}
|
||||
|
||||
if !self.peers.is_empty() {
|
||||
let mut peers = cfg.get_peers();
|
||||
peers.reserve(peers.len() + self.peers.len());
|
||||
|
||||
@@ -51,13 +51,14 @@ use easytier::{
|
||||
ListCredentialsRequest, ListCredentialsResponse, ListForeignNetworkRequest,
|
||||
ListGlobalForeignNetworkRequest, ListMappedListenerRequest, ListPeerRequest,
|
||||
ListPeerResponse, ListPortForwardRequest, ListPortForwardResponse,
|
||||
ListRouteRequest, ListRouteResponse, MappedListener, MappedListenerManageRpc,
|
||||
ListPublicIpv6InfoRequest, ListPublicIpv6InfoResponse, ListRouteRequest,
|
||||
ListRouteResponse, MappedListener, MappedListenerManageRpc,
|
||||
MappedListenerManageRpcClientFactory, MetricSnapshot, NodeInfo, PeerManageRpc,
|
||||
PeerManageRpcClientFactory, PortForwardManageRpc,
|
||||
PortForwardManageRpcClientFactory, RevokeCredentialRequest, ShowNodeInfoRequest,
|
||||
StatsRpc, StatsRpcClientFactory, TcpProxyEntryState, TcpProxyEntryTransportType,
|
||||
TcpProxyRpc, TcpProxyRpcClientFactory, TrustedKeySourcePb, VpnPortalInfo,
|
||||
VpnPortalRpc, VpnPortalRpcClientFactory,
|
||||
PortForwardManageRpcClientFactory, RevokeCredentialRequest, Route as ApiRoute,
|
||||
ShowNodeInfoRequest, StatsRpc, StatsRpcClientFactory, TcpProxyEntryState,
|
||||
TcpProxyEntryTransportType, TcpProxyRpc, TcpProxyRpcClientFactory,
|
||||
TrustedKeySourcePb, VpnPortalInfo, VpnPortalRpc, VpnPortalRpcClientFactory,
|
||||
instance_identifier::{InstanceSelector, Selector},
|
||||
list_global_foreign_network_response, list_peer_route_pair,
|
||||
},
|
||||
@@ -193,6 +194,7 @@ struct PeerArgs {
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum PeerSubCommand {
|
||||
List,
|
||||
Ipv6,
|
||||
ListForeign {
|
||||
#[arg(
|
||||
long,
|
||||
@@ -536,6 +538,12 @@ struct RouteListData {
|
||||
peer_routes: Vec<PeerRoutePair>,
|
||||
}
|
||||
|
||||
struct PeerIpv6DataRaw {
|
||||
node_info: NodeInfo,
|
||||
routes: Vec<ApiRoute>,
|
||||
provider_info: ListPublicIpv6InfoResponse,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct PeerCenterRowData {
|
||||
node_id: String,
|
||||
@@ -963,6 +971,27 @@ impl<'a> CommandHandler<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
async fn fetch_local_public_ipv6_info(&self) -> Result<ListPublicIpv6InfoResponse, Error> {
|
||||
Ok(self
|
||||
.get_peer_manager_client()
|
||||
.await?
|
||||
.list_public_ipv6_info(
|
||||
BaseController::default(),
|
||||
ListPublicIpv6InfoRequest {
|
||||
instance: Some(self.instance_selector.clone()),
|
||||
},
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn fetch_peer_ipv6_data(&self) -> Result<PeerIpv6DataRaw, Error> {
|
||||
Ok(PeerIpv6DataRaw {
|
||||
node_info: self.fetch_node_info().await?,
|
||||
routes: self.list_routes().await?.routes,
|
||||
provider_info: self.fetch_local_public_ipv6_info().await?,
|
||||
})
|
||||
}
|
||||
|
||||
async fn fetch_connector_list(&self) -> Result<Vec<Connector>, Error> {
|
||||
Ok(self
|
||||
.get_connector_manager_client()
|
||||
@@ -1375,6 +1404,154 @@ impl<'a> CommandHandler<'a> {
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle_peer_ipv6(&self) -> Result<(), Error> {
|
||||
#[derive(tabled::Tabled, serde::Serialize)]
|
||||
struct PeerIpv6NodeRow {
|
||||
peer_id: u32,
|
||||
hostname: String,
|
||||
inst_id: String,
|
||||
ipv4: String,
|
||||
public_ipv6_addr: String,
|
||||
provider_prefix: String,
|
||||
}
|
||||
|
||||
#[derive(tabled::Tabled, serde::Serialize)]
|
||||
struct ProviderLeaseRow {
|
||||
peer_id: u32,
|
||||
inst_id: String,
|
||||
leased_addr: String,
|
||||
valid_until: String,
|
||||
reused: bool,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct ProviderLeaseSection {
|
||||
provider_prefix: String,
|
||||
leases: Vec<ProviderLeaseRow>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct PeerIpv6View {
|
||||
nodes: Vec<PeerIpv6NodeRow>,
|
||||
local_provider: Option<ProviderLeaseSection>,
|
||||
}
|
||||
|
||||
fn fmt_ipv6_inet(value: Option<easytier::proto::common::Ipv6Inet>) -> String {
|
||||
value
|
||||
.map(|value| value.to_string())
|
||||
.unwrap_or_else(|| "-".to_string())
|
||||
}
|
||||
|
||||
fn fmt_valid_until(unix_seconds: i64) -> String {
|
||||
chrono::DateTime::<chrono::Utc>::from_timestamp(unix_seconds, 0)
|
||||
.map(|ts| {
|
||||
ts.with_timezone(&chrono::Local)
|
||||
.format("%Y-%m-%d %H:%M:%S")
|
||||
.to_string()
|
||||
})
|
||||
.unwrap_or_else(|| unix_seconds.to_string())
|
||||
}
|
||||
|
||||
let build_view = |data: &PeerIpv6DataRaw| {
|
||||
let mut nodes = Vec::with_capacity(data.routes.len() + 1);
|
||||
nodes.push(PeerIpv6NodeRow {
|
||||
peer_id: data.node_info.peer_id,
|
||||
hostname: data.node_info.hostname.clone(),
|
||||
inst_id: data.node_info.inst_id.clone(),
|
||||
ipv4: data.node_info.ipv4_addr.clone(),
|
||||
public_ipv6_addr: fmt_ipv6_inet(data.node_info.public_ipv6_addr),
|
||||
provider_prefix: fmt_ipv6_inet(data.node_info.ipv6_public_addr_prefix),
|
||||
});
|
||||
nodes.extend(data.routes.iter().map(|route| {
|
||||
PeerIpv6NodeRow {
|
||||
peer_id: route.peer_id,
|
||||
hostname: route.hostname.clone(),
|
||||
inst_id: route.inst_id.clone(),
|
||||
ipv4: route
|
||||
.ipv4_addr
|
||||
.map(|ipv4| ipv4.to_string())
|
||||
.unwrap_or_else(|| "-".to_string()),
|
||||
public_ipv6_addr: fmt_ipv6_inet(route.public_ipv6_addr),
|
||||
provider_prefix: fmt_ipv6_inet(route.ipv6_public_addr_prefix),
|
||||
}
|
||||
}));
|
||||
nodes.sort_by_key(|row| {
|
||||
(
|
||||
row.peer_id != data.node_info.peer_id,
|
||||
row.peer_id,
|
||||
row.inst_id.clone(),
|
||||
)
|
||||
});
|
||||
|
||||
let local_provider = data.provider_info.provider_prefix.map(|provider_prefix| {
|
||||
let mut leases = data
|
||||
.provider_info
|
||||
.provider_leases
|
||||
.iter()
|
||||
.map(|lease| ProviderLeaseRow {
|
||||
peer_id: lease.peer_id,
|
||||
inst_id: lease.inst_id.clone(),
|
||||
leased_addr: fmt_ipv6_inet(lease.leased_addr),
|
||||
valid_until: fmt_valid_until(lease.valid_until_unix_seconds),
|
||||
reused: lease.reused,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
leases.sort_by_key(|lease| {
|
||||
(
|
||||
lease.peer_id,
|
||||
lease.inst_id.clone(),
|
||||
lease.leased_addr.clone(),
|
||||
)
|
||||
});
|
||||
ProviderLeaseSection {
|
||||
provider_prefix: provider_prefix.to_string(),
|
||||
leases,
|
||||
}
|
||||
});
|
||||
|
||||
PeerIpv6View {
|
||||
nodes,
|
||||
local_provider,
|
||||
}
|
||||
};
|
||||
|
||||
let results = self
|
||||
.collect_instance_results(|handler| Box::pin(handler.fetch_peer_ipv6_data()))
|
||||
.await?;
|
||||
|
||||
if self.verbose || *self.output_format == OutputFormat::Json {
|
||||
return self.print_json_results(
|
||||
results
|
||||
.into_iter()
|
||||
.map(|result| result.map(|data| build_view(&data)))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
|
||||
self.print_results(&results, |data| {
|
||||
let view = build_view(data);
|
||||
print_output(&view.nodes, self.output_format, &[], &[], self.no_trunc)?;
|
||||
|
||||
if let Some(local_provider) = view.local_provider {
|
||||
println!();
|
||||
println!("Local provider prefix: {}", local_provider.provider_prefix);
|
||||
if local_provider.leases.is_empty() {
|
||||
println!("No active provider leases");
|
||||
} else {
|
||||
print_output(
|
||||
&local_provider.leases,
|
||||
self.output_format,
|
||||
&[],
|
||||
&[],
|
||||
self.no_trunc,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
async fn handle_route_dump(&self) -> Result<(), Error> {
|
||||
let results = self
|
||||
.collect_instance_results(|handler| Box::pin(handler.fetch_route_dump()))
|
||||
@@ -2652,6 +2829,9 @@ async fn main() -> Result<(), Error> {
|
||||
Some(PeerSubCommand::List) => {
|
||||
handler.handle_peer_list().await?;
|
||||
}
|
||||
Some(PeerSubCommand::Ipv6) => {
|
||||
handler.handle_peer_ipv6().await?;
|
||||
}
|
||||
Some(PeerSubCommand::ListForeign { trusted_keys }) => {
|
||||
handler.handle_foreign_network_list(*trusted_keys).await?;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::{
|
||||
use anyhow::Context;
|
||||
use bytes::Bytes;
|
||||
use dashmap::DashMap;
|
||||
use guarden::defer;
|
||||
use kcp_sys::{
|
||||
endpoint::{ConnId, KcpEndpoint, KcpPacketReceiver},
|
||||
ffi_safe::KcpConfig,
|
||||
@@ -359,7 +360,7 @@ impl KcpProxyDst {
|
||||
transport_type: TcpProxyEntryTransportType::Kcp.into(),
|
||||
},
|
||||
);
|
||||
crate::defer! {
|
||||
defer! {
|
||||
proxy_entries.remove(&conn_id);
|
||||
if proxy_entries.capacity() - proxy_entries.len() > 16 {
|
||||
proxy_entries.shrink_to_fit();
|
||||
|
||||
@@ -24,6 +24,7 @@ use bytes::{BufMut, Bytes, BytesMut};
|
||||
use dashmap::DashMap;
|
||||
use derivative::Derivative;
|
||||
use derive_more::{Constructor, Deref, DerefMut, From, Into};
|
||||
use guarden::defer;
|
||||
use prost::Message;
|
||||
use quinn::udp::{EcnCodepoint, RecvMeta, Transmit};
|
||||
use quinn::{
|
||||
@@ -662,7 +663,7 @@ impl QuicStreamReceiver {
|
||||
transport_type: TcpProxyEntryTransportType::Quic.into(),
|
||||
},
|
||||
);
|
||||
crate::defer! {
|
||||
defer! {
|
||||
proxy_entries.remove(&handle);
|
||||
if proxy_entries.capacity() - proxy_entries.len() > 16 {
|
||||
proxy_entries.shrink_to_fit();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// translated from tailscale #32ce1bdb48078ec4cedaeeb5b1b2ff9c0ef61a49
|
||||
|
||||
use crate::defer;
|
||||
use anyhow::{Context, Result};
|
||||
use dbus::blocking::stdintf::org_freedesktop_dbus::Properties as _;
|
||||
use std::fs;
|
||||
@@ -167,6 +166,7 @@ fn new_os_configurator(_interface_name: String) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
use guarden::defer;
|
||||
use std::io::{self, BufRead, Cursor};
|
||||
|
||||
/// 返回 `resolv.conf` 内容的拥有者("systemd-resolved"、"NetworkManager"、"resolvconf" 或空字符串)
|
||||
|
||||
@@ -9,7 +9,6 @@ use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use cidr::{IpCidr, Ipv4Inet};
|
||||
|
||||
use futures::FutureExt;
|
||||
use tokio::sync::{Mutex, Notify};
|
||||
#[cfg(feature = "tun")]
|
||||
@@ -65,6 +64,11 @@ use crate::vpn_portal::{self, VpnPortal};
|
||||
#[cfg(feature = "magic-dns")]
|
||||
use super::dns_server::{MAGIC_DNS_FAKE_IP, runner::DnsRunner};
|
||||
use super::listeners::ListenerManager;
|
||||
use super::public_ipv6_provider::{
|
||||
reconcile_public_ipv6_provider_runtime, run_public_ipv6_provider_reconcile_task,
|
||||
should_run_public_ipv6_provider_reconcile, validate_public_ipv6_config,
|
||||
validate_public_ipv6_config_values,
|
||||
};
|
||||
|
||||
#[cfg(feature = "socks5")]
|
||||
use crate::gateway::socks5::Socks5Server;
|
||||
@@ -253,11 +257,64 @@ pub struct InstanceConfigPatcher {
|
||||
}
|
||||
|
||||
impl InstanceConfigPatcher {
|
||||
fn parse_ipv6_public_addr_prefix_patch(
|
||||
prefix: Option<&str>,
|
||||
) -> Result<Option<Option<cidr::Ipv6Cidr>>, anyhow::Error> {
|
||||
let Some(prefix) = prefix else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let prefix = prefix.trim();
|
||||
if prefix.is_empty() {
|
||||
return Ok(Some(None));
|
||||
}
|
||||
|
||||
let parsed = prefix
|
||||
.parse()
|
||||
.with_context(|| format!("failed to parse ipv6 public address prefix: {prefix}"))?;
|
||||
Ok(Some(Some(parsed)))
|
||||
}
|
||||
|
||||
fn effective_ipv6_for_public_ipv6_validation(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
patch: &crate::proto::api::config::InstanceConfigPatch,
|
||||
_auto_enabled: bool,
|
||||
) -> Option<cidr::Ipv6Inet> {
|
||||
if let Some(ipv6) = patch.ipv6 {
|
||||
return Some(ipv6.into());
|
||||
}
|
||||
|
||||
global_ctx.get_ipv6()
|
||||
}
|
||||
|
||||
fn validate_public_ipv6_patch(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
patch: &crate::proto::api::config::InstanceConfigPatch,
|
||||
) -> Result<Option<Option<cidr::Ipv6Cidr>>, anyhow::Error> {
|
||||
let parsed_prefix =
|
||||
Self::parse_ipv6_public_addr_prefix_patch(patch.ipv6_public_addr_prefix.as_deref())?;
|
||||
|
||||
let auto_enabled = patch
|
||||
.ipv6_public_addr_auto
|
||||
.unwrap_or(global_ctx.config.get_ipv6_public_addr_auto());
|
||||
let provider_enabled = patch
|
||||
.ipv6_public_addr_provider
|
||||
.unwrap_or(global_ctx.config.get_ipv6_public_addr_provider());
|
||||
let prefix =
|
||||
parsed_prefix.unwrap_or_else(|| global_ctx.config.get_ipv6_public_addr_prefix());
|
||||
let ipv6 = Self::effective_ipv6_for_public_ipv6_validation(global_ctx, patch, auto_enabled);
|
||||
|
||||
validate_public_ipv6_config_values(ipv6, provider_enabled, auto_enabled, prefix)?;
|
||||
Ok(parsed_prefix)
|
||||
}
|
||||
|
||||
pub async fn apply_patch(
|
||||
&self,
|
||||
patch: crate::proto::api::config::InstanceConfigPatch,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let patch_for_event = patch.clone();
|
||||
let global_ctx = weak_upgrade(&self.global_ctx)?;
|
||||
let parsed_ipv6_public_addr_prefix = Self::validate_public_ipv6_patch(&global_ctx, &patch)?;
|
||||
|
||||
self.patch_port_forwards(patch.port_forwards).await?;
|
||||
self.patch_acl(patch.acl).await?;
|
||||
@@ -267,7 +324,8 @@ impl InstanceConfigPatcher {
|
||||
self.patch_mapped_listeners(patch.mapped_listeners).await?;
|
||||
self.patch_connector(patch.connectors).await?;
|
||||
|
||||
let global_ctx = weak_upgrade(&self.global_ctx)?;
|
||||
let provider_reconcile_was_running = should_run_public_ipv6_provider_reconcile(&global_ctx);
|
||||
let mut provider_config_changed = false;
|
||||
if let Some(hostname) = patch.hostname {
|
||||
global_ctx.set_hostname(hostname.clone());
|
||||
global_ctx.config.set_hostname(Some(hostname));
|
||||
@@ -282,9 +340,30 @@ impl InstanceConfigPatcher {
|
||||
global_ctx.set_ipv6(Some(ipv6.into()));
|
||||
global_ctx.config.set_ipv6(Some(ipv6.into()));
|
||||
}
|
||||
if let Some(enabled) = patch.ipv6_public_addr_provider {
|
||||
global_ctx.config.set_ipv6_public_addr_provider(enabled);
|
||||
provider_config_changed = true;
|
||||
}
|
||||
if let Some(enabled) = patch.ipv6_public_addr_auto {
|
||||
global_ctx.config.set_ipv6_public_addr_auto(enabled);
|
||||
}
|
||||
if let Some(prefix) = parsed_ipv6_public_addr_prefix {
|
||||
global_ctx.config.set_ipv6_public_addr_prefix(prefix);
|
||||
provider_config_changed = true;
|
||||
}
|
||||
|
||||
global_ctx.issue_event(GlobalCtxEvent::ConfigPatched(patch_for_event));
|
||||
|
||||
if provider_config_changed {
|
||||
reconcile_public_ipv6_provider_runtime(&global_ctx).await;
|
||||
|
||||
let provider_reconcile_should_run =
|
||||
should_run_public_ipv6_provider_reconcile(&global_ctx);
|
||||
if !provider_reconcile_was_running && provider_reconcile_should_run {
|
||||
run_public_ipv6_provider_reconcile_task(&global_ctx);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -664,6 +743,12 @@ impl Instance {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn prepare_public_ipv6_config(&self) -> Result<(), Error> {
|
||||
validate_public_ipv6_config(&self.global_ctx)?;
|
||||
reconcile_public_ipv6_provider_runtime(&self.global_ctx).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// use a mock nic ctx to consume packets.
|
||||
#[cfg(feature = "tun")]
|
||||
async fn clear_nic_ctx(
|
||||
@@ -932,6 +1017,7 @@ impl Instance {
|
||||
}
|
||||
|
||||
pub async fn run(&mut self) -> Result<(), Error> {
|
||||
self.prepare_public_ipv6_config().await?;
|
||||
self.listener_manager
|
||||
.lock()
|
||||
.await
|
||||
@@ -939,6 +1025,7 @@ impl Instance {
|
||||
.await?;
|
||||
self.listener_manager.lock().await.run().await?;
|
||||
self.peer_manager.run().await?;
|
||||
run_public_ipv6_provider_reconcile_task(&self.global_ctx);
|
||||
|
||||
#[cfg(feature = "tun")]
|
||||
{
|
||||
@@ -1544,7 +1631,9 @@ impl Drop for Instance {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
instance::instance::InstanceRpcServerHook, proto::rpc_impl::standalone::RpcServerHook,
|
||||
common::global_ctx::tests::get_mock_global_ctx,
|
||||
instance::instance::{InstanceConfigPatcher, InstanceRpcServerHook},
|
||||
proto::{api::config::InstanceConfigPatch, rpc_impl::standalone::RpcServerHook},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1665,4 +1754,50 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_public_ipv6_patch_rejects_non_global_prefix() {
|
||||
let global_ctx = get_mock_global_ctx();
|
||||
let patch = InstanceConfigPatch {
|
||||
ipv6_public_addr_provider: Some(true),
|
||||
ipv6_public_addr_prefix: Some("fd00::/64".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let err =
|
||||
InstanceConfigPatcher::validate_public_ipv6_patch(&global_ctx, &patch).unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("not a valid global unicast IPv6 prefix")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_public_ipv6_patch_allows_enabling_auto_with_manual_ipv6() {
|
||||
let global_ctx = get_mock_global_ctx();
|
||||
global_ctx.set_ipv6(Some("fd00::1/64".parse().unwrap()));
|
||||
|
||||
let patch = InstanceConfigPatch {
|
||||
ipv6_public_addr_auto: Some(true),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(InstanceConfigPatcher::validate_public_ipv6_patch(&global_ctx, &patch).is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn validate_public_ipv6_patch_ignores_runtime_auto_ipv6_cache() {
|
||||
let global_ctx = get_mock_global_ctx();
|
||||
global_ctx.config.set_ipv6_public_addr_auto(true);
|
||||
global_ctx.set_ipv6(Some("2001:db8::10/64".parse().unwrap()));
|
||||
|
||||
let patch = InstanceConfigPatch {
|
||||
ipv6_public_addr_provider: Some(true),
|
||||
ipv6_public_addr_prefix: Some("2001:db8:100::/64".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(InstanceConfigPatcher::validate_public_ipv6_patch(&global_ctx, &patch).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ pub mod instance;
|
||||
|
||||
pub mod listeners;
|
||||
|
||||
mod public_ipv6_provider;
|
||||
|
||||
pub mod proxy_cidrs_monitor;
|
||||
|
||||
#[cfg(feature = "tun")]
|
||||
|
||||
@@ -0,0 +1,918 @@
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
use anyhow::Context;
|
||||
use cidr::{Ipv6Cidr, Ipv6Inet};
|
||||
#[cfg(target_os = "linux")]
|
||||
use netlink_packet_route::route::{RouteAddress, RouteAttribute, RouteMessage, RouteType};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use crate::common::ifcfg::{get_interface_index, list_ipv6_route_messages};
|
||||
use crate::common::{
|
||||
error::Error,
|
||||
global_ctx::{ArcGlobalCtx, GlobalCtxEvent},
|
||||
};
|
||||
|
||||
const PUBLIC_IPV6_PROVIDER_RECONCILE_INTERVAL: std::time::Duration =
|
||||
std::time::Duration::from_secs(5);
|
||||
const PUBLIC_IPV6_PROVIDER_RECONCILE_MAX_RETRIES: usize = 3;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum PublicIpv6ProviderRuntimeState {
|
||||
Disabled,
|
||||
Pending(String),
|
||||
Active(Ipv6Cidr),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct PublicIpv6ProviderConfigSnapshot {
|
||||
provider_enabled: bool,
|
||||
configured_prefix: Option<Ipv6Cidr>,
|
||||
}
|
||||
|
||||
fn read_public_ipv6_provider_config_snapshot(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
) -> PublicIpv6ProviderConfigSnapshot {
|
||||
PublicIpv6ProviderConfigSnapshot {
|
||||
provider_enabled: global_ctx.config.get_ipv6_public_addr_provider(),
|
||||
configured_prefix: global_ctx.config.get_ipv6_public_addr_prefix(),
|
||||
}
|
||||
}
|
||||
|
||||
fn should_run_public_ipv6_provider_reconcile_task(
|
||||
config: PublicIpv6ProviderConfigSnapshot,
|
||||
) -> bool {
|
||||
config.provider_enabled && config.configured_prefix.is_none()
|
||||
}
|
||||
|
||||
pub(super) fn should_run_public_ipv6_provider_reconcile(global_ctx: &ArcGlobalCtx) -> bool {
|
||||
should_run_public_ipv6_provider_reconcile_task(read_public_ipv6_provider_config_snapshot(
|
||||
global_ctx,
|
||||
))
|
||||
}
|
||||
|
||||
fn is_global_routable_public_ipv6_prefix(prefix: Ipv6Cidr) -> bool {
|
||||
let addr = prefix.first_address();
|
||||
!addr.is_loopback()
|
||||
&& !addr.is_multicast()
|
||||
&& !addr.is_unicast_link_local()
|
||||
&& !addr.is_unique_local()
|
||||
&& !addr.is_unspecified()
|
||||
}
|
||||
|
||||
pub(super) fn validate_public_ipv6_config_values(
|
||||
_ipv6: Option<Ipv6Inet>,
|
||||
provider_enabled: bool,
|
||||
_auto_enabled: bool,
|
||||
prefix: Option<Ipv6Cidr>,
|
||||
) -> Result<(), Error> {
|
||||
if !provider_enabled {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
ensure_public_ipv6_provider_supported()?;
|
||||
|
||||
if let Some(prefix) = prefix
|
||||
&& !is_global_routable_public_ipv6_prefix(prefix)
|
||||
{
|
||||
return Err(anyhow::anyhow!(
|
||||
"the prefix {} is not a valid global unicast IPv6 prefix; it must be a routable address range, not a private, link-local, or multicast address",
|
||||
prefix
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn validate_public_ipv6_config(global_ctx: &ArcGlobalCtx) -> Result<(), Error> {
|
||||
validate_public_ipv6_config_values(
|
||||
global_ctx.get_ipv6(),
|
||||
global_ctx.config.get_ipv6_public_addr_provider(),
|
||||
global_ctx.config.get_ipv6_public_addr_auto(),
|
||||
global_ctx.config.get_ipv6_public_addr_prefix(),
|
||||
)
|
||||
}
|
||||
|
||||
fn ensure_public_ipv6_provider_supported() -> Result<(), Error> {
|
||||
if cfg!(target_os = "linux") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(anyhow::anyhow!(
|
||||
"the provider feature requires Linux; run without --ipv6-public-addr-provider on this node, or move the provider role to a Linux node. client mode (--ipv6-public-addr-auto) works on all platforms"
|
||||
)
|
||||
.into())
|
||||
}
|
||||
|
||||
fn public_ipv6_provider_auto_detect_error() -> Error {
|
||||
anyhow::anyhow!(
|
||||
"no public IPv6 prefix found on this system; set --ipv6-public-addr-prefix manually, or check that your ISP has delegated an IPv6 prefix and a default-from route exists in the kernel routing table"
|
||||
)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn read_linux_proc_bool(path: &Path) -> Result<bool, Error> {
|
||||
let value = std::fs::read_to_string(path)
|
||||
.with_context(|| format!("failed to read {}", path.display()))?;
|
||||
match value.trim() {
|
||||
"0" => Ok(false),
|
||||
"1" => Ok(true),
|
||||
other => Err(anyhow::anyhow!("unexpected value '{}' in {}", other, path.display()).into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn write_linux_proc_bool(path: &Path, enabled: bool) -> Result<(), Error> {
|
||||
let value = if enabled { "1\n" } else { "0\n" };
|
||||
std::fs::write(path, value).with_context(|| format!("failed to write {}", path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn ensure_linux_ipv6_forwarding_at_paths(
|
||||
all_path: &Path,
|
||||
default_path: &Path,
|
||||
) -> Result<bool, Error> {
|
||||
let all_enabled = read_linux_proc_bool(all_path)?;
|
||||
let default_enabled = read_linux_proc_bool(default_path)?;
|
||||
let mut changed = false;
|
||||
|
||||
if !all_enabled {
|
||||
write_linux_proc_bool(all_path, true)?;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if !default_enabled {
|
||||
write_linux_proc_bool(default_path, true)?;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if !read_linux_proc_bool(all_path)? || !read_linux_proc_bool(default_path)? {
|
||||
return Err(anyhow::anyhow!(
|
||||
"failed to enable Linux IPv6 forwarding in {} and {}",
|
||||
all_path.display(),
|
||||
default_path.display()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn ensure_linux_ipv6_forwarding() -> Result<bool, Error> {
|
||||
let all_path = Path::new("/proc/sys/net/ipv6/conf/all/forwarding");
|
||||
let default_path = Path::new("/proc/sys/net/ipv6/conf/default/forwarding");
|
||||
|
||||
ensure_linux_ipv6_forwarding_at_paths(all_path, default_path).map_err(|err| {
|
||||
anyhow::anyhow!(
|
||||
"public IPv6 provider requires Linux IPv6 forwarding; failed to enable net.ipv6.conf.all.forwarding=1 and net.ipv6.conf.default.forwarding=1 automatically: {}. run with sufficient privileges or set them manually",
|
||||
err
|
||||
)
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct DetectedIpv6Route {
|
||||
dst: Option<Ipv6Cidr>,
|
||||
src: Option<Ipv6Cidr>,
|
||||
ifindex: Option<u32>,
|
||||
kind: RouteType,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn ipv6_cidr_from_route_addr(addr: RouteAddress, prefix_len: u8) -> Option<Ipv6Cidr> {
|
||||
match addr {
|
||||
RouteAddress::Inet6(addr) => Ipv6Cidr::new(addr, prefix_len).ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl TryFrom<RouteMessage> for DetectedIpv6Route {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(message: RouteMessage) -> Result<Self, Self::Error> {
|
||||
let dst = message.attributes.iter().find_map(|attr| match attr {
|
||||
RouteAttribute::Destination(addr) => {
|
||||
ipv6_cidr_from_route_addr(addr.clone(), message.header.destination_prefix_length)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let src = message.attributes.iter().find_map(|attr| match attr {
|
||||
RouteAttribute::Source(addr) => {
|
||||
ipv6_cidr_from_route_addr(addr.clone(), message.header.source_prefix_length)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
let ifindex = message.attributes.iter().find_map(|attr| match attr {
|
||||
RouteAttribute::Oif(index) => Some(*index),
|
||||
_ => None,
|
||||
});
|
||||
|
||||
Ok(Self {
|
||||
dst,
|
||||
src,
|
||||
ifindex,
|
||||
kind: message.header.kind,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn is_ipv6_default_route(dst: Option<Ipv6Cidr>) -> bool {
|
||||
dst.is_none() || dst == Some(Ipv6Cidr::new(std::net::Ipv6Addr::UNSPECIFIED, 0).unwrap())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn detect_public_ipv6_prefix_from_routes(
|
||||
routes: &[DetectedIpv6Route],
|
||||
loopback_ifindex: u32,
|
||||
) -> Option<Ipv6Cidr> {
|
||||
routes
|
||||
.iter()
|
||||
.filter_map(|route| {
|
||||
if !is_ipv6_default_route(route.dst) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let prefix = route.src?;
|
||||
let wan_ifindex = route.ifindex?;
|
||||
if !is_global_routable_public_ipv6_prefix(prefix) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let delegated = routes.iter().any(|candidate| {
|
||||
candidate.dst == Some(prefix)
|
||||
&& candidate.ifindex.is_some()
|
||||
&& candidate.ifindex != Some(wan_ifindex)
|
||||
&& candidate.ifindex != Some(loopback_ifindex)
|
||||
&& candidate.kind == RouteType::Unicast
|
||||
});
|
||||
|
||||
delegated.then_some(prefix)
|
||||
})
|
||||
.min_by_key(|prefix| prefix.network_length())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
async fn detect_public_ipv6_prefix_linux() -> Result<Option<Ipv6Cidr>, Error> {
|
||||
let routes = list_ipv6_route_messages().with_context(|| "failed to query linux ipv6 routes")?;
|
||||
let routes = routes
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(DetectedIpv6Route::try_from)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let loopback_ifindex =
|
||||
get_interface_index("lo").with_context(|| "failed to resolve linux loopback ifindex")?;
|
||||
|
||||
Ok(detect_public_ipv6_prefix_from_routes(
|
||||
&routes,
|
||||
loopback_ifindex,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
async fn detect_public_ipv6_prefix_linux() -> Result<Option<Ipv6Cidr>, Error> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn invalid_public_ipv6_prefix_state(
|
||||
prefix: Ipv6Cidr,
|
||||
source: &str,
|
||||
) -> PublicIpv6ProviderRuntimeState {
|
||||
PublicIpv6ProviderRuntimeState::Pending(format!(
|
||||
"the {} prefix {} is not a valid global unicast IPv6 prefix",
|
||||
source, prefix
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
async fn resolve_public_ipv6_provider_runtime_state_linux(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
configured_prefix: Option<Ipv6Cidr>,
|
||||
) -> PublicIpv6ProviderRuntimeState {
|
||||
let _g = global_ctx.net_ns.guard();
|
||||
|
||||
if let Err(err) = ensure_linux_ipv6_forwarding() {
|
||||
return PublicIpv6ProviderRuntimeState::Pending(err.to_string());
|
||||
}
|
||||
|
||||
if let Some(prefix) = configured_prefix {
|
||||
if !is_global_routable_public_ipv6_prefix(prefix) {
|
||||
return invalid_public_ipv6_prefix_state(prefix, "configured");
|
||||
}
|
||||
return PublicIpv6ProviderRuntimeState::Active(prefix);
|
||||
}
|
||||
|
||||
match detect_public_ipv6_prefix_linux().await {
|
||||
Ok(Some(prefix)) if is_global_routable_public_ipv6_prefix(prefix) => {
|
||||
PublicIpv6ProviderRuntimeState::Active(prefix)
|
||||
}
|
||||
Ok(Some(prefix)) => invalid_public_ipv6_prefix_state(prefix, "detected"),
|
||||
Ok(None) => PublicIpv6ProviderRuntimeState::Pending(
|
||||
public_ipv6_provider_auto_detect_error().to_string(),
|
||||
),
|
||||
Err(err) => PublicIpv6ProviderRuntimeState::Pending(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_public_ipv6_provider_runtime_state(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
config: PublicIpv6ProviderConfigSnapshot,
|
||||
) -> PublicIpv6ProviderRuntimeState {
|
||||
if !config.provider_enabled {
|
||||
return PublicIpv6ProviderRuntimeState::Disabled;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
return resolve_public_ipv6_provider_runtime_state_linux(
|
||||
global_ctx,
|
||||
config.configured_prefix,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = config.configured_prefix;
|
||||
PublicIpv6ProviderRuntimeState::Pending(
|
||||
ensure_public_ipv6_provider_supported()
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_public_ipv6_provider_runtime_state(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
state: &PublicIpv6ProviderRuntimeState,
|
||||
) -> bool {
|
||||
let next_prefix = match state {
|
||||
PublicIpv6ProviderRuntimeState::Active(prefix) => Some(*prefix),
|
||||
PublicIpv6ProviderRuntimeState::Disabled | PublicIpv6ProviderRuntimeState::Pending(_) => {
|
||||
None
|
||||
}
|
||||
};
|
||||
let prefix_changed = global_ctx.set_advertised_ipv6_public_addr_prefix(next_prefix);
|
||||
|
||||
let next_provider_enabled = matches!(state, PublicIpv6ProviderRuntimeState::Active(_));
|
||||
let feature_changed = {
|
||||
let mut feature_flags = global_ctx.get_feature_flags();
|
||||
if feature_flags.ipv6_public_addr_provider == next_provider_enabled {
|
||||
false
|
||||
} else {
|
||||
feature_flags.ipv6_public_addr_provider = next_provider_enabled;
|
||||
global_ctx.set_feature_flags(feature_flags);
|
||||
true
|
||||
}
|
||||
};
|
||||
|
||||
prefix_changed || feature_changed
|
||||
}
|
||||
|
||||
fn try_apply_public_ipv6_provider_runtime_state(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
config: PublicIpv6ProviderConfigSnapshot,
|
||||
state: &PublicIpv6ProviderRuntimeState,
|
||||
) -> Option<bool> {
|
||||
(read_public_ipv6_provider_config_snapshot(global_ctx) == config)
|
||||
.then(|| apply_public_ipv6_provider_runtime_state(global_ctx, state))
|
||||
}
|
||||
|
||||
fn current_public_ipv6_provider_runtime_state(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
) -> PublicIpv6ProviderRuntimeState {
|
||||
match (
|
||||
global_ctx.get_feature_flags().ipv6_public_addr_provider,
|
||||
global_ctx.get_advertised_ipv6_public_addr_prefix(),
|
||||
) {
|
||||
(false, _) => PublicIpv6ProviderRuntimeState::Disabled,
|
||||
(true, Some(prefix)) => PublicIpv6ProviderRuntimeState::Active(prefix),
|
||||
(true, None) => PublicIpv6ProviderRuntimeState::Pending(
|
||||
"public IPv6 provider runtime is missing an advertised prefix".to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
async fn reconcile_public_ipv6_provider_runtime_with_state(
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
) -> (PublicIpv6ProviderRuntimeState, bool) {
|
||||
for attempt in 0..PUBLIC_IPV6_PROVIDER_RECONCILE_MAX_RETRIES {
|
||||
let config = read_public_ipv6_provider_config_snapshot(global_ctx);
|
||||
let next_state = resolve_public_ipv6_provider_runtime_state(global_ctx, config).await;
|
||||
|
||||
if let Some(changed) =
|
||||
try_apply_public_ipv6_provider_runtime_state(global_ctx, config, &next_state)
|
||||
{
|
||||
return (next_state, changed);
|
||||
}
|
||||
|
||||
tracing::debug!(
|
||||
attempt = attempt + 1,
|
||||
max_retries = PUBLIC_IPV6_PROVIDER_RECONCILE_MAX_RETRIES,
|
||||
"public IPv6 provider config changed during reconcile, retrying"
|
||||
);
|
||||
}
|
||||
|
||||
tracing::warn!(
|
||||
max_retries = PUBLIC_IPV6_PROVIDER_RECONCILE_MAX_RETRIES,
|
||||
"skipping public IPv6 provider reconcile because config kept changing"
|
||||
);
|
||||
(
|
||||
current_public_ipv6_provider_runtime_state(global_ctx),
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn reconcile_public_ipv6_provider_runtime(global_ctx: &ArcGlobalCtx) -> bool {
|
||||
reconcile_public_ipv6_provider_runtime_with_state(global_ctx)
|
||||
.await
|
||||
.1
|
||||
}
|
||||
|
||||
pub(super) fn run_public_ipv6_provider_reconcile_task(global_ctx: &ArcGlobalCtx) {
|
||||
if !should_run_public_ipv6_provider_reconcile_task(read_public_ipv6_provider_config_snapshot(
|
||||
global_ctx,
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let global_ctx = Arc::downgrade(global_ctx);
|
||||
tokio::spawn(async move {
|
||||
let Some(initial_ctx) = global_ctx.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let mut event_receiver = initial_ctx.subscribe();
|
||||
let mut last_state: Option<PublicIpv6ProviderRuntimeState> = None;
|
||||
|
||||
loop {
|
||||
let Some(global_ctx) = global_ctx.upgrade() else {
|
||||
tracing::debug!("global ctx dropped, stopping public ipv6 provider reconcile");
|
||||
return;
|
||||
};
|
||||
|
||||
let (next_state, changed) =
|
||||
reconcile_public_ipv6_provider_runtime_with_state(&global_ctx).await;
|
||||
if last_state.as_ref() != Some(&next_state) {
|
||||
match &next_state {
|
||||
PublicIpv6ProviderRuntimeState::Disabled if last_state.is_some() => {
|
||||
tracing::info!("public IPv6 provider disabled");
|
||||
}
|
||||
PublicIpv6ProviderRuntimeState::Disabled => {}
|
||||
PublicIpv6ProviderRuntimeState::Pending(reason) => {
|
||||
tracing::warn!(reason = %reason, "public IPv6 provider not ready");
|
||||
}
|
||||
PublicIpv6ProviderRuntimeState::Active(prefix) => {
|
||||
tracing::info!(prefix = %prefix, "public IPv6 provider is active");
|
||||
}
|
||||
}
|
||||
} else if changed {
|
||||
tracing::info!("public IPv6 provider runtime state changed");
|
||||
}
|
||||
last_state = Some(next_state);
|
||||
|
||||
if matches!(
|
||||
last_state.as_ref(),
|
||||
Some(PublicIpv6ProviderRuntimeState::Disabled)
|
||||
) {
|
||||
match event_receiver.recv().await {
|
||||
Ok(GlobalCtxEvent::ConfigPatched(_)) => {}
|
||||
Ok(_) => {}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
|
||||
event_receiver = event_receiver.resubscribe();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tokio::select! {
|
||||
recv = event_receiver.recv() => match recv {
|
||||
Ok(GlobalCtxEvent::ConfigPatched(_)) => {}
|
||||
Ok(_) => {}
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
|
||||
event_receiver = event_receiver.resubscribe();
|
||||
}
|
||||
},
|
||||
_ = tokio::time::sleep(PUBLIC_IPV6_PROVIDER_RECONCILE_INTERVAL) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::fs;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::path::PathBuf;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use netlink_packet_route::route::RouteType;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
use super::{
|
||||
DetectedIpv6Route, detect_public_ipv6_prefix_from_routes, detect_public_ipv6_prefix_linux,
|
||||
ensure_linux_ipv6_forwarding_at_paths, ensure_public_ipv6_provider_supported,
|
||||
public_ipv6_provider_auto_detect_error,
|
||||
};
|
||||
|
||||
use super::{
|
||||
PublicIpv6ProviderConfigSnapshot, PublicIpv6ProviderRuntimeState,
|
||||
read_public_ipv6_provider_config_snapshot, should_run_public_ipv6_provider_reconcile_task,
|
||||
try_apply_public_ipv6_provider_runtime_state,
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
use super::{ensure_public_ipv6_provider_supported, public_ipv6_provider_auto_detect_error};
|
||||
use crate::common::{
|
||||
config::{ConfigLoader, TomlConfigLoader},
|
||||
global_ctx::GlobalCtx,
|
||||
};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn run_ip(args: &[&str]) {
|
||||
let output = Command::new("ip")
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("failed to execute ip process");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"ip command failed: {:?}\nstdout: {}\nstderr: {}",
|
||||
args,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn test_iface_name(tag: &str) -> String {
|
||||
format!("et{}{:x}", tag, std::process::id() & 0xffff)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
struct ScopedDummyLink {
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl ScopedDummyLink {
|
||||
fn new(name: &str) -> Self {
|
||||
let _ = Command::new("ip").args(["link", "del", name]).output();
|
||||
run_ip(&["link", "add", name, "type", "dummy"]);
|
||||
run_ip(&["link", "set", name, "up"]);
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Drop for ScopedDummyLink {
|
||||
fn drop(&mut self) {
|
||||
let _ = Command::new("ip")
|
||||
.args(["link", "del", &self.name])
|
||||
.output();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn temp_forwarding_paths(
|
||||
all_value: &str,
|
||||
default_value: &str,
|
||||
) -> (tempfile::TempDir, PathBuf, PathBuf) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let all_path = dir.path().join("all_forwarding");
|
||||
let default_path = dir.path().join("default_forwarding");
|
||||
fs::write(&all_path, all_value).unwrap();
|
||||
fs::write(&default_path, default_value).unwrap();
|
||||
(dir, all_path, default_path)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn route(
|
||||
dst: Option<&str>,
|
||||
src: Option<&str>,
|
||||
ifindex: Option<u32>,
|
||||
kind: RouteType,
|
||||
) -> DetectedIpv6Route {
|
||||
DetectedIpv6Route {
|
||||
dst: dst.map(|cidr| cidr.parse().unwrap()),
|
||||
src: src.map(|cidr| cidr.parse().unwrap()),
|
||||
ifindex,
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_detect_public_ipv6_prefix_from_routes_selects_delegated_prefix() {
|
||||
let routes = vec![
|
||||
route(None, Some("2001:db8:1::/56"), Some(2), RouteType::Unicast),
|
||||
route(Some("2001:db8:1::/56"), None, Some(3), RouteType::Unicast),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
detect_public_ipv6_prefix_from_routes(&routes, 1),
|
||||
Some("2001:db8:1::/56".parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_detect_public_ipv6_prefix_from_routes_rejects_non_public_prefixes() {
|
||||
let routes = vec![
|
||||
route(Some("::/0"), Some("fd00::/48"), Some(2), RouteType::Unicast),
|
||||
route(Some("fd00::/48"), None, Some(3), RouteType::Unicast),
|
||||
route(None, Some("fe80::/64"), Some(4), RouteType::Unicast),
|
||||
route(Some("fe80::/64"), None, Some(5), RouteType::Unicast),
|
||||
route(None, Some("ff00::/8"), Some(6), RouteType::Unicast),
|
||||
route(Some("ff00::/8"), None, Some(7), RouteType::Unicast),
|
||||
route(None, Some("::/0"), Some(8), RouteType::Unicast),
|
||||
route(Some("::/0"), None, Some(9), RouteType::Unicast),
|
||||
];
|
||||
|
||||
assert_eq!(detect_public_ipv6_prefix_from_routes(&routes, 1), None);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_detect_public_ipv6_prefix_from_routes_requires_delegated_route() {
|
||||
let routes = vec![route(
|
||||
None,
|
||||
Some("2001:db8:1::/56"),
|
||||
Some(2),
|
||||
RouteType::Unicast,
|
||||
)];
|
||||
|
||||
assert_eq!(detect_public_ipv6_prefix_from_routes(&routes, 1), None);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_detect_public_ipv6_prefix_from_routes_rejects_loopback_delegation() {
|
||||
let routes = vec![
|
||||
route(None, Some("2001:db8:1::/56"), Some(2), RouteType::Unicast),
|
||||
route(Some("2001:db8:1::/56"), None, Some(1), RouteType::Unicast),
|
||||
];
|
||||
|
||||
assert_eq!(detect_public_ipv6_prefix_from_routes(&routes, 1), None);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_detect_public_ipv6_prefix_from_routes_prefers_shortest_prefix() {
|
||||
let routes = vec![
|
||||
route(None, Some("2001:db8:1::/56"), Some(2), RouteType::Unicast),
|
||||
route(Some("2001:db8:1::/56"), None, Some(3), RouteType::Unicast),
|
||||
route(None, Some("2001:db8::/48"), Some(4), RouteType::Unicast),
|
||||
route(Some("2001:db8::/48"), None, Some(5), RouteType::Unicast),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
detect_public_ipv6_prefix_from_routes(&routes, 1),
|
||||
Some("2001:db8::/48".parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_detect_public_ipv6_prefix_from_routes_rejects_non_unicast_delegation() {
|
||||
let routes = vec![
|
||||
route(None, Some("2001:db8:1::/56"), Some(2), RouteType::Unicast),
|
||||
route(Some("2001:db8:1::/56"), None, Some(3), RouteType::BlackHole),
|
||||
];
|
||||
|
||||
assert_eq!(detect_public_ipv6_prefix_from_routes(&routes, 1), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_public_ipv6_provider_auto_detect_error_mentions_manual_prefix() {
|
||||
let err = public_ipv6_provider_auto_detect_error();
|
||||
let msg = err.to_string();
|
||||
|
||||
assert!(msg.contains("IPv6 prefix"), "{}", msg);
|
||||
assert!(msg.contains("ipv6-public-addr-prefix"), "{}", msg);
|
||||
}
|
||||
|
||||
fn test_global_ctx() -> Arc<GlobalCtx> {
|
||||
Arc::new(GlobalCtx::new(TomlConfigLoader::default()))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_read_public_ipv6_provider_config_snapshot_reads_provider_fields() {
|
||||
let global_ctx = test_global_ctx();
|
||||
let prefix = "2001:db8::/48".parse().unwrap();
|
||||
global_ctx.config.set_ipv6_public_addr_provider(true);
|
||||
global_ctx.config.set_ipv6_public_addr_prefix(Some(prefix));
|
||||
|
||||
assert_eq!(
|
||||
read_public_ipv6_provider_config_snapshot(&global_ctx),
|
||||
PublicIpv6ProviderConfigSnapshot {
|
||||
provider_enabled: true,
|
||||
configured_prefix: Some(prefix),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reconcile_task_only_runs_for_auto_detect_provider() {
|
||||
assert!(!should_run_public_ipv6_provider_reconcile_task(
|
||||
PublicIpv6ProviderConfigSnapshot {
|
||||
provider_enabled: false,
|
||||
configured_prefix: None,
|
||||
}
|
||||
));
|
||||
assert!(!should_run_public_ipv6_provider_reconcile_task(
|
||||
PublicIpv6ProviderConfigSnapshot {
|
||||
provider_enabled: true,
|
||||
configured_prefix: Some("2001:db8::/48".parse().unwrap()),
|
||||
}
|
||||
));
|
||||
assert!(should_run_public_ipv6_provider_reconcile_task(
|
||||
PublicIpv6ProviderConfigSnapshot {
|
||||
provider_enabled: true,
|
||||
configured_prefix: None,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_try_apply_public_ipv6_provider_runtime_state_rejects_stale_config() {
|
||||
let global_ctx = test_global_ctx();
|
||||
let prefix = "2001:db8::/48".parse().unwrap();
|
||||
let config = PublicIpv6ProviderConfigSnapshot {
|
||||
provider_enabled: true,
|
||||
configured_prefix: Some(prefix),
|
||||
};
|
||||
|
||||
global_ctx.config.set_ipv6_public_addr_provider(false);
|
||||
global_ctx.config.set_ipv6_public_addr_prefix(None);
|
||||
|
||||
let changed = try_apply_public_ipv6_provider_runtime_state(
|
||||
&global_ctx,
|
||||
config,
|
||||
&PublicIpv6ProviderRuntimeState::Active(prefix),
|
||||
);
|
||||
|
||||
assert_eq!(changed, None);
|
||||
assert_eq!(global_ctx.get_advertised_ipv6_public_addr_prefix(), None);
|
||||
assert!(!global_ctx.get_feature_flags().ipv6_public_addr_provider);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_try_apply_public_ipv6_provider_runtime_state_applies_matching_config() {
|
||||
let global_ctx = test_global_ctx();
|
||||
let prefix = "2001:db8::/48".parse().unwrap();
|
||||
global_ctx.config.set_ipv6_public_addr_provider(true);
|
||||
global_ctx.config.set_ipv6_public_addr_prefix(Some(prefix));
|
||||
let config = read_public_ipv6_provider_config_snapshot(&global_ctx);
|
||||
|
||||
let changed = try_apply_public_ipv6_provider_runtime_state(
|
||||
&global_ctx,
|
||||
config,
|
||||
&PublicIpv6ProviderRuntimeState::Active(prefix),
|
||||
);
|
||||
|
||||
assert_eq!(changed, Some(true));
|
||||
assert_eq!(
|
||||
global_ctx.get_advertised_ipv6_public_addr_prefix(),
|
||||
Some(prefix)
|
||||
);
|
||||
assert!(global_ctx.get_feature_flags().ipv6_public_addr_provider);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_public_ipv6_provider_platform_check_accepts_linux() {
|
||||
assert!(ensure_public_ipv6_provider_supported().is_ok());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_ensure_linux_ipv6_forwarding_enables_all_and_default() {
|
||||
let (_dir, all_path, default_path) = temp_forwarding_paths("0\n", "0\n");
|
||||
|
||||
let changed = ensure_linux_ipv6_forwarding_at_paths(&all_path, &default_path).unwrap();
|
||||
|
||||
assert!(changed);
|
||||
assert_eq!(fs::read_to_string(&all_path).unwrap(), "1\n");
|
||||
assert_eq!(fs::read_to_string(&default_path).unwrap(), "1\n");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn test_ensure_linux_ipv6_forwarding_is_noop_when_already_enabled() {
|
||||
let (_dir, all_path, default_path) = temp_forwarding_paths("1\n", "1\n");
|
||||
|
||||
let changed = ensure_linux_ipv6_forwarding_at_paths(&all_path, &default_path).unwrap();
|
||||
|
||||
assert!(!changed);
|
||||
assert_eq!(fs::read_to_string(&all_path).unwrap(), "1\n");
|
||||
assert_eq!(fs::read_to_string(&default_path).unwrap(), "1\n");
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
#[test]
|
||||
fn test_public_ipv6_provider_platform_check_reports_linux_only() {
|
||||
let err = ensure_public_ipv6_provider_supported().unwrap_err();
|
||||
let msg = err.to_string();
|
||||
|
||||
assert!(msg.contains("Linux"), "{}", msg);
|
||||
assert!(msg.contains("ipv6-public-addr-auto"), "{}", msg);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[serial_test::serial]
|
||||
#[tokio::test]
|
||||
async fn test_detect_public_ipv6_prefix_linux_reads_netlink_routes_from_kernel() {
|
||||
let wan_if = test_iface_name("dw");
|
||||
let lan_if = test_iface_name("dl");
|
||||
let _wan = ScopedDummyLink::new(&wan_if);
|
||||
let _lan = ScopedDummyLink::new(&lan_if);
|
||||
|
||||
run_ip(&[
|
||||
"-6",
|
||||
"addr",
|
||||
"add",
|
||||
"2001:db8:100:ffff::1/64",
|
||||
"dev",
|
||||
&wan_if,
|
||||
]);
|
||||
run_ip(&[
|
||||
"-6",
|
||||
"route",
|
||||
"add",
|
||||
"default",
|
||||
"from",
|
||||
"2001:db8:100::/56",
|
||||
"dev",
|
||||
&wan_if,
|
||||
]);
|
||||
run_ip(&["-6", "route", "add", "2001:db8:100::/56", "dev", &lan_if]);
|
||||
|
||||
assert_eq!(
|
||||
detect_public_ipv6_prefix_linux().await.unwrap(),
|
||||
Some("2001:db8:100::/56".parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[serial_test::serial]
|
||||
#[tokio::test]
|
||||
async fn test_detect_public_ipv6_prefix_linux_prefers_shortest_prefix_from_kernel() {
|
||||
let wan_if_1 = test_iface_name("sw1");
|
||||
let lan_if_1 = test_iface_name("sl1");
|
||||
let wan_if_2 = test_iface_name("sw2");
|
||||
let lan_if_2 = test_iface_name("sl2");
|
||||
let _wan_1 = ScopedDummyLink::new(&wan_if_1);
|
||||
let _lan_1 = ScopedDummyLink::new(&lan_if_1);
|
||||
let _wan_2 = ScopedDummyLink::new(&wan_if_2);
|
||||
let _lan_2 = ScopedDummyLink::new(&lan_if_2);
|
||||
|
||||
run_ip(&[
|
||||
"-6",
|
||||
"addr",
|
||||
"add",
|
||||
"2001:db8:3000:ffff::1/64",
|
||||
"dev",
|
||||
&wan_if_1,
|
||||
]);
|
||||
run_ip(&[
|
||||
"-6",
|
||||
"route",
|
||||
"add",
|
||||
"default",
|
||||
"from",
|
||||
"2001:db8:3000::/56",
|
||||
"dev",
|
||||
&wan_if_1,
|
||||
]);
|
||||
run_ip(&["-6", "route", "add", "2001:db8:3000::/56", "dev", &lan_if_1]);
|
||||
|
||||
run_ip(&["-6", "addr", "add", "2001:db9:ffff::1/64", "dev", &wan_if_2]);
|
||||
run_ip(&[
|
||||
"-6",
|
||||
"route",
|
||||
"add",
|
||||
"default",
|
||||
"from",
|
||||
"2001:db9::/48",
|
||||
"dev",
|
||||
&wan_if_2,
|
||||
]);
|
||||
run_ip(&["-6", "route", "add", "2001:db9::/48", "dev", &lan_if_2]);
|
||||
|
||||
assert_eq!(
|
||||
detect_public_ipv6_prefix_linux().await.unwrap(),
|
||||
Some("2001:db9::/48".parse().unwrap())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -735,9 +735,26 @@ impl VirtualNic {
|
||||
}
|
||||
|
||||
pub async fn add_ipv6_route(&self, address: Ipv6Addr, cidr: u8) -> Result<(), Error> {
|
||||
self.add_ipv6_route_with_cost(address, cidr, None).await
|
||||
}
|
||||
|
||||
pub async fn add_ipv6_route_with_cost(
|
||||
&self,
|
||||
address: Ipv6Addr,
|
||||
cidr: u8,
|
||||
cost: Option<i32>,
|
||||
) -> Result<(), Error> {
|
||||
let _g = self.global_ctx.net_ns.guard();
|
||||
self.ifcfg
|
||||
.add_ipv6_route(self.ifname(), address, cidr, None)
|
||||
.add_ipv6_route(self.ifname(), address, cidr, cost)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn remove_ipv6_route(&self, address: Ipv6Addr, cidr: u8) -> Result<(), Error> {
|
||||
let _g = self.global_ctx.net_ns.guard();
|
||||
self.ifcfg
|
||||
.remove_ipv6_route(self.ifname(), address, cidr)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -903,7 +920,7 @@ impl NicCtx {
|
||||
}
|
||||
let src_ipv6 = ipv6.get_source();
|
||||
let dst_ipv6 = ipv6.get_destination();
|
||||
let my_ipv6 = mgr.get_global_ctx().get_ipv6().map(|x| x.address());
|
||||
let is_local_src = mgr.get_global_ctx().is_ip_local_ipv6(&src_ipv6);
|
||||
tracing::trace!(
|
||||
?ret,
|
||||
?src_ipv6,
|
||||
@@ -911,14 +928,14 @@ impl NicCtx {
|
||||
"[USER_PACKET] recv new packet from tun device and forward to peers."
|
||||
);
|
||||
|
||||
if src_ipv6.is_unicast_link_local() && Some(src_ipv6) != my_ipv6 {
|
||||
if src_ipv6.is_unicast_link_local() && !is_local_src {
|
||||
// do not route link local packet to other nodes unless the address is assigned by user
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: use zero-copy
|
||||
let send_ret = mgr
|
||||
.send_msg_by_ip(ret, IpAddr::V6(dst_ipv6), Some(src_ipv6) == my_ipv6)
|
||||
.send_msg_by_ip(ret, IpAddr::V6(dst_ipv6), is_local_src)
|
||||
.await;
|
||||
if send_ret.is_err() {
|
||||
tracing::trace!(?send_ret, "[USER_PACKET] send_msg failed")
|
||||
@@ -1039,6 +1056,44 @@ impl NicCtx {
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply_public_ipv6_route_changes(
|
||||
ifcfg: &impl IfConfiguerTrait,
|
||||
ifname: &str,
|
||||
net_ns: &crate::common::netns::NetNS,
|
||||
cur_routes: &mut BTreeSet<cidr::Ipv6Inet>,
|
||||
added: Vec<cidr::Ipv6Inet>,
|
||||
removed: Vec<cidr::Ipv6Inet>,
|
||||
) {
|
||||
for route in removed {
|
||||
if !cur_routes.contains(&route) {
|
||||
continue;
|
||||
}
|
||||
let _g = net_ns.guard();
|
||||
let ret = ifcfg
|
||||
.remove_ipv6_route(ifname, route.address(), route.network_length())
|
||||
.await;
|
||||
if ret.is_err() {
|
||||
tracing::trace!(route = ?route, err = ?ret, "remove public ipv6 route failed");
|
||||
}
|
||||
cur_routes.remove(&route);
|
||||
}
|
||||
|
||||
for route in added {
|
||||
if cur_routes.contains(&route) {
|
||||
continue;
|
||||
}
|
||||
let _g = net_ns.guard();
|
||||
let ret = ifcfg
|
||||
.add_ipv6_route(ifname, route.address(), route.network_length(), None)
|
||||
.await;
|
||||
if ret.is_err() {
|
||||
tracing::trace!(route = ?route, err = ?ret, "add public ipv6 route failed");
|
||||
} else {
|
||||
cur_routes.insert(route);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_proxy_cidrs_route_updater(&mut self) -> Result<(), Error> {
|
||||
let Some(peer_mgr) = self.peer_mgr.upgrade() else {
|
||||
return Err(anyhow::anyhow!("peer manager not available").into());
|
||||
@@ -1114,6 +1169,137 @@ impl NicCtx {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_public_ipv6_route_updater(&mut self) -> Result<(), Error> {
|
||||
let Some(peer_mgr) = self.peer_mgr.upgrade() else {
|
||||
return Err(anyhow::anyhow!("peer manager not available").into());
|
||||
};
|
||||
let global_ctx = self.global_ctx.clone();
|
||||
let net_ns = self.global_ctx.net_ns.clone();
|
||||
let nic = self.nic.lock().await;
|
||||
let ifcfg = nic.get_ifcfg();
|
||||
let ifname = nic.ifname().to_owned();
|
||||
let mut event_receiver = global_ctx.subscribe();
|
||||
|
||||
self.tasks.spawn(async move {
|
||||
let mut cur_routes = BTreeSet::<cidr::Ipv6Inet>::new();
|
||||
let initial_routes = peer_mgr.list_public_ipv6_routes().await;
|
||||
let initial_added = initial_routes.iter().copied().collect::<Vec<_>>();
|
||||
Self::apply_public_ipv6_route_changes(
|
||||
&ifcfg,
|
||||
&ifname,
|
||||
&net_ns,
|
||||
&mut cur_routes,
|
||||
initial_added,
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
|
||||
loop {
|
||||
let event = match event_receiver.recv().await {
|
||||
Ok(event) => event,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
|
||||
event_receiver = event_receiver.resubscribe();
|
||||
let latest = peer_mgr.list_public_ipv6_routes().await;
|
||||
let added = latest.difference(&cur_routes).copied().collect::<Vec<_>>();
|
||||
let removed = cur_routes.difference(&latest).copied().collect::<Vec<_>>();
|
||||
GlobalCtxEvent::PublicIpv6RoutesUpdated(added, removed)
|
||||
}
|
||||
};
|
||||
|
||||
let (added, removed) = match event {
|
||||
GlobalCtxEvent::PublicIpv6RoutesUpdated(added, removed) => (added, removed),
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
Self::apply_public_ipv6_route_changes(
|
||||
&ifcfg,
|
||||
&ifname,
|
||||
&net_ns,
|
||||
&mut cur_routes,
|
||||
added,
|
||||
removed,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_public_ipv6_addr_updater(&mut self) -> Result<(), Error> {
|
||||
let Some(peer_mgr) = self.peer_mgr.upgrade() else {
|
||||
return Err(anyhow::anyhow!("peer manager not available").into());
|
||||
};
|
||||
let global_ctx = self.global_ctx.clone();
|
||||
let nic = self.nic.clone();
|
||||
let mut event_receiver = global_ctx.subscribe();
|
||||
|
||||
self.tasks.spawn(async move {
|
||||
let mut current_addr = peer_mgr.get_my_public_ipv6_addr().await;
|
||||
if let Some(addr) = current_addr {
|
||||
let nic = nic.lock().await;
|
||||
if let Err(err) = nic.link_up().await {
|
||||
tracing::warn!(?err, "failed to bring public ipv6 nic link up");
|
||||
}
|
||||
if let Err(err) = nic.add_ipv6(addr.address(), addr.network_length() as i32).await {
|
||||
tracing::warn!(addr = ?addr, ?err, "failed to add public ipv6 address");
|
||||
}
|
||||
if let Err(err) = nic
|
||||
.add_ipv6_route_with_cost(Ipv6Addr::UNSPECIFIED, 0, Some(5))
|
||||
.await
|
||||
{
|
||||
tracing::warn!(route = %Ipv6Addr::UNSPECIFIED, prefix = 0, ?err, "failed to add default public ipv6 route");
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
let event = match event_receiver.recv().await {
|
||||
Ok(event) => event,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
|
||||
event_receiver = event_receiver.resubscribe();
|
||||
let latest = peer_mgr.get_my_public_ipv6_addr().await;
|
||||
GlobalCtxEvent::PublicIpv6Changed(current_addr, latest)
|
||||
}
|
||||
};
|
||||
|
||||
let (old, new) = match event {
|
||||
GlobalCtxEvent::PublicIpv6Changed(old, new) => (old, new),
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
current_addr = new;
|
||||
let nic = nic.lock().await;
|
||||
if let Err(err) = nic.link_up().await {
|
||||
tracing::warn!(?err, "failed to bring public ipv6 nic link up");
|
||||
}
|
||||
if let Some(old) = old {
|
||||
if let Err(err) = nic.remove_ipv6_route(Ipv6Addr::UNSPECIFIED, 0).await {
|
||||
tracing::warn!(route = %Ipv6Addr::UNSPECIFIED, prefix = 0, ?err, "failed to remove default public ipv6 route");
|
||||
}
|
||||
if let Err(err) = nic.remove_ipv6(Some(old)).await {
|
||||
tracing::warn!(addr = ?old, ?err, "failed to remove old public ipv6 address");
|
||||
}
|
||||
}
|
||||
if let Some(new) = new {
|
||||
if let Err(err) = nic.add_ipv6(new.address(), new.network_length() as i32).await
|
||||
{
|
||||
tracing::warn!(addr = ?new, ?err, "failed to add public ipv6 address");
|
||||
}
|
||||
if let Err(err) = nic
|
||||
.add_ipv6_route_with_cost(Ipv6Addr::UNSPECIFIED, 0, Some(5))
|
||||
.await
|
||||
{
|
||||
tracing::warn!(route = %Ipv6Addr::UNSPECIFIED, prefix = 0, ?err, "failed to add default public ipv6 route");
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run(
|
||||
&mut self,
|
||||
ipv4_addr: Option<cidr::Ipv4Inet>,
|
||||
@@ -1169,6 +1355,10 @@ impl NicCtx {
|
||||
}
|
||||
|
||||
self.run_proxy_cidrs_route_updater().await?;
|
||||
self.run_public_ipv6_route_updater().await?;
|
||||
// Keep the updater running so runtime config patches can enable auto mode
|
||||
// without recreating the NIC.
|
||||
self.run_public_ipv6_addr_updater().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -435,6 +435,20 @@ fn handle_event(
|
||||
event!(info, ?ip, "[{}] dhcp ip conflict", instance_id);
|
||||
}
|
||||
|
||||
GlobalCtxEvent::PublicIpv6Changed(old, new) => {
|
||||
event!(info, ?old, ?new, "[{}] public ipv6 changed", instance_id);
|
||||
}
|
||||
|
||||
GlobalCtxEvent::PublicIpv6RoutesUpdated(added, removed) => {
|
||||
event!(
|
||||
info,
|
||||
?added,
|
||||
?removed,
|
||||
"[{}] public ipv6 routes updated",
|
||||
instance_id
|
||||
);
|
||||
}
|
||||
|
||||
GlobalCtxEvent::PortForwardAdded(cfg) => {
|
||||
event!(
|
||||
info,
|
||||
|
||||
@@ -714,6 +714,24 @@ impl NetworkConfig {
|
||||
flags.use_smoltcp = use_smoltcp;
|
||||
}
|
||||
|
||||
if let Some(ipv6_public_addr_provider) = self.ipv6_public_addr_provider {
|
||||
cfg.set_ipv6_public_addr_provider(ipv6_public_addr_provider);
|
||||
}
|
||||
|
||||
if let Some(ipv6_public_addr_auto) = self.ipv6_public_addr_auto {
|
||||
cfg.set_ipv6_public_addr_auto(ipv6_public_addr_auto);
|
||||
}
|
||||
|
||||
if let Some(ipv6_public_addr_prefix) = self
|
||||
.ipv6_public_addr_prefix
|
||||
.as_ref()
|
||||
.filter(|prefix| !prefix.is_empty())
|
||||
{
|
||||
cfg.set_ipv6_public_addr_prefix(Some(ipv6_public_addr_prefix.parse().with_context(
|
||||
|| format!("failed to parse ipv6 public address prefix: {ipv6_public_addr_prefix}"),
|
||||
)?));
|
||||
}
|
||||
|
||||
if let Some(disable_ipv6) = self.disable_ipv6 {
|
||||
flags.enable_ipv6 = !disable_ipv6;
|
||||
}
|
||||
@@ -863,6 +881,17 @@ impl NetworkConfig {
|
||||
result.network_length = Some(ipv4.network_length() as i32);
|
||||
}
|
||||
|
||||
if config.get_ipv6_public_addr_provider() != default_config.get_ipv6_public_addr_provider()
|
||||
{
|
||||
result.ipv6_public_addr_provider = Some(config.get_ipv6_public_addr_provider());
|
||||
}
|
||||
if config.get_ipv6_public_addr_auto() != default_config.get_ipv6_public_addr_auto() {
|
||||
result.ipv6_public_addr_auto = Some(config.get_ipv6_public_addr_auto());
|
||||
}
|
||||
result.ipv6_public_addr_prefix = config
|
||||
.get_ipv6_public_addr_prefix()
|
||||
.map(|prefix| prefix.to_string());
|
||||
|
||||
let peers = config.get_peers();
|
||||
result.networking_method = Some(NetworkingMethod::Manual as i32);
|
||||
if !peers.is_empty() {
|
||||
|
||||
@@ -94,6 +94,8 @@ impl AclFilter {
|
||||
/// Preserves connection tracking and rate limiting state across reloads
|
||||
/// Now lock-free and doesn't require &mut self!
|
||||
pub fn reload_rules(&self, acl_config: Option<&Acl>) {
|
||||
self.outbound_allow_records.clear();
|
||||
|
||||
let Some(acl_config) = acl_config else {
|
||||
self.acl_enabled.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
@@ -292,13 +294,33 @@ impl AclFilter {
|
||||
processor.increment_stat(AclStatKey::PacketsTotal);
|
||||
}
|
||||
|
||||
fn classify_chain_type(
|
||||
is_in: bool,
|
||||
packet_info: &PacketInfo,
|
||||
my_ipv4: Option<Ipv4Addr>,
|
||||
is_local_ipv6: impl Fn(Ipv6Addr) -> bool,
|
||||
) -> ChainType {
|
||||
if !is_in {
|
||||
return ChainType::Outbound;
|
||||
}
|
||||
|
||||
let is_local_dst = packet_info.dst_ip == my_ipv4.unwrap_or(Ipv4Addr::UNSPECIFIED)
|
||||
|| matches!(packet_info.dst_ip, IpAddr::V6(dst) if is_local_ipv6(dst));
|
||||
|
||||
if is_local_dst {
|
||||
ChainType::Inbound
|
||||
} else {
|
||||
ChainType::Forward
|
||||
}
|
||||
}
|
||||
|
||||
/// Common ACL processing logic
|
||||
pub fn process_packet_with_acl(
|
||||
&self,
|
||||
packet: &ZCPacket,
|
||||
is_in: bool,
|
||||
my_ipv4: Option<Ipv4Addr>,
|
||||
my_ipv6: Option<Ipv6Addr>,
|
||||
is_local_ipv6: impl Fn(Ipv6Addr) -> bool,
|
||||
route: &(dyn super::route_trait::Route + Send + Sync + 'static),
|
||||
) -> bool {
|
||||
if !self.acl_enabled.load(Ordering::Relaxed) {
|
||||
@@ -323,17 +345,7 @@ impl AclFilter {
|
||||
}
|
||||
};
|
||||
|
||||
let chain_type = if is_in {
|
||||
if packet_info.dst_ip == my_ipv4.unwrap_or(Ipv4Addr::UNSPECIFIED)
|
||||
|| packet_info.dst_ip == my_ipv6.unwrap_or(Ipv6Addr::UNSPECIFIED)
|
||||
{
|
||||
ChainType::Inbound
|
||||
} else {
|
||||
ChainType::Forward
|
||||
}
|
||||
} else {
|
||||
ChainType::Outbound
|
||||
};
|
||||
let chain_type = Self::classify_chain_type(is_in, &packet_info, my_ipv4, is_local_ipv6);
|
||||
|
||||
// Get current processor atomically
|
||||
let processor = self.get_processor();
|
||||
@@ -384,3 +396,92 @@ impl AclFilter {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr},
|
||||
sync::Arc,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
common::acl_processor::PacketInfo,
|
||||
proto::acl::{Acl, ChainType, Protocol},
|
||||
};
|
||||
|
||||
use super::{AclFilter, OutboundAllowRecord};
|
||||
|
||||
fn packet_info(dst_ip: IpAddr) -> PacketInfo {
|
||||
PacketInfo {
|
||||
src_ip: IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
|
||||
dst_ip,
|
||||
src_port: Some(1234),
|
||||
dst_port: Some(80),
|
||||
protocol: Protocol::Tcp,
|
||||
packet_size: 64,
|
||||
src_groups: Arc::new(Vec::new()),
|
||||
dst_groups: Arc::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classify_chain_type_treats_public_ipv6_lease_as_inbound() {
|
||||
let leased_ipv6 = Ipv6Addr::new(0x2001, 0xdb8, 0x100, 0, 0, 0, 0, 0x123);
|
||||
let packet_info = packet_info(IpAddr::V6(leased_ipv6));
|
||||
|
||||
let chain =
|
||||
AclFilter::classify_chain_type(true, &packet_info, None, |ip| ip == leased_ipv6);
|
||||
|
||||
assert_eq!(chain, ChainType::Inbound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classify_chain_type_keeps_non_local_ipv6_as_forward() {
|
||||
let leased_ipv6 = Ipv6Addr::new(0x2001, 0xdb8, 0x100, 0, 0, 0, 0, 0x123);
|
||||
let packet_info = packet_info(IpAddr::V6(Ipv6Addr::new(
|
||||
0x2001, 0xdb8, 0xffff, 2, 0, 0, 0, 0x100,
|
||||
)));
|
||||
|
||||
let chain =
|
||||
AclFilter::classify_chain_type(true, &packet_info, None, |ip| ip == leased_ipv6);
|
||||
|
||||
assert_eq!(chain, ChainType::Forward);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reload_rules_clears_outbound_allow_records() {
|
||||
let filter = AclFilter::new();
|
||||
filter.outbound_allow_records.insert(
|
||||
OutboundAllowRecord {
|
||||
src_ip: IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
|
||||
dst_ip: IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)),
|
||||
src_port: Some(1234),
|
||||
dst_port: Some(80),
|
||||
protocol: Protocol::Tcp,
|
||||
},
|
||||
Instant::now(),
|
||||
);
|
||||
assert_eq!(filter.outbound_allow_records.len(), 1);
|
||||
|
||||
filter.reload_rules(Some(&Acl::default()));
|
||||
|
||||
assert_eq!(filter.outbound_allow_records.len(), 0);
|
||||
|
||||
filter.outbound_allow_records.insert(
|
||||
OutboundAllowRecord {
|
||||
src_ip: IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)),
|
||||
dst_ip: IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
|
||||
src_port: Some(4321),
|
||||
dst_port: Some(443),
|
||||
protocol: Protocol::Tcp,
|
||||
},
|
||||
Instant::now(),
|
||||
);
|
||||
assert_eq!(filter.outbound_allow_records.len(), 1);
|
||||
|
||||
filter.reload_rules(None);
|
||||
|
||||
assert_eq!(filter.outbound_allow_records.len(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod peer_ospf_route;
|
||||
pub mod peer_rpc;
|
||||
pub mod peer_rpc_service;
|
||||
pub mod peer_session;
|
||||
pub(crate) mod public_ipv6;
|
||||
pub mod relay_peer_map;
|
||||
pub mod route_trait;
|
||||
pub mod rpc_service;
|
||||
|
||||
@@ -12,6 +12,7 @@ use std::{
|
||||
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use guarden::guard;
|
||||
use hmac::Mac;
|
||||
use prost::Message;
|
||||
|
||||
@@ -40,7 +41,6 @@ use crate::{
|
||||
error::Error,
|
||||
global_ctx::ArcGlobalCtx,
|
||||
},
|
||||
guard,
|
||||
peers::peer_session::{PeerSessionStore, SessionKey, UpsertResponderSessionReturn},
|
||||
proto::{
|
||||
api::instance::{PeerConnInfo, PeerConnStats},
|
||||
|
||||
@@ -1062,7 +1062,7 @@ impl PeerManager {
|
||||
&ret,
|
||||
true,
|
||||
global_ctx.get_ipv4().map(|x| x.address()),
|
||||
global_ctx.get_ipv6().map(|x| x.address()),
|
||||
|dst| global_ctx.is_ip_local_ipv6(&dst),
|
||||
&route,
|
||||
) {
|
||||
continue;
|
||||
@@ -1291,6 +1291,18 @@ impl PeerManager {
|
||||
self.get_route().list_proxy_cidrs_v6().await
|
||||
}
|
||||
|
||||
pub async fn list_public_ipv6_routes(&self) -> BTreeSet<cidr::Ipv6Inet> {
|
||||
self.get_route().list_public_ipv6_routes().await
|
||||
}
|
||||
|
||||
pub async fn get_my_public_ipv6_addr(&self) -> Option<cidr::Ipv6Inet> {
|
||||
self.get_route().get_my_public_ipv6_addr().await
|
||||
}
|
||||
|
||||
pub async fn get_local_public_ipv6_info(&self) -> instance::ListPublicIpv6InfoResponse {
|
||||
self.get_route().get_local_public_ipv6_info().await
|
||||
}
|
||||
|
||||
pub async fn dump_route(&self) -> String {
|
||||
self.get_route().dump().await
|
||||
}
|
||||
@@ -1330,7 +1342,7 @@ impl PeerManager {
|
||||
data,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
|_| false,
|
||||
&self.get_route(),
|
||||
) {
|
||||
return false;
|
||||
@@ -1532,6 +1544,10 @@ impl PeerManager {
|
||||
dst_peers.extend(self.peers.list_routes().await.iter().map(|x| *x.key()));
|
||||
} else if let Some(peer_id) = self.peers.get_peer_id_by_ipv6(ipv6_addr).await {
|
||||
dst_peers.push(peer_id);
|
||||
} else if !ipv6_addr.is_unicast_link_local()
|
||||
&& let Some(peer_id) = self.get_route().get_public_ipv6_gateway_peer_id().await
|
||||
{
|
||||
dst_peers.push(peer_id);
|
||||
} else if !ipv6_addr.is_unicast_link_local() {
|
||||
// NOTE: never route link local address to exit node.
|
||||
for exit_node in self.exit_nodes.read().await.iter() {
|
||||
@@ -1662,7 +1678,7 @@ impl PeerManager {
|
||||
&& !self.global_ctx.is_ip_local_virtual_ip(&ip_addr)
|
||||
{
|
||||
// Keep the loop-prevention flags for proxy-induced self-delivery where
|
||||
// the destination is not this node's own virtual IP.
|
||||
// the destination is not this node's own EasyTier-managed IP.
|
||||
hdr.set_not_send_to_tun(true);
|
||||
hdr.set_no_proxy(true);
|
||||
}
|
||||
@@ -1879,6 +1895,15 @@ impl PeerManager {
|
||||
version: EASYTIER_VERSION.to_string(),
|
||||
feature_flag: Some(self.global_ctx.get_feature_flags()),
|
||||
ip_list: Some(self.global_ctx.get_ip_collector().collect_ip_addrs().await),
|
||||
public_ipv6_addr: self.get_my_public_ipv6_addr().await.map(Into::into),
|
||||
ipv6_public_addr_prefix: self
|
||||
.global_ctx
|
||||
.get_advertised_ipv6_public_addr_prefix()
|
||||
.map(|prefix| {
|
||||
cidr::Ipv6Inet::new(prefix.first_address(), prefix.network_length())
|
||||
.unwrap()
|
||||
.into()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::{
|
||||
};
|
||||
|
||||
use arc_swap::ArcSwap;
|
||||
use cidr::{IpCidr, Ipv4Cidr, Ipv6Cidr};
|
||||
use cidr::{IpCidr, Ipv4Cidr, Ipv6Cidr, Ipv6Inet};
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
use dashmap::DashMap;
|
||||
use ordered_hash_map::OrderedHashMap;
|
||||
@@ -46,9 +46,10 @@ use crate::{
|
||||
peer_rpc::{
|
||||
ForeignNetworkRouteInfoEntry, ForeignNetworkRouteInfoKey, OspfRouteRpc,
|
||||
OspfRouteRpcClientFactory, OspfRouteRpcServer, PeerGroupInfo, PeerIdVersion,
|
||||
PeerIdentityType, RouteForeignNetworkInfos, RouteForeignNetworkSummary, RoutePeerInfo,
|
||||
RoutePeerInfos, SyncRouteInfoError, SyncRouteInfoRequest, SyncRouteInfoResponse,
|
||||
TrustedCredentialPubkey, TrustedCredentialPubkeyProof, route_foreign_network_infos,
|
||||
PeerIdentityType, PublicIpv6AddrRpcServer, RouteForeignNetworkInfos,
|
||||
RouteForeignNetworkSummary, RoutePeerInfo, RoutePeerInfos, SyncRouteInfoError,
|
||||
SyncRouteInfoRequest, SyncRouteInfoResponse, TrustedCredentialPubkey,
|
||||
TrustedCredentialPubkeyProof, route_foreign_network_infos,
|
||||
route_foreign_network_summary, sync_route_info_request::ConnInfo,
|
||||
},
|
||||
rpc_types::{
|
||||
@@ -63,6 +64,9 @@ use super::{
|
||||
PeerPacketFilter,
|
||||
graph_algo::dijkstra_with_first_hop,
|
||||
peer_rpc::PeerRpcManager,
|
||||
public_ipv6::{
|
||||
PublicIpv6PeerRouteInfo, PublicIpv6RouteControl, PublicIpv6Service, PublicIpv6SyncTrigger,
|
||||
},
|
||||
route_trait::{
|
||||
DefaultRouteCostCalculator, ForeignNetworkRouteInfoMap, NextHopPolicy, RouteCostCalculator,
|
||||
RouteCostCalculatorInterface,
|
||||
@@ -137,6 +141,10 @@ fn raw_credential_bytes_from_route_info(
|
||||
.map(|credential| credential.encode_to_vec())
|
||||
}
|
||||
|
||||
fn route_peer_inst_id(info: &RoutePeerInfo) -> Option<uuid::Uuid> {
|
||||
info.inst_id.map(Into::into)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct AtomicVersion(Arc<AtomicU32>);
|
||||
|
||||
@@ -205,6 +213,8 @@ impl RoutePeerInfo {
|
||||
quic_port: None,
|
||||
noise_static_pubkey: Vec::new(),
|
||||
trusted_credential_pubkeys: Vec::new(),
|
||||
ipv6_public_addr_prefix: None,
|
||||
ipv6_public_addr_lease: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,6 +231,7 @@ impl RoutePeerInfo {
|
||||
my_peer_id: PeerId,
|
||||
peer_route_id: u64,
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
public_ipv6_addr_lease: Option<Ipv6Inet>,
|
||||
) -> Self {
|
||||
let stun_info = global_ctx.get_stun_info_collector().get_stun_info();
|
||||
let noise_static_pubkey = global_ctx
|
||||
@@ -259,6 +270,14 @@ impl RoutePeerInfo {
|
||||
.unwrap_or(24),
|
||||
|
||||
ipv6_addr: global_ctx.get_ipv6().map(|x| x.into()),
|
||||
ipv6_public_addr_prefix: global_ctx.get_advertised_ipv6_public_addr_prefix().map(
|
||||
|prefix| {
|
||||
Ipv6Inet::new(prefix.first_address(), prefix.network_length())
|
||||
.unwrap()
|
||||
.into()
|
||||
},
|
||||
),
|
||||
ipv6_public_addr_lease: public_ipv6_addr_lease.map(Into::into),
|
||||
|
||||
groups: global_ctx.get_acl_groups(my_peer_id),
|
||||
|
||||
@@ -349,6 +368,8 @@ impl From<RoutePeerInfo> for crate::proto::api::instance::Route {
|
||||
path_latency_latency_first: None,
|
||||
|
||||
ipv6_addr: val.ipv6_addr,
|
||||
public_ipv6_addr: val.ipv6_public_addr_lease,
|
||||
ipv6_public_addr_prefix: val.ipv6_public_addr_prefix,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -964,8 +985,14 @@ impl SyncedRouteInfo {
|
||||
my_peer_id: PeerId,
|
||||
my_peer_route_id: u64,
|
||||
global_ctx: &ArcGlobalCtx,
|
||||
public_ipv6_addr_lease: Option<Ipv6Inet>,
|
||||
) -> bool {
|
||||
let mut new = RoutePeerInfo::new_updated_self(my_peer_id, my_peer_route_id, global_ctx);
|
||||
let mut new = RoutePeerInfo::new_updated_self(
|
||||
my_peer_id,
|
||||
my_peer_route_id,
|
||||
global_ctx,
|
||||
public_ipv6_addr_lease,
|
||||
);
|
||||
let mut guard = self.peer_infos.upgradable_read();
|
||||
let old = guard.get(&my_peer_id);
|
||||
let new_version = old.map(|x| x.version).unwrap_or(0) + 1;
|
||||
@@ -1588,6 +1615,21 @@ impl RouteTable {
|
||||
.or_insert(peer_id_and_version);
|
||||
}
|
||||
|
||||
if let Some(ipv6_addr) = info
|
||||
.ipv6_public_addr_lease
|
||||
.as_ref()
|
||||
.and_then(|addr| addr.address)
|
||||
{
|
||||
self.ipv6_peer_id_map
|
||||
.entry(ipv6_addr.into())
|
||||
.and_modify(|v| {
|
||||
if is_new_peer_better(v) {
|
||||
*v = peer_id_and_version;
|
||||
}
|
||||
})
|
||||
.or_insert(peer_id_and_version);
|
||||
}
|
||||
|
||||
for cidr in info.proxy_cidrs.iter() {
|
||||
let Ok(cidr) = cidr.parse::<IpCidr>() else {
|
||||
tracing::warn!("invalid proxy cidr: {:?}, from peer: {:?}", cidr, peer_id);
|
||||
@@ -2019,6 +2061,8 @@ struct PeerRouteServiceImpl {
|
||||
foreign_network_owner_map: DashMap<NetworkIdentity, Vec<PeerId>>,
|
||||
foreign_network_my_peer_id_map: DashMap<(String, PeerId), PeerId>,
|
||||
synced_route_info: SyncedRouteInfo,
|
||||
public_ipv6_service: std::sync::Mutex<Weak<PublicIpv6Service>>,
|
||||
self_public_ipv6_addr_lease: std::sync::Mutex<Option<Ipv6Inet>>,
|
||||
cached_local_conn_map: std::sync::Mutex<RouteConnBitmap>,
|
||||
cached_local_conn_map_version: AtomicVersion,
|
||||
cached_interface_peer_snapshot: std::sync::Mutex<Arc<InterfacePeerSnapshot>>,
|
||||
@@ -2081,6 +2125,8 @@ impl PeerRouteServiceImpl {
|
||||
non_reusable_credential_owners: DashMap::new(),
|
||||
version: AtomicVersion::new(),
|
||||
},
|
||||
public_ipv6_service: std::sync::Mutex::new(Weak::new()),
|
||||
self_public_ipv6_addr_lease: std::sync::Mutex::new(None),
|
||||
cached_local_conn_map: std::sync::Mutex::new(RouteConnBitmap::default()),
|
||||
cached_local_conn_map_version: AtomicVersion::new(),
|
||||
cached_interface_peer_snapshot: std::sync::Mutex::new(Arc::new(
|
||||
@@ -2119,6 +2165,20 @@ impl PeerRouteServiceImpl {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn set_public_ipv6_service(&self, service: Weak<PublicIpv6Service>) {
|
||||
*self.public_ipv6_service.lock().unwrap() = service;
|
||||
}
|
||||
|
||||
fn public_ipv6_service(&self) -> Option<Arc<PublicIpv6Service>> {
|
||||
self.public_ipv6_service.lock().unwrap().upgrade()
|
||||
}
|
||||
|
||||
fn notify_public_ipv6_route_change(&self) -> bool {
|
||||
self.public_ipv6_service()
|
||||
.map(|service| service.handle_route_change())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn get_or_create_session(&self, dst_peer_id: PeerId) -> Arc<SyncRouteSession> {
|
||||
self.sessions
|
||||
.entry(dst_peer_id)
|
||||
@@ -2230,6 +2290,7 @@ impl PeerRouteServiceImpl {
|
||||
self.my_peer_id,
|
||||
self.my_peer_route_id,
|
||||
&self.global_ctx,
|
||||
*self.self_public_ipv6_addr_lease.lock().unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2618,14 +2679,19 @@ impl PeerRouteServiceImpl {
|
||||
untrusted_changed = self.refresh_credential_trusts_and_disconnect().await;
|
||||
}
|
||||
|
||||
let mut public_ipv6_state_updated = false;
|
||||
if my_peer_info_updated || my_conn_info_updated || untrusted_changed {
|
||||
self.update_route_table_and_cached_local_conn_bitmap();
|
||||
self.update_foreign_network_owner_map();
|
||||
public_ipv6_state_updated = self.notify_public_ipv6_route_change();
|
||||
}
|
||||
if my_peer_info_updated {
|
||||
self.update_peer_info_last_update();
|
||||
}
|
||||
my_peer_info_updated || my_conn_info_updated || my_foreign_network_updated
|
||||
my_peer_info_updated
|
||||
|| my_conn_info_updated
|
||||
|| my_foreign_network_updated
|
||||
|| public_ipv6_state_updated
|
||||
}
|
||||
|
||||
async fn refresh_acl_groups(&self) -> bool {
|
||||
@@ -2652,15 +2718,17 @@ impl PeerRouteServiceImpl {
|
||||
let untrusted = self.refresh_credential_trusts_with_current_topology();
|
||||
self.disconnect_untrusted_peers(&untrusted).await;
|
||||
|
||||
let mut public_ipv6_state_updated = false;
|
||||
if my_peer_info_updated || !untrusted.is_empty() {
|
||||
self.update_route_table_and_cached_local_conn_bitmap();
|
||||
self.update_foreign_network_owner_map();
|
||||
public_ipv6_state_updated = self.notify_public_ipv6_route_change();
|
||||
}
|
||||
if my_peer_info_updated {
|
||||
self.update_peer_info_last_update();
|
||||
}
|
||||
|
||||
my_peer_info_updated || !untrusted.is_empty()
|
||||
my_peer_info_updated || !untrusted.is_empty() || public_ipv6_state_updated
|
||||
}
|
||||
|
||||
fn refresh_credential_trusts(&self) -> Vec<PeerId> {
|
||||
@@ -2968,7 +3036,6 @@ impl PeerRouteServiceImpl {
|
||||
session
|
||||
.update_dst_saved_foreign_network_version(foreign_network, dst_peer_id);
|
||||
}
|
||||
|
||||
session.update_last_sync_succ_timestamp(next_last_sync_succ_timestamp);
|
||||
}
|
||||
}
|
||||
@@ -3493,7 +3560,13 @@ impl RouteSessionManager {
|
||||
}
|
||||
|
||||
if need_update_route_table || foreign_network_changed {
|
||||
service_impl.update_route_table_and_cached_local_conn_bitmap();
|
||||
service_impl.update_foreign_network_owner_map();
|
||||
if need_update_route_table
|
||||
&& let Some(public_ipv6_service) = service_impl.public_ipv6_service()
|
||||
{
|
||||
public_ipv6_service.handle_route_change();
|
||||
}
|
||||
}
|
||||
|
||||
tracing::debug!(
|
||||
@@ -3534,12 +3607,86 @@ impl RouteSessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
struct OspfPublicIpv6RouteHandle {
|
||||
service_impl: Weak<PeerRouteServiceImpl>,
|
||||
}
|
||||
|
||||
impl PublicIpv6RouteControl for OspfPublicIpv6RouteHandle {
|
||||
fn my_peer_id(&self) -> PeerId {
|
||||
self.service_impl
|
||||
.upgrade()
|
||||
.map(|service_impl| service_impl.my_peer_id)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn peer_route_snapshot(&self) -> Vec<PublicIpv6PeerRouteInfo> {
|
||||
let Some(service_impl) = self.service_impl.upgrade() else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
service_impl
|
||||
.synced_route_info
|
||||
.peer_infos
|
||||
.read()
|
||||
.iter()
|
||||
.map(|(peer_id, info)| PublicIpv6PeerRouteInfo {
|
||||
peer_id: *peer_id,
|
||||
inst_id: route_peer_inst_id(info),
|
||||
is_provider: info
|
||||
.feature_flag
|
||||
.as_ref()
|
||||
.map(|flags| flags.ipv6_public_addr_provider)
|
||||
.unwrap_or(false),
|
||||
prefix: info
|
||||
.ipv6_public_addr_prefix
|
||||
.map(Into::into)
|
||||
.map(|prefix: Ipv6Inet| prefix.network()),
|
||||
lease: info.ipv6_public_addr_lease.map(Into::into),
|
||||
reachable: *peer_id == service_impl.my_peer_id
|
||||
|| service_impl.route_table.peer_reachable(*peer_id),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn publish_self_public_ipv6_lease(&self, lease: Option<Ipv6Inet>) -> bool {
|
||||
let Some(service_impl) = self.service_impl.upgrade() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let mut current = service_impl.self_public_ipv6_addr_lease.lock().unwrap();
|
||||
if *current == lease {
|
||||
return false;
|
||||
}
|
||||
*current = lease;
|
||||
drop(current);
|
||||
|
||||
let changed = service_impl.update_my_peer_info();
|
||||
if changed {
|
||||
service_impl.update_route_table_and_cached_local_conn_bitmap();
|
||||
service_impl.update_foreign_network_owner_map();
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct OspfPublicIpv6SyncTrigger {
|
||||
session_mgr: RouteSessionManager,
|
||||
}
|
||||
|
||||
impl PublicIpv6SyncTrigger for OspfPublicIpv6SyncTrigger {
|
||||
fn sync_now(&self, reason: &str) {
|
||||
self.session_mgr.sync_now(reason);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PeerRoute {
|
||||
my_peer_id: PeerId,
|
||||
global_ctx: ArcGlobalCtx,
|
||||
peer_rpc: Weak<PeerRpcManager>,
|
||||
|
||||
service_impl: Arc<PeerRouteServiceImpl>,
|
||||
public_ipv6_service: Arc<PublicIpv6Service>,
|
||||
session_mgr: RouteSessionManager,
|
||||
|
||||
tasks: std::sync::Mutex<JoinSet<()>>,
|
||||
@@ -3563,6 +3710,17 @@ impl PeerRoute {
|
||||
) -> Arc<Self> {
|
||||
let service_impl = Arc::new(PeerRouteServiceImpl::new(my_peer_id, global_ctx.clone()));
|
||||
let session_mgr = RouteSessionManager::new(service_impl.clone(), peer_rpc.clone());
|
||||
let public_ipv6_service = Arc::new(PublicIpv6Service::new(
|
||||
global_ctx.clone(),
|
||||
Arc::downgrade(&peer_rpc),
|
||||
Arc::new(OspfPublicIpv6RouteHandle {
|
||||
service_impl: Arc::downgrade(&service_impl),
|
||||
}),
|
||||
Arc::new(OspfPublicIpv6SyncTrigger {
|
||||
session_mgr: session_mgr.clone(),
|
||||
}),
|
||||
));
|
||||
service_impl.set_public_ipv6_service(Arc::downgrade(&public_ipv6_service));
|
||||
|
||||
Arc::new(PeerRoute {
|
||||
my_peer_id,
|
||||
@@ -3570,6 +3728,7 @@ impl PeerRoute {
|
||||
peer_rpc: Arc::downgrade(&peer_rpc),
|
||||
|
||||
service_impl,
|
||||
public_ipv6_service,
|
||||
session_mgr,
|
||||
|
||||
tasks: std::sync::Mutex::new(JoinSet::new()),
|
||||
@@ -3607,6 +3766,9 @@ impl PeerRoute {
|
||||
tracing::debug!("cost_calculator_need_update");
|
||||
service_impl.synced_route_info.version.inc();
|
||||
service_impl.update_route_table();
|
||||
if let Some(public_ipv6_service) = service_impl.public_ipv6_service() {
|
||||
public_ipv6_service.handle_route_change();
|
||||
}
|
||||
}
|
||||
|
||||
select! {
|
||||
@@ -3631,11 +3793,16 @@ impl PeerRoute {
|
||||
|
||||
// make sure my_peer_id is in the peer_infos.
|
||||
self.service_impl.update_my_infos().await;
|
||||
self.public_ipv6_service.handle_route_change();
|
||||
|
||||
peer_rpc.rpc_server().registry().register(
|
||||
OspfRouteRpcServer::new(self.session_mgr.clone()),
|
||||
&self.global_ctx.get_network_name(),
|
||||
);
|
||||
peer_rpc.rpc_server().registry().register(
|
||||
PublicIpv6AddrRpcServer::new(self.public_ipv6_service.rpc_server()),
|
||||
&self.global_ctx.get_network_name(),
|
||||
);
|
||||
|
||||
self.tasks
|
||||
.lock()
|
||||
@@ -3657,6 +3824,16 @@ impl PeerRoute {
|
||||
.lock()
|
||||
.unwrap()
|
||||
.spawn(Self::clear_expired_peer(self.service_impl.clone()));
|
||||
|
||||
self.tasks
|
||||
.lock()
|
||||
.unwrap()
|
||||
.spawn(self.public_ipv6_service.clone().provider_gc_routine());
|
||||
|
||||
self.tasks
|
||||
.lock()
|
||||
.unwrap()
|
||||
.spawn(self.public_ipv6_service.clone().client_routine());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3677,6 +3854,10 @@ impl Drop for PeerRoute {
|
||||
OspfRouteRpcServer::new(self.session_mgr.clone()),
|
||||
&self.global_ctx.get_network_name(),
|
||||
);
|
||||
peer_rpc.rpc_server().registry().unregister(
|
||||
PublicIpv6AddrRpcServer::new(self.public_ipv6_service.rpc_server()),
|
||||
&self.global_ctx.get_network_name(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3765,6 +3946,51 @@ impl Route for PeerRoute {
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn list_public_ipv6_routes(&self) -> BTreeSet<Ipv6Inet> {
|
||||
self.public_ipv6_service.list_routes()
|
||||
}
|
||||
|
||||
async fn get_my_public_ipv6_addr(&self) -> Option<Ipv6Inet> {
|
||||
self.public_ipv6_service.my_addr()
|
||||
}
|
||||
|
||||
async fn get_public_ipv6_gateway_peer_id(&self) -> Option<PeerId> {
|
||||
self.public_ipv6_service.provider_peer_id_for_client()
|
||||
}
|
||||
|
||||
async fn get_local_public_ipv6_info(
|
||||
&self,
|
||||
) -> crate::proto::api::instance::ListPublicIpv6InfoResponse {
|
||||
let Some((provider, leases)) = self.public_ipv6_service.local_provider_state() else {
|
||||
return crate::proto::api::instance::ListPublicIpv6InfoResponse::default();
|
||||
};
|
||||
|
||||
crate::proto::api::instance::ListPublicIpv6InfoResponse {
|
||||
provider_prefix: Some(
|
||||
Ipv6Inet::new(
|
||||
provider.prefix.first_address(),
|
||||
provider.prefix.network_length(),
|
||||
)
|
||||
.unwrap()
|
||||
.into(),
|
||||
),
|
||||
provider_leases: leases
|
||||
.into_iter()
|
||||
.map(|lease| crate::proto::api::instance::PublicIpv6LeaseInfo {
|
||||
peer_id: lease.peer_id,
|
||||
inst_id: lease.inst_id.to_string(),
|
||||
leased_addr: Some(lease.addr.into()),
|
||||
valid_until_unix_seconds: lease
|
||||
.valid_until
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i64,
|
||||
reused: lease.reused,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_peer_id_by_ipv4(&self, ipv4_addr: &Ipv4Addr) -> Option<PeerId> {
|
||||
let route_table = &self.service_impl.route_table;
|
||||
if let Some(p) = route_table.ipv4_peer_id_map.get(ipv4_addr) {
|
||||
@@ -5180,6 +5406,7 @@ mod tests {
|
||||
service_impl.my_peer_id,
|
||||
service_impl.my_peer_route_id,
|
||||
&service_impl.global_ctx,
|
||||
None,
|
||||
);
|
||||
let mut self_info = self_info;
|
||||
self_info.version = 1;
|
||||
|
||||
@@ -12,6 +12,22 @@ use crate::{
|
||||
tunnel::udp,
|
||||
};
|
||||
|
||||
fn remove_easytier_managed_ipv6s(ret: &mut GetIpListResponse, global_ctx: &ArcGlobalCtx) {
|
||||
ret.interface_ipv6s.retain(|ip| {
|
||||
let ip = std::net::Ipv6Addr::from(*ip);
|
||||
!global_ctx.is_ip_easytier_managed_ipv6(&ip)
|
||||
});
|
||||
|
||||
if ret
|
||||
.public_ipv6
|
||||
.as_ref()
|
||||
.map(|ip| std::net::Ipv6Addr::from(*ip))
|
||||
.is_some_and(|ip| global_ctx.is_ip_easytier_managed_ipv6(&ip))
|
||||
{
|
||||
ret.public_ipv6 = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DirectConnectorManagerRpcServer {
|
||||
// TODO: this only cache for one src peer, should make it global
|
||||
@@ -36,11 +52,7 @@ impl DirectConnectorRpc for DirectConnectorManagerRpcServer {
|
||||
.chain(self.global_ctx.get_running_listeners())
|
||||
.map(Into::into)
|
||||
.collect();
|
||||
// remove et ipv6 from the interface ipv6 list
|
||||
if let Some(et_ipv6) = self.global_ctx.get_ipv6() {
|
||||
let et_ipv6: crate::proto::common::Ipv6Addr = et_ipv6.address().into();
|
||||
ret.interface_ipv6s.retain(|x| *x != et_ipv6);
|
||||
}
|
||||
remove_easytier_managed_ipv6s(&mut ret, &self.global_ctx);
|
||||
tracing::trace!(
|
||||
"get_ip_list: public_ipv4: {:?}, public_ipv6: {:?}, listeners: {:?}",
|
||||
ret.public_ipv4,
|
||||
@@ -84,3 +96,41 @@ impl DirectConnectorManagerRpcServer {
|
||||
Self { global_ctx }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::{
|
||||
common::global_ctx::tests::get_mock_global_ctx,
|
||||
peers::peer_rpc_service::remove_easytier_managed_ipv6s, proto::peer_rpc::GetIpListResponse,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn get_ip_list_sanitizer_removes_managed_ipv6_from_all_sources() {
|
||||
let global_ctx = get_mock_global_ctx();
|
||||
let virtual_ipv6 = "fd00::1/64".parse().unwrap();
|
||||
let public_ipv6 = "2001:db8::2/128".parse().unwrap();
|
||||
let physical_ipv6: std::net::Ipv6Addr = "2001:db8::3".parse().unwrap();
|
||||
let routed_ipv6: cidr::Ipv6Inet = "2001:db8::4/128".parse().unwrap();
|
||||
global_ctx.set_ipv6(Some(virtual_ipv6));
|
||||
global_ctx.set_public_ipv6_lease(Some(public_ipv6));
|
||||
global_ctx.set_public_ipv6_routes(BTreeSet::from([routed_ipv6]));
|
||||
|
||||
let mut ip_list = GetIpListResponse {
|
||||
public_ipv6: Some(public_ipv6.address().into()),
|
||||
interface_ipv6s: vec![
|
||||
virtual_ipv6.address().into(),
|
||||
public_ipv6.address().into(),
|
||||
routed_ipv6.address().into(),
|
||||
physical_ipv6.into(),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
remove_easytier_managed_ipv6s(&mut ip_list, &global_ctx);
|
||||
|
||||
assert_eq!(ip_list.public_ipv6, None);
|
||||
assert_eq!(ip_list.interface_ipv6s, vec![physical_ipv6.into()]);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,4 @@
|
||||
use cidr::Ipv6Inet;
|
||||
use cidr::{Ipv4Cidr, Ipv6Cidr};
|
||||
use dashmap::DashMap;
|
||||
use std::{
|
||||
@@ -8,9 +9,12 @@ use std::{
|
||||
|
||||
use crate::{
|
||||
common::{PeerId, global_ctx::NetworkIdentity},
|
||||
proto::peer_rpc::{
|
||||
ForeignNetworkRouteInfoEntry, ForeignNetworkRouteInfoKey, PeerIdentityType,
|
||||
RouteForeignNetworkInfos, RouteForeignNetworkSummary, RoutePeerInfo,
|
||||
proto::{
|
||||
api::instance::ListPublicIpv6InfoResponse,
|
||||
peer_rpc::{
|
||||
ForeignNetworkRouteInfoEntry, ForeignNetworkRouteInfoKey, PeerIdentityType,
|
||||
RouteForeignNetworkInfos, RouteForeignNetworkSummary, RoutePeerInfo,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -93,6 +97,22 @@ pub trait Route {
|
||||
// TODO: rewrite route management, remove this
|
||||
async fn list_proxy_cidrs_v6(&self) -> BTreeSet<Ipv6Cidr>;
|
||||
|
||||
async fn list_public_ipv6_routes(&self) -> BTreeSet<Ipv6Inet> {
|
||||
BTreeSet::new()
|
||||
}
|
||||
|
||||
async fn get_my_public_ipv6_addr(&self) -> Option<Ipv6Inet> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn get_public_ipv6_gateway_peer_id(&self) -> Option<PeerId> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn get_local_public_ipv6_info(&self) -> ListPublicIpv6InfoResponse {
|
||||
ListPublicIpv6InfoResponse::default()
|
||||
}
|
||||
|
||||
async fn get_peer_id_by_ipv4(&self, _ipv4: &Ipv4Addr) -> Option<PeerId> {
|
||||
None
|
||||
}
|
||||
@@ -194,6 +214,14 @@ impl Route for MockRoute {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn list_public_ipv6_routes(&self) -> BTreeSet<Ipv6Inet> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn get_my_public_ipv6_addr(&self) -> Option<Ipv6Inet> {
|
||||
panic!("mock route")
|
||||
}
|
||||
|
||||
async fn get_peer_info(&self, _peer_id: PeerId) -> Option<RoutePeerInfo> {
|
||||
panic!("mock route")
|
||||
}
|
||||
|
||||
@@ -13,9 +13,9 @@ use crate::{
|
||||
GetWhitelistRequest, GetWhitelistResponse, ListCredentialsRequest,
|
||||
ListCredentialsResponse, ListForeignNetworkRequest, ListForeignNetworkResponse,
|
||||
ListGlobalForeignNetworkRequest, ListGlobalForeignNetworkResponse, ListPeerRequest,
|
||||
ListPeerResponse, ListRouteRequest, ListRouteResponse, PeerInfo, PeerManageRpc,
|
||||
RevokeCredentialRequest, RevokeCredentialResponse, ShowNodeInfoRequest,
|
||||
ShowNodeInfoResponse,
|
||||
ListPeerResponse, ListPublicIpv6InfoRequest, ListPublicIpv6InfoResponse,
|
||||
ListRouteRequest, ListRouteResponse, PeerInfo, PeerManageRpc, RevokeCredentialRequest,
|
||||
RevokeCredentialResponse, ShowNodeInfoRequest, ShowNodeInfoResponse,
|
||||
},
|
||||
rpc_types::{self, controller::BaseController},
|
||||
},
|
||||
@@ -99,6 +99,16 @@ impl PeerManageRpc for PeerManagerRpcService {
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
async fn list_public_ipv6_info(
|
||||
&self,
|
||||
_: BaseController,
|
||||
_request: ListPublicIpv6InfoRequest,
|
||||
) -> Result<ListPublicIpv6InfoResponse, rpc_types::error::Error> {
|
||||
Ok(weak_upgrade(&self.peer_manager)?
|
||||
.get_local_public_ipv6_info()
|
||||
.await)
|
||||
}
|
||||
|
||||
async fn list_route(
|
||||
&self,
|
||||
_: BaseController,
|
||||
|
||||
@@ -24,6 +24,9 @@ message InstanceConfigPatch {
|
||||
repeated ExitNodePatch exit_nodes = 8;
|
||||
repeated UrlPatch mapped_listeners = 9;
|
||||
repeated UrlPatch connectors = 10;
|
||||
optional bool ipv6_public_addr_provider = 11;
|
||||
optional bool ipv6_public_addr_auto = 12;
|
||||
optional string ipv6_public_addr_prefix = 13;
|
||||
}
|
||||
|
||||
message PortForwardPatch {
|
||||
|
||||
@@ -81,6 +81,8 @@ message Route {
|
||||
optional int32 path_latency_latency_first = 14;
|
||||
|
||||
common.Ipv6Inet ipv6_addr = 15;
|
||||
common.Ipv6Inet public_ipv6_addr = 16;
|
||||
common.Ipv6Inet ipv6_public_addr_prefix = 17;
|
||||
}
|
||||
|
||||
message PeerRoutePair {
|
||||
@@ -100,12 +102,29 @@ message NodeInfo {
|
||||
string version = 9;
|
||||
common.PeerFeatureFlag feature_flag = 10;
|
||||
peer_rpc.GetIpListResponse ip_list = 11;
|
||||
common.Ipv6Inet public_ipv6_addr = 12;
|
||||
common.Ipv6Inet ipv6_public_addr_prefix = 13;
|
||||
}
|
||||
|
||||
message ShowNodeInfoRequest { InstanceIdentifier instance = 1; }
|
||||
|
||||
message ShowNodeInfoResponse { NodeInfo node_info = 1; }
|
||||
|
||||
message PublicIpv6LeaseInfo {
|
||||
uint32 peer_id = 1;
|
||||
string inst_id = 2;
|
||||
common.Ipv6Inet leased_addr = 3;
|
||||
int64 valid_until_unix_seconds = 4;
|
||||
bool reused = 5;
|
||||
}
|
||||
|
||||
message ListPublicIpv6InfoRequest { InstanceIdentifier instance = 1; }
|
||||
|
||||
message ListPublicIpv6InfoResponse {
|
||||
common.Ipv6Inet provider_prefix = 1;
|
||||
repeated PublicIpv6LeaseInfo provider_leases = 2;
|
||||
}
|
||||
|
||||
message ListRouteRequest { InstanceIdentifier instance = 1; }
|
||||
|
||||
message ListRouteResponse { repeated Route routes = 1; }
|
||||
@@ -167,6 +186,8 @@ message GetForeignNetworkSummaryResponse {
|
||||
|
||||
service PeerManageRpc {
|
||||
rpc ListPeer(ListPeerRequest) returns (ListPeerResponse);
|
||||
rpc ListPublicIpv6Info(ListPublicIpv6InfoRequest)
|
||||
returns (ListPublicIpv6InfoResponse);
|
||||
rpc ListRoute(ListRouteRequest) returns (ListRouteResponse);
|
||||
rpc DumpRoute(DumpRouteRequest) returns (DumpRouteResponse);
|
||||
rpc ListForeignNetwork(ListForeignNetworkRequest)
|
||||
|
||||
@@ -96,6 +96,9 @@ message NetworkConfig {
|
||||
optional bool need_p2p = 59;
|
||||
optional uint64 instance_recv_bps_limit = 60;
|
||||
optional bool disable_upnp = 61;
|
||||
optional bool ipv6_public_addr_provider = 62;
|
||||
optional bool ipv6_public_addr_auto = 63;
|
||||
optional string ipv6_public_addr_prefix = 64;
|
||||
}
|
||||
|
||||
message PortForwardConfig {
|
||||
|
||||
@@ -225,6 +225,7 @@ message PeerFeatureFlag {
|
||||
bool is_credential_peer = 8;
|
||||
bool need_p2p = 9;
|
||||
bool disable_p2p = 10;
|
||||
bool ipv6_public_addr_provider = 11;
|
||||
}
|
||||
|
||||
enum SocketType {
|
||||
|
||||
@@ -47,6 +47,9 @@ message RoutePeerInfo {
|
||||
|
||||
// Trusted credential public keys published by admin nodes (holding network_secret)
|
||||
repeated TrustedCredentialPubkeyProof trusted_credential_pubkeys = 19;
|
||||
|
||||
optional common.Ipv6Inet ipv6_public_addr_prefix = 22;
|
||||
optional common.Ipv6Inet ipv6_public_addr_lease = 24;
|
||||
}
|
||||
|
||||
message PeerIdVersion {
|
||||
@@ -133,6 +136,46 @@ service OspfRouteRpc {
|
||||
rpc SyncRouteInfo(SyncRouteInfoRequest) returns (SyncRouteInfoResponse);
|
||||
}
|
||||
|
||||
message AcquireIpv6PublicAddrLeaseRequest {
|
||||
uint32 peer_id = 1;
|
||||
common.UUID inst_id = 2;
|
||||
}
|
||||
|
||||
message RenewIpv6PublicAddrLeaseRequest {
|
||||
uint32 peer_id = 1;
|
||||
common.UUID inst_id = 2;
|
||||
common.Ipv6Inet leased_addr = 3;
|
||||
}
|
||||
|
||||
message ReleaseIpv6PublicAddrLeaseRequest {
|
||||
uint32 peer_id = 1;
|
||||
common.UUID inst_id = 2;
|
||||
}
|
||||
|
||||
message GetIpv6PublicAddrLeaseRequest {
|
||||
uint32 peer_id = 1;
|
||||
common.UUID inst_id = 2;
|
||||
}
|
||||
|
||||
message Ipv6PublicAddrLeaseReply {
|
||||
uint32 provider_peer_id = 1;
|
||||
common.UUID provider_inst_id = 2;
|
||||
common.Ipv6Inet provider_prefix = 3;
|
||||
common.Ipv6Inet leased_addr = 4;
|
||||
google.protobuf.Timestamp valid_until = 5;
|
||||
bool reused = 6;
|
||||
optional string error_msg = 7;
|
||||
}
|
||||
|
||||
service PublicIpv6AddrRpc {
|
||||
rpc AcquireLease(AcquireIpv6PublicAddrLeaseRequest)
|
||||
returns (Ipv6PublicAddrLeaseReply);
|
||||
rpc RenewLease(RenewIpv6PublicAddrLeaseRequest)
|
||||
returns (Ipv6PublicAddrLeaseReply);
|
||||
rpc ReleaseLease(ReleaseIpv6PublicAddrLeaseRequest) returns (common.Void);
|
||||
rpc GetLease(GetIpv6PublicAddrLeaseRequest) returns (Ipv6PublicAddrLeaseReply);
|
||||
}
|
||||
|
||||
message GetIpListRequest {}
|
||||
|
||||
message GetIpListResponse {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use std::sync::{Arc, Mutex, atomic::AtomicBool};
|
||||
|
||||
use futures::{SinkExt as _, StreamExt};
|
||||
use guarden::defer;
|
||||
use tokio::{task::JoinSet, time::timeout};
|
||||
|
||||
use crate::{
|
||||
defer,
|
||||
proto::rpc_types::error::Error,
|
||||
tunnel::{Tunnel, packet_def::PacketType, ring::create_ring_tunnel_pair},
|
||||
};
|
||||
|
||||
@@ -4,18 +4,17 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use bytes::Bytes;
|
||||
use dashmap::DashMap;
|
||||
use guarden::defer;
|
||||
use prost::Message;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::timeout;
|
||||
use tokio_stream::StreamExt;
|
||||
|
||||
use crate::common::shrink_dashmap;
|
||||
use crate::common::{
|
||||
PeerId,
|
||||
PeerId, shrink_dashmap,
|
||||
stats_manager::{LabelSet, LabelType, MetricName, StatsManager},
|
||||
};
|
||||
use crate::defer;
|
||||
use crate::proto::common::{
|
||||
CompressionAlgoPb, RpcCompressionInfo, RpcDescriptor, RpcPacket, RpcRequest, RpcResponse,
|
||||
};
|
||||
|
||||
@@ -3,7 +3,10 @@ use std::sync::Arc;
|
||||
use crate::{
|
||||
instance_manager::NetworkInstanceManager,
|
||||
proto::{
|
||||
api::instance::{self, ListPeerRequest, ListPeerResponse, PeerManageRpc},
|
||||
api::instance::{
|
||||
self, ListPeerRequest, ListPeerResponse, ListPublicIpv6InfoRequest,
|
||||
ListPublicIpv6InfoResponse, PeerManageRpc,
|
||||
},
|
||||
rpc_types::controller::BaseController,
|
||||
},
|
||||
};
|
||||
@@ -34,6 +37,17 @@ impl PeerManageRpc for PeerManageRpcService {
|
||||
.await
|
||||
}
|
||||
|
||||
async fn list_public_ipv6_info(
|
||||
&self,
|
||||
ctrl: Self::Controller,
|
||||
req: ListPublicIpv6InfoRequest,
|
||||
) -> crate::proto::rpc_types::error::Result<ListPublicIpv6InfoResponse> {
|
||||
super::get_instance_service(&self.instance_manager, &req.instance)?
|
||||
.get_peer_manage_service()
|
||||
.list_public_ipv6_info(ctrl, req)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn list_route(
|
||||
&self,
|
||||
ctrl: Self::Controller,
|
||||
|
||||
@@ -38,7 +38,7 @@ async fn test_route_peer_info_ipv6() {
|
||||
global_ctx.set_ipv6(Some(ipv6_cidr));
|
||||
|
||||
// Create RoutePeerInfo with IPv6 support
|
||||
let updated_info = RoutePeerInfo::new_updated_self(123, 456, &global_ctx);
|
||||
let updated_info = RoutePeerInfo::new_updated_self(123, 456, &global_ctx, None);
|
||||
|
||||
// Verify IPv6 address is included
|
||||
assert!(updated_info.ipv6_addr.is_some());
|
||||
|
||||
@@ -402,6 +402,528 @@ async fn ping6_test(from_netns: &str, target_ip: &str, payload_size: Option<usiz
|
||||
code.code().unwrap() == 0
|
||||
}
|
||||
|
||||
fn run_cmd(program: &str, args: &[&str]) {
|
||||
let output = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{} {:?} failed: stdout={}, stderr={}",
|
||||
program,
|
||||
args,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
fn run_cmd_output(program: &str, args: &[&str]) -> String {
|
||||
let output = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{} {:?} failed: stdout={}, stderr={}",
|
||||
program,
|
||||
args,
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8(output.stdout).unwrap()
|
||||
}
|
||||
|
||||
fn run_ip(args: &[&str]) {
|
||||
run_cmd("ip", args);
|
||||
}
|
||||
|
||||
fn run_ip_in_ns(ns: &str, args: &[&str]) {
|
||||
let mut cmd = vec!["netns", "exec", ns, "ip"];
|
||||
cmd.extend_from_slice(args);
|
||||
run_cmd("ip", &cmd);
|
||||
}
|
||||
|
||||
fn run_ip_in_ns_output(ns: &str, args: &[&str]) -> String {
|
||||
let mut cmd = vec!["netns", "exec", ns, "ip"];
|
||||
cmd.extend_from_slice(args);
|
||||
run_cmd_output("ip", &cmd)
|
||||
}
|
||||
|
||||
fn run_sysctl_in_ns(ns: &str, assignment: &str) {
|
||||
run_cmd("ip", &["netns", "exec", ns, "sysctl", "-qw", assignment]);
|
||||
}
|
||||
|
||||
fn create_empty_netns(name: &str) {
|
||||
del_netns(name);
|
||||
run_ip(&["netns", "add", name]);
|
||||
run_ip(&["netns", "exec", name, "ip", "link", "set", "lo", "up"]);
|
||||
}
|
||||
|
||||
fn connect_ns_to_bridge(ns: &str, guest_if: &str, host_if: &str, bridge: &str) {
|
||||
let _ = std::process::Command::new("ip")
|
||||
.args(["link", "del", host_if])
|
||||
.status();
|
||||
run_ip(&[
|
||||
"link", "add", host_if, "type", "veth", "peer", "name", guest_if,
|
||||
]);
|
||||
run_ip(&["link", "set", guest_if, "netns", ns]);
|
||||
run_ip(&["link", "set", host_if, "up"]);
|
||||
run_cmd("brctl", &["addif", bridge, host_if]);
|
||||
run_ip(&["netns", "exec", ns, "ip", "link", "set", guest_if, "up"]);
|
||||
}
|
||||
|
||||
struct PublicIpv6Lab {
|
||||
extra_namespaces: [&'static str; 2],
|
||||
extra_bridges: [&'static str; 2],
|
||||
}
|
||||
|
||||
impl PublicIpv6Lab {
|
||||
const PROVIDER_NS: &'static str = "net_a";
|
||||
const CLIENT_NS: &'static str = "net_b";
|
||||
const UPSTREAM_NS: &'static str = "net_pubgw";
|
||||
const SERVER_NS: &'static str = "net_pubsrv";
|
||||
const WAN_BRIDGE: &'static str = "br_pubwan";
|
||||
const SERVER_BRIDGE: &'static str = "br_pubsrv";
|
||||
const PROVIDER_TUN: &'static str = "etpubv6p";
|
||||
const CLIENT_TUN: &'static str = "etpubv6c";
|
||||
const PROVIDER_PREFIX: &'static str = "2001:db8:100::/64";
|
||||
const PROVIDER_DEFAULT_FROM: &'static str = "2001:db8:100::/64";
|
||||
const PROVIDER_WAN_ADDR: &'static str = "2001:db8:ffff:1::2/64";
|
||||
const UPSTREAM_WAN_ADDR: &'static str = "2001:db8:ffff:1::1/64";
|
||||
const UPSTREAM_SERVER_ADDR: &'static str = "2001:db8:ffff:2::1/64";
|
||||
const SERVER_ADDR: &'static str = "2001:db8:ffff:2::100/64";
|
||||
const SERVER_IP: &'static str = "2001:db8:ffff:2::100";
|
||||
|
||||
fn setup() -> Self {
|
||||
prepare_linux_namespaces();
|
||||
|
||||
del_netns(Self::UPSTREAM_NS);
|
||||
del_netns(Self::SERVER_NS);
|
||||
let _ = std::process::Command::new("ip")
|
||||
.args(["link", "del", Self::WAN_BRIDGE])
|
||||
.status();
|
||||
let _ = std::process::Command::new("ip")
|
||||
.args(["link", "del", Self::SERVER_BRIDGE])
|
||||
.status();
|
||||
let _ = std::process::Command::new("brctl")
|
||||
.args(["delbr", Self::WAN_BRIDGE])
|
||||
.status();
|
||||
let _ = std::process::Command::new("brctl")
|
||||
.args(["delbr", Self::SERVER_BRIDGE])
|
||||
.status();
|
||||
|
||||
create_empty_netns(Self::UPSTREAM_NS);
|
||||
create_empty_netns(Self::SERVER_NS);
|
||||
prepare_bridge(Self::WAN_BRIDGE);
|
||||
prepare_bridge(Self::SERVER_BRIDGE);
|
||||
run_ip(&["link", "set", Self::WAN_BRIDGE, "up"]);
|
||||
run_ip(&["link", "set", Self::SERVER_BRIDGE, "up"]);
|
||||
|
||||
connect_ns_to_bridge(
|
||||
Self::PROVIDER_NS,
|
||||
"pubwan0",
|
||||
"veth_pubwan_p",
|
||||
Self::WAN_BRIDGE,
|
||||
);
|
||||
connect_ns_to_bridge(
|
||||
Self::UPSTREAM_NS,
|
||||
"upwan0",
|
||||
"veth_pubwan_u",
|
||||
Self::WAN_BRIDGE,
|
||||
);
|
||||
connect_ns_to_bridge(
|
||||
Self::UPSTREAM_NS,
|
||||
"upsrv0",
|
||||
"veth_pubsrv_u",
|
||||
Self::SERVER_BRIDGE,
|
||||
);
|
||||
connect_ns_to_bridge(
|
||||
Self::SERVER_NS,
|
||||
"srv0",
|
||||
"veth_pubsrv_s",
|
||||
Self::SERVER_BRIDGE,
|
||||
);
|
||||
|
||||
run_ip_in_ns(
|
||||
Self::PROVIDER_NS,
|
||||
&["addr", "add", Self::PROVIDER_WAN_ADDR, "dev", "pubwan0"],
|
||||
);
|
||||
run_ip_in_ns(
|
||||
Self::UPSTREAM_NS,
|
||||
&["addr", "add", Self::UPSTREAM_WAN_ADDR, "dev", "upwan0"],
|
||||
);
|
||||
run_ip_in_ns(
|
||||
Self::UPSTREAM_NS,
|
||||
&["addr", "add", Self::UPSTREAM_SERVER_ADDR, "dev", "upsrv0"],
|
||||
);
|
||||
run_ip_in_ns(
|
||||
Self::SERVER_NS,
|
||||
&["addr", "add", Self::SERVER_ADDR, "dev", "srv0"],
|
||||
);
|
||||
|
||||
run_ip_in_ns(
|
||||
Self::PROVIDER_NS,
|
||||
&["link", "add", "pubprefix0", "type", "dummy"],
|
||||
);
|
||||
run_ip_in_ns(Self::PROVIDER_NS, &["link", "set", "pubprefix0", "up"]);
|
||||
run_ip_in_ns(
|
||||
Self::PROVIDER_NS,
|
||||
&[
|
||||
"-6",
|
||||
"route",
|
||||
"add",
|
||||
Self::PROVIDER_PREFIX,
|
||||
"dev",
|
||||
"pubprefix0",
|
||||
],
|
||||
);
|
||||
run_ip_in_ns(
|
||||
Self::PROVIDER_NS,
|
||||
&[
|
||||
"-6",
|
||||
"route",
|
||||
"add",
|
||||
"default",
|
||||
"from",
|
||||
Self::PROVIDER_DEFAULT_FROM,
|
||||
"via",
|
||||
"2001:db8:ffff:1::1",
|
||||
"dev",
|
||||
"pubwan0",
|
||||
],
|
||||
);
|
||||
|
||||
run_ip_in_ns(
|
||||
Self::SERVER_NS,
|
||||
&[
|
||||
"-6",
|
||||
"route",
|
||||
"add",
|
||||
"default",
|
||||
"via",
|
||||
"2001:db8:ffff:2::1",
|
||||
"dev",
|
||||
"srv0",
|
||||
],
|
||||
);
|
||||
run_ip_in_ns(
|
||||
Self::UPSTREAM_NS,
|
||||
&[
|
||||
"-6",
|
||||
"route",
|
||||
"add",
|
||||
Self::PROVIDER_PREFIX,
|
||||
"via",
|
||||
"2001:db8:ffff:1::2",
|
||||
"dev",
|
||||
"upwan0",
|
||||
],
|
||||
);
|
||||
|
||||
run_sysctl_in_ns(Self::PROVIDER_NS, "net.ipv6.conf.all.forwarding=1");
|
||||
run_sysctl_in_ns(Self::UPSTREAM_NS, "net.ipv6.conf.all.forwarding=1");
|
||||
|
||||
Self {
|
||||
extra_namespaces: [Self::UPSTREAM_NS, Self::SERVER_NS],
|
||||
extra_bridges: [Self::WAN_BRIDGE, Self::SERVER_BRIDGE],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PublicIpv6Lab {
|
||||
fn drop(&mut self) {
|
||||
for ns in self.extra_namespaces {
|
||||
del_netns(ns);
|
||||
}
|
||||
for bridge in self.extra_bridges {
|
||||
let _ = std::process::Command::new("ip")
|
||||
.args(["link", "del", bridge])
|
||||
.status();
|
||||
let _ = std::process::Command::new("brctl")
|
||||
.args(["delbr", bridge])
|
||||
.status();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_public_ipv6_config(
|
||||
inst_name: &str,
|
||||
netns: &str,
|
||||
ipv4: &str,
|
||||
dev_name: &str,
|
||||
inst_id: uuid::Uuid,
|
||||
) -> TomlConfigLoader {
|
||||
let config = get_inst_config(inst_name, Some(netns), ipv4, "fd00::1/64");
|
||||
config.set_id(inst_id);
|
||||
config.set_ipv6(None);
|
||||
config.set_socks5_portal(None);
|
||||
config.set_network_identity(NetworkIdentity {
|
||||
network_name: "public_ipv6_auto_addr_test".to_string(),
|
||||
network_secret: Some("public_ipv6_auto_addr_secret".to_string()),
|
||||
network_secret_digest: None,
|
||||
});
|
||||
config.set_listeners(vec!["tcp://0.0.0.0:11010".parse().unwrap()]);
|
||||
let mut flags = config.get_flags();
|
||||
flags.dev_name = dev_name.to_string();
|
||||
config.set_flags(flags);
|
||||
config
|
||||
}
|
||||
|
||||
async fn init_public_ipv6_two_node(
|
||||
client_inst_id: uuid::Uuid,
|
||||
) -> (PublicIpv6Lab, Instance, Instance) {
|
||||
let lab = PublicIpv6Lab::setup();
|
||||
|
||||
let provider_cfg = get_public_ipv6_config(
|
||||
"provider_public_ipv6",
|
||||
PublicIpv6Lab::PROVIDER_NS,
|
||||
"10.144.144.1",
|
||||
PublicIpv6Lab::PROVIDER_TUN,
|
||||
uuid::Uuid::parse_str("11111111-1111-1111-1111-111111111111").unwrap(),
|
||||
);
|
||||
provider_cfg.set_ipv6_public_addr_provider(true);
|
||||
|
||||
let client_cfg = get_public_ipv6_config(
|
||||
"client_public_ipv6",
|
||||
PublicIpv6Lab::CLIENT_NS,
|
||||
"10.144.144.2",
|
||||
PublicIpv6Lab::CLIENT_TUN,
|
||||
client_inst_id,
|
||||
);
|
||||
client_cfg.set_ipv6_public_addr_auto(true);
|
||||
|
||||
let mut provider = Instance::new(provider_cfg);
|
||||
let mut client = Instance::new(client_cfg);
|
||||
|
||||
provider.run().await.unwrap();
|
||||
client.run().await.unwrap();
|
||||
|
||||
provider
|
||||
.get_conn_manager()
|
||||
.add_connector(TcpTunnelConnector::new(
|
||||
"tcp://10.1.1.2:11010".parse().unwrap(),
|
||||
));
|
||||
|
||||
wait_for_condition(
|
||||
|| async {
|
||||
provider.get_peer_manager().list_routes().await.len() == 1
|
||||
&& client.get_peer_manager().list_routes().await.len() == 1
|
||||
},
|
||||
Duration::from_secs(8),
|
||||
)
|
||||
.await;
|
||||
|
||||
(lab, provider, client)
|
||||
}
|
||||
|
||||
async fn wait_for_public_ipv6_addr(inst: &Instance) -> cidr::Ipv6Inet {
|
||||
wait_for_condition(
|
||||
|| async {
|
||||
inst.get_peer_manager()
|
||||
.get_my_public_ipv6_addr()
|
||||
.await
|
||||
.is_some()
|
||||
},
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
inst.get_peer_manager()
|
||||
.get_my_public_ipv6_addr()
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn wait_for_public_ipv6_route(inst: &Instance, target: cidr::Ipv6Inet) {
|
||||
wait_for_condition(
|
||||
|| async {
|
||||
inst.get_peer_manager()
|
||||
.list_public_ipv6_routes()
|
||||
.await
|
||||
.contains(&target)
|
||||
},
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn route_exists_in_ns(ns: &str, needle: &str) -> bool {
|
||||
run_ip_in_ns_output(ns, &["-6", "route", "show"])
|
||||
.lines()
|
||||
.any(|line| line.contains(needle))
|
||||
}
|
||||
|
||||
fn addr_exists_in_ns(ns: &str, dev: &str, needle: &str) -> bool {
|
||||
run_ip_in_ns_output(ns, &["-6", "addr", "show", "dev", dev]).contains(needle)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
pub async fn public_ipv6_auto_addr_end_to_end() {
|
||||
let client_id = uuid::Uuid::parse_str("22222222-2222-2222-2222-222222222222").unwrap();
|
||||
let (_lab, provider, client) = init_public_ipv6_two_node(client_id).await;
|
||||
|
||||
wait_for_condition(
|
||||
|| async {
|
||||
provider
|
||||
.get_global_ctx()
|
||||
.get_advertised_ipv6_public_addr_prefix()
|
||||
== Some(PublicIpv6Lab::PROVIDER_PREFIX.parse().unwrap())
|
||||
},
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
|
||||
let leased = wait_for_public_ipv6_addr(&client).await;
|
||||
wait_for_public_ipv6_route(&provider, leased).await;
|
||||
|
||||
assert_eq!(
|
||||
provider
|
||||
.get_global_ctx()
|
||||
.config
|
||||
.get_ipv6_public_addr_prefix(),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.get_global_ctx()
|
||||
.get_advertised_ipv6_public_addr_prefix(),
|
||||
Some(PublicIpv6Lab::PROVIDER_PREFIX.parse().unwrap())
|
||||
);
|
||||
let provider_prefix = PublicIpv6Lab::PROVIDER_PREFIX
|
||||
.parse::<cidr::Ipv6Cidr>()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
provider
|
||||
.get_peer_manager()
|
||||
.get_my_info()
|
||||
.await
|
||||
.ipv6_public_addr_prefix,
|
||||
Some(
|
||||
cidr::Ipv6Inet::new(
|
||||
provider_prefix.first_address(),
|
||||
provider_prefix.network_length()
|
||||
)
|
||||
.unwrap()
|
||||
.into()
|
||||
)
|
||||
);
|
||||
let provider_info = provider
|
||||
.get_peer_manager()
|
||||
.get_local_public_ipv6_info()
|
||||
.await;
|
||||
let client_peer_id = client.get_peer_manager().get_my_info().await.peer_id;
|
||||
assert_eq!(
|
||||
provider_info.provider_prefix,
|
||||
Some(
|
||||
cidr::Ipv6Inet::new(
|
||||
provider_prefix.first_address(),
|
||||
provider_prefix.network_length()
|
||||
)
|
||||
.unwrap()
|
||||
.into()
|
||||
)
|
||||
);
|
||||
assert_eq!(provider_info.provider_leases.len(), 1);
|
||||
assert_eq!(provider_info.provider_leases[0].peer_id, client_peer_id);
|
||||
assert_eq!(
|
||||
provider_info.provider_leases[0].inst_id,
|
||||
client_id.to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
provider_info.provider_leases[0].leased_addr,
|
||||
Some(leased.into())
|
||||
);
|
||||
assert!(
|
||||
leased.address().segments()[0] & 0xfe00 != 0xfc00,
|
||||
"leased address should not be unique-local: {leased}"
|
||||
);
|
||||
|
||||
wait_for_condition(
|
||||
|| async {
|
||||
addr_exists_in_ns(
|
||||
PublicIpv6Lab::CLIENT_NS,
|
||||
PublicIpv6Lab::CLIENT_TUN,
|
||||
&leased.to_string(),
|
||||
) && route_exists_in_ns(
|
||||
PublicIpv6Lab::CLIENT_NS,
|
||||
&format!("default dev {}", PublicIpv6Lab::CLIENT_TUN),
|
||||
) && route_exists_in_ns(
|
||||
PublicIpv6Lab::PROVIDER_NS,
|
||||
&format!("{} dev {}", leased.address(), PublicIpv6Lab::PROVIDER_TUN),
|
||||
)
|
||||
},
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
|
||||
wait_for_condition(
|
||||
|| async { ping6_test(PublicIpv6Lab::CLIENT_NS, PublicIpv6Lab::SERVER_IP, None).await },
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
|
||||
wait_for_condition(
|
||||
|| async {
|
||||
ping6_test(
|
||||
PublicIpv6Lab::SERVER_NS,
|
||||
leased.address().to_string().as_str(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
},
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
|
||||
drop_insts(vec![provider, client]).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
pub async fn public_ipv6_auto_addr_reconnect_reuses_same_address() {
|
||||
let client_id = uuid::Uuid::parse_str("33333333-3333-3333-3333-333333333333").unwrap();
|
||||
let (_lab, provider, client) = init_public_ipv6_two_node(client_id).await;
|
||||
let first = wait_for_public_ipv6_addr(&client).await;
|
||||
|
||||
drop_insts(vec![client]).await;
|
||||
|
||||
let client_cfg = get_public_ipv6_config(
|
||||
"client_public_ipv6_reconnect",
|
||||
PublicIpv6Lab::CLIENT_NS,
|
||||
"10.144.144.2",
|
||||
PublicIpv6Lab::CLIENT_TUN,
|
||||
client_id,
|
||||
);
|
||||
client_cfg.set_ipv6_public_addr_auto(true);
|
||||
let mut client = Instance::new(client_cfg);
|
||||
client.run().await.unwrap();
|
||||
provider
|
||||
.get_conn_manager()
|
||||
.add_connector(TcpTunnelConnector::new(
|
||||
"tcp://10.1.1.2:11010".parse().unwrap(),
|
||||
));
|
||||
|
||||
wait_for_condition(
|
||||
|| async {
|
||||
provider.get_peer_manager().list_routes().await.len() == 1
|
||||
&& client.get_peer_manager().list_routes().await.len() == 1
|
||||
},
|
||||
Duration::from_secs(8),
|
||||
)
|
||||
.await;
|
||||
|
||||
let second = wait_for_public_ipv6_addr(&client).await;
|
||||
assert_eq!(first, second);
|
||||
|
||||
wait_for_condition(
|
||||
|| async { ping6_test(PublicIpv6Lab::CLIENT_NS, PublicIpv6Lab::SERVER_IP, None).await },
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
|
||||
drop_insts(vec![provider, client]).await;
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
@@ -3077,7 +3599,15 @@ pub async fn config_patch_test() {
|
||||
};
|
||||
use crate::tunnel::common::tests::_tunnel_pingpong_netns_with_timeout;
|
||||
|
||||
let insts = init_three_node("udp").await;
|
||||
let insts = init_three_node_ex(
|
||||
"udp",
|
||||
|cfg| {
|
||||
cfg.set_ipv6(None);
|
||||
cfg
|
||||
},
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
check_route(
|
||||
"10.144.144.2/24",
|
||||
@@ -3124,6 +3654,46 @@ pub async fn config_patch_test() {
|
||||
},
|
||||
);
|
||||
|
||||
// 测试1.1:修改公网 IPv6 provider 相关配置
|
||||
let public_prefix = "2001:db8:100::/64";
|
||||
let patch = InstanceConfigPatch {
|
||||
ipv6_public_addr_provider: Some(true),
|
||||
ipv6_public_addr_auto: Some(true),
|
||||
ipv6_public_addr_prefix: Some(public_prefix.to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
insts[1]
|
||||
.get_config_patcher()
|
||||
.apply_patch(patch)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
insts[1]
|
||||
.get_global_ctx()
|
||||
.config
|
||||
.get_ipv6_public_addr_provider()
|
||||
);
|
||||
assert!(insts[1].get_global_ctx().config.get_ipv6_public_addr_auto());
|
||||
assert_eq!(
|
||||
insts[1]
|
||||
.get_global_ctx()
|
||||
.config
|
||||
.get_ipv6_public_addr_prefix(),
|
||||
Some(public_prefix.parse().unwrap())
|
||||
);
|
||||
assert!(
|
||||
insts[1]
|
||||
.get_global_ctx()
|
||||
.get_feature_flags()
|
||||
.ipv6_public_addr_provider
|
||||
);
|
||||
assert_eq!(
|
||||
insts[1]
|
||||
.get_global_ctx()
|
||||
.get_advertised_ipv6_public_addr_prefix(),
|
||||
Some(public_prefix.parse().unwrap())
|
||||
);
|
||||
|
||||
// 测试2: 端口转发
|
||||
let patch = InstanceConfigPatch {
|
||||
port_forwards: vec![PortForwardPatch {
|
||||
|
||||
@@ -281,6 +281,7 @@ impl TunnelListener for FakeTcpTunnelListener {
|
||||
pub struct FakeTcpTunnelConnector {
|
||||
addr: url::Url,
|
||||
ip_to_if_name: IpToIfNameCache,
|
||||
resolved_addr: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl FakeTcpTunnelConnector {
|
||||
@@ -288,6 +289,7 @@ impl FakeTcpTunnelConnector {
|
||||
FakeTcpTunnelConnector {
|
||||
addr,
|
||||
ip_to_if_name: IpToIfNameCache::new(),
|
||||
resolved_addr: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -314,7 +316,10 @@ fn get_local_ip_for_destination(destination: IpAddr) -> Option<IpAddr> {
|
||||
#[async_trait::async_trait]
|
||||
impl TunnelConnector for FakeTcpTunnelConnector {
|
||||
async fn connect(&mut self) -> Result<Box<dyn Tunnel>, TunnelError> {
|
||||
let remote_addr = SocketAddr::from_url(self.addr.clone(), IpVersion::Both).await?;
|
||||
let remote_addr = match self.resolved_addr {
|
||||
Some(addr) => addr,
|
||||
None => SocketAddr::from_url(self.addr.clone(), IpVersion::Both).await?,
|
||||
};
|
||||
let local_ip = get_local_ip_for_destination(remote_addr.ip())
|
||||
.ok_or(TunnelError::InternalError("Failed to get local ip".into()))?;
|
||||
|
||||
@@ -390,6 +395,10 @@ impl TunnelConnector for FakeTcpTunnelConnector {
|
||||
fn remote_url(&self) -> url::Url {
|
||||
self.addr.clone()
|
||||
}
|
||||
|
||||
fn set_resolved_addr(&mut self, addr: SocketAddr) {
|
||||
self.resolved_addr = Some(addr);
|
||||
}
|
||||
}
|
||||
|
||||
type RecvFut = Pin<Box<dyn Future<Output = Option<(BytesMut, usize)>> + Send + Sync>>;
|
||||
|
||||
@@ -141,6 +141,7 @@ pub trait TunnelConnector: Send {
|
||||
fn remote_url(&self) -> url::Url;
|
||||
fn set_bind_addrs(&mut self, _addrs: Vec<SocketAddr>) {}
|
||||
fn set_ip_version(&mut self, _ip_version: IpVersion) {}
|
||||
fn set_resolved_addr(&mut self, _addr: SocketAddr) {}
|
||||
}
|
||||
|
||||
pub fn build_url_from_socket_addr(addr: &String, scheme: &str) -> url::Url {
|
||||
@@ -371,9 +372,13 @@ impl TryFrom<&url::Url> for TunnelScheme {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_scheme_by_url(l: &url::Url) -> Result<TunnelScheme, Error> {
|
||||
l.try_into()
|
||||
}
|
||||
|
||||
macro_rules! __matches_scheme__ {
|
||||
($url:expr, $( $pattern:pat_param )|+ ) => {
|
||||
matches!($crate::tunnel::TunnelScheme::try_from(($url).as_ref()), Ok($( $pattern )|+))
|
||||
matches!($crate::tunnel::get_scheme_by_url(&$url), Ok($( $pattern )|+))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -393,3 +398,22 @@ macro_rules! __matches_protocol__ {
|
||||
}
|
||||
|
||||
pub(crate) use __matches_protocol__ as matches_protocol;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{IpScheme, TunnelScheme, matches_scheme};
|
||||
|
||||
#[test]
|
||||
fn matches_scheme_accepts_owned_url() {
|
||||
let url: url::Url = "udp://[2001:db8::1]:11010".parse().unwrap();
|
||||
|
||||
assert!(matches_scheme!(url, TunnelScheme::Ip(IpScheme::Udp)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_scheme_accepts_borrowed_url() {
|
||||
let url: url::Url = "udp://[2001:db8::1]:11010".parse().unwrap();
|
||||
|
||||
assert!(matches_scheme!(&url, TunnelScheme::Ip(IpScheme::Udp)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -432,6 +432,7 @@ pub struct QuicTunnelConnector {
|
||||
addr: url::Url,
|
||||
global_ctx: ArcGlobalCtx,
|
||||
ip_version: IpVersion,
|
||||
resolved_addr: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl QuicTunnelConnector {
|
||||
@@ -440,6 +441,7 @@ impl QuicTunnelConnector {
|
||||
addr,
|
||||
global_ctx,
|
||||
ip_version: IpVersion::Both,
|
||||
resolved_addr: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -447,7 +449,10 @@ impl QuicTunnelConnector {
|
||||
#[async_trait::async_trait]
|
||||
impl TunnelConnector for QuicTunnelConnector {
|
||||
async fn connect(&mut self) -> Result<Box<dyn Tunnel>, TunnelError> {
|
||||
let addr = SocketAddr::from_url(self.addr.clone(), self.ip_version).await?;
|
||||
let addr = match self.resolved_addr {
|
||||
Some(addr) => addr,
|
||||
None => SocketAddr::from_url(self.addr.clone(), self.ip_version).await?,
|
||||
};
|
||||
let (endpoint, connection) = QuicEndpointManager::connect(&self.global_ctx, addr).await?;
|
||||
|
||||
let local_addr = endpoint.local_addr()?;
|
||||
@@ -484,6 +489,10 @@ impl TunnelConnector for QuicTunnelConnector {
|
||||
fn set_ip_version(&mut self, ip_version: IpVersion) {
|
||||
self.ip_version = ip_version;
|
||||
}
|
||||
|
||||
fn set_resolved_addr(&mut self, addr: SocketAddr) {
|
||||
self.resolved_addr = Some(addr);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -129,6 +129,7 @@ pub struct TcpTunnelConnector {
|
||||
|
||||
bind_addrs: Vec<SocketAddr>,
|
||||
ip_version: IpVersion,
|
||||
resolved_addr: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl TcpTunnelConnector {
|
||||
@@ -137,6 +138,7 @@ impl TcpTunnelConnector {
|
||||
addr,
|
||||
bind_addrs: vec![],
|
||||
ip_version: IpVersion::Both,
|
||||
resolved_addr: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,7 +177,10 @@ impl TcpTunnelConnector {
|
||||
#[async_trait]
|
||||
impl super::TunnelConnector for TcpTunnelConnector {
|
||||
async fn connect(&mut self) -> Result<Box<dyn Tunnel>, TunnelError> {
|
||||
let addr = SocketAddr::from_url(self.addr.clone(), self.ip_version).await?;
|
||||
let addr = match self.resolved_addr {
|
||||
Some(addr) => addr,
|
||||
None => SocketAddr::from_url(self.addr.clone(), self.ip_version).await?,
|
||||
};
|
||||
if self.bind_addrs.is_empty() {
|
||||
self.connect_with_default_bind(addr).await
|
||||
} else {
|
||||
@@ -194,6 +199,10 @@ impl super::TunnelConnector for TcpTunnelConnector {
|
||||
fn set_ip_version(&mut self, ip_version: IpVersion) {
|
||||
self.ip_version = ip_version;
|
||||
}
|
||||
|
||||
fn set_resolved_addr(&mut self, addr: SocketAddr) {
|
||||
self.resolved_addr = Some(addr);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -294,6 +303,31 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connector_uses_pre_resolved_addr_without_resolving_url() {
|
||||
let mut listener = TcpTunnelListener::new("tcp://127.0.0.1:0".parse().unwrap());
|
||||
listener.listen().await.unwrap();
|
||||
|
||||
let port = listener.local_url().port().unwrap();
|
||||
let source_url: url::Url = format!("tcp://unresolvable.invalid:{port}")
|
||||
.parse()
|
||||
.unwrap();
|
||||
let resolved_addr: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
|
||||
let mut connector = TcpTunnelConnector::new(source_url.clone());
|
||||
connector.set_resolved_addr(resolved_addr);
|
||||
|
||||
let accept_task = tokio::spawn(async move { listener.accept().await.unwrap() });
|
||||
let tunnel = connector.connect().await.unwrap();
|
||||
let _accepted_tunnel = accept_task.await.unwrap();
|
||||
|
||||
let info = tunnel.info().unwrap();
|
||||
assert_eq!(info.remote_addr.unwrap().url, source_url.to_string());
|
||||
|
||||
let resolved_remote_addr: url::Url = info.resolved_remote_addr.unwrap().into();
|
||||
assert_eq!(resolved_remote_addr.host_str(), Some("127.0.0.1"));
|
||||
assert_eq!(resolved_remote_addr.port(), Some(port));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_alloc_port() {
|
||||
// v4
|
||||
|
||||
@@ -682,6 +682,7 @@ pub struct UdpTunnelConnector {
|
||||
addr: url::Url,
|
||||
bind_addrs: Vec<SocketAddr>,
|
||||
ip_version: IpVersion,
|
||||
resolved_addr: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl UdpTunnelConnector {
|
||||
@@ -690,6 +691,7 @@ impl UdpTunnelConnector {
|
||||
addr,
|
||||
bind_addrs: vec![],
|
||||
ip_version: IpVersion::Both,
|
||||
resolved_addr: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -906,7 +908,10 @@ impl UdpTunnelConnector {
|
||||
#[async_trait]
|
||||
impl super::TunnelConnector for UdpTunnelConnector {
|
||||
async fn connect(&mut self) -> Result<Box<dyn Tunnel>, TunnelError> {
|
||||
let addr = SocketAddr::from_url(self.addr.clone(), self.ip_version).await?;
|
||||
let addr = match self.resolved_addr {
|
||||
Some(addr) => addr,
|
||||
None => SocketAddr::from_url(self.addr.clone(), self.ip_version).await?,
|
||||
};
|
||||
if self.bind_addrs.is_empty() || addr.is_ipv6() {
|
||||
self.connect_with_default_bind(addr).await
|
||||
} else {
|
||||
@@ -925,6 +930,10 @@ impl super::TunnelConnector for UdpTunnelConnector {
|
||||
fn set_ip_version(&mut self, ip_version: IpVersion) {
|
||||
self.ip_version = ip_version;
|
||||
}
|
||||
|
||||
fn set_resolved_addr(&mut self, addr: SocketAddr) {
|
||||
self.resolved_addr = Some(addr);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -198,6 +198,7 @@ impl TunnelListener for WsTunnelListener {
|
||||
pub struct WsTunnelConnector {
|
||||
addr: url::Url,
|
||||
ip_version: IpVersion,
|
||||
resolved_addr: Option<SocketAddr>,
|
||||
|
||||
bind_addrs: Vec<SocketAddr>,
|
||||
}
|
||||
@@ -207,6 +208,7 @@ impl WsTunnelConnector {
|
||||
WsTunnelConnector {
|
||||
addr,
|
||||
ip_version: IpVersion::Both,
|
||||
resolved_addr: None,
|
||||
|
||||
bind_addrs: vec![],
|
||||
}
|
||||
@@ -214,11 +216,10 @@ impl WsTunnelConnector {
|
||||
|
||||
async fn connect_with(
|
||||
addr: url::Url,
|
||||
ip_version: IpVersion,
|
||||
socket_addr: SocketAddr,
|
||||
tcp_socket: TcpSocket,
|
||||
) -> Result<Box<dyn Tunnel>, TunnelError> {
|
||||
let is_wss = is_wss(&addr)?;
|
||||
let socket_addr = SocketAddr::from_url(addr.clone(), ip_version).await?;
|
||||
let stream = tcp_socket.connect(socket_addr).await?;
|
||||
if let Err(error) = stream.set_nodelay(true) {
|
||||
tracing::warn!(?error, "set_nodelay fail in ws connect");
|
||||
@@ -273,7 +274,7 @@ impl WsTunnelConnector {
|
||||
} else {
|
||||
TcpSocket::new_v6()?
|
||||
};
|
||||
Self::connect_with(self.addr.clone(), self.ip_version, socket).await
|
||||
Self::connect_with(self.addr.clone(), addr, socket).await
|
||||
}
|
||||
|
||||
async fn connect_with_custom_bind(
|
||||
@@ -285,11 +286,7 @@ impl WsTunnelConnector {
|
||||
for bind_addr in self.bind_addrs.iter() {
|
||||
tracing::info!(?bind_addr, ?addr, "bind addr");
|
||||
match bind().addr(*bind_addr).only_v6(true).call() {
|
||||
Ok(socket) => futures.push(Self::connect_with(
|
||||
self.addr.clone(),
|
||||
self.ip_version,
|
||||
socket,
|
||||
)),
|
||||
Ok(socket) => futures.push(Self::connect_with(self.addr.clone(), addr, socket)),
|
||||
Err(error) => {
|
||||
tracing::error!(?bind_addr, ?addr, ?error, "bind addr fail");
|
||||
continue;
|
||||
@@ -304,7 +301,10 @@ impl WsTunnelConnector {
|
||||
#[async_trait::async_trait]
|
||||
impl TunnelConnector for WsTunnelConnector {
|
||||
async fn connect(&mut self) -> Result<Box<dyn Tunnel>, TunnelError> {
|
||||
let addr = SocketAddr::from_url(self.addr.clone(), self.ip_version).await?;
|
||||
let addr = match self.resolved_addr {
|
||||
Some(addr) => addr,
|
||||
None => SocketAddr::from_url(self.addr.clone(), self.ip_version).await?,
|
||||
};
|
||||
if self.bind_addrs.is_empty() || addr.is_ipv6() {
|
||||
self.connect_with_default_bind(addr).await
|
||||
} else {
|
||||
@@ -323,6 +323,10 @@ impl TunnelConnector for WsTunnelConnector {
|
||||
fn set_bind_addrs(&mut self, addrs: Vec<SocketAddr>) {
|
||||
self.bind_addrs = addrs;
|
||||
}
|
||||
|
||||
fn set_resolved_addr(&mut self, addr: SocketAddr) {
|
||||
self.resolved_addr = Some(addr);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -598,6 +598,7 @@ pub struct WgTunnelConnector {
|
||||
|
||||
bind_addrs: Vec<SocketAddr>,
|
||||
ip_version: IpVersion,
|
||||
resolved_addr: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl Debug for WgTunnelConnector {
|
||||
@@ -617,6 +618,7 @@ impl WgTunnelConnector {
|
||||
udp: None,
|
||||
bind_addrs: vec![],
|
||||
ip_version: IpVersion::Both,
|
||||
resolved_addr: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -702,7 +704,10 @@ impl WgTunnelConnector {
|
||||
impl super::TunnelConnector for WgTunnelConnector {
|
||||
#[tracing::instrument]
|
||||
async fn connect(&mut self) -> Result<Box<dyn Tunnel>, TunnelError> {
|
||||
let addr = SocketAddr::from_url(self.addr.clone(), self.ip_version).await?;
|
||||
let addr = match self.resolved_addr {
|
||||
Some(addr) => addr,
|
||||
None => SocketAddr::from_url(self.addr.clone(), self.ip_version).await?,
|
||||
};
|
||||
|
||||
if addr.is_ipv6() {
|
||||
return self.connect_with_ipv6(addr).await;
|
||||
@@ -744,6 +749,10 @@ impl super::TunnelConnector for WgTunnelConnector {
|
||||
fn set_ip_version(&mut self, ip_version: IpVersion) {
|
||||
self.ip_version = ip_version;
|
||||
}
|
||||
|
||||
fn set_resolved_addr(&mut self, addr: SocketAddr) {
|
||||
self.resolved_addr = Some(addr);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,638 +0,0 @@
|
||||
//! # Guard Module Utilities
|
||||
//!
|
||||
//! This module provides mechanisms for scope-based resource management and deferred execution.
|
||||
//!
|
||||
//! ### ⚠️ Critical Usage Note: Diverging Expressions
|
||||
//!
|
||||
//! Do not use "naked" diverging expressions—such as `panic!`, `todo!`, or `loop {}`—as
|
||||
//! the sole content of sync guard closure. This prevents the compiler from
|
||||
//! distinguishing between synchronous (`ASYNC = false`) and asynchronous
|
||||
//! (`ASYNC = true`) implementations, leading to a type inference error (E0277).
|
||||
//!
|
||||
//! ### Technical Context
|
||||
//!
|
||||
//! The `!` (Never Type) is a bottom type that can be coerced into any other type.
|
||||
//! Because it satisfies both the `()` requirement for sync guards and the `Future`
|
||||
//! requirement for async guards, the compiler encounters an inference deadlock.
|
||||
//!
|
||||
//! ### Workaround
|
||||
//!
|
||||
//! For macros like `guard!` or `guarded!`, force the closure to resolve to `()`
|
||||
//! by explicitly setting the guard to `sync`:
|
||||
//!
|
||||
//! ```rust
|
||||
//! let _g = guard!([val] sync {
|
||||
//! panic!("critical failure");
|
||||
//! });
|
||||
//! ```
|
||||
|
||||
use crate::utils::task::{DetachableTask, TaskSpawner};
|
||||
use std::fmt::Debug;
|
||||
use std::mem::ManuallyDrop;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
pub trait CallableGuard<const ASYNC: bool, Context> {
|
||||
type Output;
|
||||
fn call(self, context: Context) -> Self::Output;
|
||||
}
|
||||
|
||||
impl<Context, Guard> CallableGuard<false, Context> for Guard
|
||||
where
|
||||
Guard: FnOnce(Context),
|
||||
{
|
||||
type Output = ();
|
||||
|
||||
fn call(self, context: Context) -> Self::Output {
|
||||
self(context)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Context, Guard, Task, _R> CallableGuard<true, Context> for Guard
|
||||
where
|
||||
Guard: FnOnce(Context) -> Task + Send + 'static,
|
||||
Task: Future<Output = _R> + Send + 'static,
|
||||
_R: Send + 'static,
|
||||
{
|
||||
type Output = DetachableTask<TaskSpawner<Task>, Task>;
|
||||
|
||||
fn call(self, context: Context) -> Self::Output {
|
||||
DetachableTask::new(self(context))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ContextGuard<const ASYNC: bool, Context, Guard: CallableGuard<ASYNC, Context>> {
|
||||
context: ManuallyDrop<Context>,
|
||||
guard: ManuallyDrop<Guard>,
|
||||
}
|
||||
|
||||
impl<const ASYNC: bool, Context, Guard: CallableGuard<ASYNC, Context>> Deref
|
||||
for ContextGuard<ASYNC, Context, Guard>
|
||||
{
|
||||
type Target = Context;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.context
|
||||
}
|
||||
}
|
||||
|
||||
impl<const ASYNC: bool, Context, Guard: CallableGuard<ASYNC, Context>> DerefMut
|
||||
for ContextGuard<ASYNC, Context, Guard>
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.context
|
||||
}
|
||||
}
|
||||
|
||||
impl<const ASYNC: bool, Context: Debug, Guard: CallableGuard<ASYNC, Context>> Debug
|
||||
for ContextGuard<ASYNC, Context, Guard>
|
||||
{
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let name = if ASYNC {
|
||||
"ContextGuard::Async"
|
||||
} else {
|
||||
"ContextGuard::Sync"
|
||||
};
|
||||
f.debug_struct(name)
|
||||
.field("context", &self.context)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<const ASYNC: bool, Context, Guard: CallableGuard<ASYNC, Context>>
|
||||
ContextGuard<ASYNC, Context, Guard>
|
||||
{
|
||||
/// Creates a new `ContextGuard`.
|
||||
///
|
||||
/// **Note on generics:** The seemingly unused `_R` generic parameter and the
|
||||
/// `Guard: FnOnce(Context) -> _R` trait bound are intentionally included.
|
||||
/// They act as a hint to help the compiler infer closure types.
|
||||
pub fn new<_R>(context: Context, guard: Guard) -> Self
|
||||
where
|
||||
Guard: FnOnce(Context) -> _R,
|
||||
{
|
||||
ContextGuard {
|
||||
context: ManuallyDrop::new(context),
|
||||
guard: ManuallyDrop::new(guard),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const ASYNC: bool, Context, Guard: CallableGuard<ASYNC, Context>>
|
||||
ContextGuard<ASYNC, Context, Guard>
|
||||
{
|
||||
unsafe fn call(&mut self) -> Guard::Output {
|
||||
unsafe {
|
||||
let context = ManuallyDrop::take(&mut self.context);
|
||||
let guard = ManuallyDrop::take(&mut self.guard);
|
||||
|
||||
guard.call(context)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trigger(self) -> Guard::Output {
|
||||
let mut this = ManuallyDrop::new(self);
|
||||
unsafe { this.call() }
|
||||
}
|
||||
|
||||
pub fn defuse(self) -> Context {
|
||||
let mut this = ManuallyDrop::new(self);
|
||||
unsafe {
|
||||
ManuallyDrop::drop(&mut this.guard);
|
||||
ManuallyDrop::take(&mut this.context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const ASYNC: bool, Context, Guard: CallableGuard<ASYNC, Context>> Drop
|
||||
for ContextGuard<ASYNC, Context, Guard>
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
let _: Guard::Output = unsafe { self.call() };
|
||||
}
|
||||
}
|
||||
|
||||
// region macro
|
||||
|
||||
#[doc(hidden)]
|
||||
#[macro_export]
|
||||
macro_rules! __guarded {
|
||||
(@parse@action $guard:ident => $($tt:tt)*) => {
|
||||
$crate::__guarded! { @parse@async action: [ @stmt $guard ] ; $($tt)* }
|
||||
};
|
||||
|
||||
(@parse@action $($tt:tt)*) => {
|
||||
$crate::__guarded! { @parse@async action: [ @stmt __guard ] ; $($tt)* }
|
||||
};
|
||||
|
||||
(@parse@async action: [ $($action:tt)* ] ; sync $($tt:tt)*) => {
|
||||
$crate::__guarded! { @parse@move action: [ $($action)* ] ; async: [ false ] ; $($tt)* }
|
||||
};
|
||||
|
||||
(@parse@async action: [ $($action:tt)* ] ; $($tt:tt)*) => {
|
||||
$crate::__guarded! { @parse@move action: [ $($action)* ] ; async: [ _ ] ; $($tt)* }
|
||||
};
|
||||
|
||||
(@parse@move action: [ $($action:tt)* ] ; async: [ $async:tt ] ; move $($tt:tt)*) => {
|
||||
$crate::__guarded! { @parse action: [ $($action)* ] ; async: [ $async ] ; move: [ move ] ; $($tt)* }
|
||||
};
|
||||
|
||||
(@parse@move action: [ $($action:tt)* ] ; async: [ $async:tt ] ; $($tt:tt)*) => {
|
||||
$crate::__guarded! { @parse action: [ $($action)* ] ; async: [ $async ] ; move: [] ; $($tt)* }
|
||||
};
|
||||
|
||||
(
|
||||
@parse action: [ $($action:tt)* ] ; async: [ $async:tt ] ; move: [ $($move:tt)? ] ;
|
||||
[ $($args:tt)* ] $body:block
|
||||
) => {
|
||||
$crate::__guarded! {
|
||||
action: [ $($action)* ]
|
||||
async: [ $async ]
|
||||
move: [ $($move)? ]
|
||||
mut: []
|
||||
rest: [ $($args)* , ]
|
||||
args: []
|
||||
vars: []
|
||||
body: [ $body ]
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
@parse action: [ $($action:tt)* ] ; async: [ $async:tt ] ; move: [ $($move:tt)? ] ;
|
||||
$body:block
|
||||
) => {
|
||||
$crate::__guarded! {
|
||||
@parse action: [ $($action)* ] ; async: [ $async ] ; move: [ $($move)? ] ;
|
||||
[] $body
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
@parse action: [ $($action:tt)* ] ; async: [ $async:tt ] ; move: [ $($move:tt)? ] ;
|
||||
[ $($args:tt)* ] $($body:tt)*
|
||||
) => {
|
||||
$crate::__guarded! {
|
||||
@parse action: [ $($action)* ] ; async: [ $async ] ; move: [ $($move)? ] ;
|
||||
[ $($args)* ] { $($body)* }
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
@parse action: [ $($action:tt)* ] ; async: [ $async:tt ] ; move: [ $($move:tt)? ] ;
|
||||
$($body:tt)*
|
||||
) => {
|
||||
$crate::__guarded! {
|
||||
@parse action: [ $($action)* ] ; async: [ $async ] ; move: [ $($move)? ] ;
|
||||
[] { $($body)* }
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
action: [ $($action:tt)* ]
|
||||
async: [ $async:tt ]
|
||||
move: [ $($move:tt)? ]
|
||||
mut: [ $($mut:tt)? ]
|
||||
rest: [ mut $arg:ident , $($rest:tt)* ]
|
||||
args: [ $($args:ident)* ]
|
||||
vars: [ $($vars:tt)* ]
|
||||
body: [ $body:expr ]
|
||||
) => {
|
||||
$crate::__guarded! {
|
||||
action: [ $($action)* ]
|
||||
async: [ $async ]
|
||||
move: [ $($move)? ]
|
||||
mut: [ mut ]
|
||||
rest: [ $($rest)* ]
|
||||
args: [ $($args)* $arg ]
|
||||
vars: [ $($vars)* [mut $arg] ]
|
||||
body: [ $body ]
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
action: [ $($action:tt)* ]
|
||||
async: [ $async:tt ]
|
||||
move: [ $($move:tt)? ]
|
||||
mut: [ $($mut:tt)? ]
|
||||
rest: [ $arg:ident , $($rest:tt)* ]
|
||||
args: [ $($args:ident)* ]
|
||||
vars: [ $($vars:tt)* ]
|
||||
body: [ $body:expr ]
|
||||
) => {
|
||||
$crate::__guarded! {
|
||||
action: [ $($action)* ]
|
||||
async: [ $async ]
|
||||
move: [ $($move)? ]
|
||||
mut: [ $($mut)? ]
|
||||
rest: [ $($rest)* ]
|
||||
args: [ $($args)* $arg ]
|
||||
vars: [ $($vars)* [$arg] ]
|
||||
body: [ $body ]
|
||||
}
|
||||
};
|
||||
|
||||
(
|
||||
action: [ @stmt $guard:ident ]
|
||||
async: [ $async:tt ]
|
||||
move: [ $($move:tt)? ]
|
||||
mut: [ $($mut:tt)? ]
|
||||
rest: [ $(,)* ]
|
||||
args: [ $($args:ident)* ]
|
||||
vars: [ $([$($vars:tt)*])* ]
|
||||
body: [ $body:expr ]
|
||||
) => {
|
||||
let $($mut)? $guard = $crate::utils::guard::ContextGuard::<$async, _, _>::new(
|
||||
( $($args),* ),
|
||||
$($move)? |#[allow(unused_parens, unused_mut)] ( $($($vars)*),* )| $body
|
||||
);
|
||||
|
||||
#[allow(unused_parens, unused_variables, clippy::toplevel_ref_arg)]
|
||||
let ( $(ref $($vars)*),* ) = *$guard;
|
||||
};
|
||||
|
||||
(
|
||||
action: [ @expr ]
|
||||
async: [ $async:tt ]
|
||||
move: [ $($move:tt)? ]
|
||||
mut: [ $($mut:tt)? ]
|
||||
rest: [ $(,)* ]
|
||||
args: [ $($args:ident)* ]
|
||||
vars: [ $([$($vars:tt)*])* ]
|
||||
body: [ $body:expr ]
|
||||
) => {
|
||||
$crate::utils::guard::ContextGuard::<$async, _, _>::new(
|
||||
( $($args),* ),
|
||||
$($move)? |#[allow(unused_parens)] ( $($($vars)*),* )| $body
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
/// Creates a [`ContextGuard`] object, binding it to a variable with the specified name (e.g., `_guard`).
|
||||
/// Context variables specified in the macro invocation are available within and after the guard body.
|
||||
///
|
||||
/// **Note:** For usage with `panic!` or `loop`, see the [module-level documentation](self)
|
||||
/// regarding type inference deadlocks.
|
||||
#[macro_export]
|
||||
macro_rules! guarded {
|
||||
( $($tt:tt)* ) => {
|
||||
$crate::__guarded! { @parse@action $($tt)* }
|
||||
};
|
||||
}
|
||||
|
||||
/// Creates a [`ContextGuard`] object, without binding it to a variable.
|
||||
/// Context variables specified in the macro invocation are available within the guard body.
|
||||
///
|
||||
/// **Note:** For usage with `panic!` or `loop`, see the [module-level documentation](self)
|
||||
/// regarding type inference deadlocks.
|
||||
#[macro_export]
|
||||
macro_rules! guard {
|
||||
( $($tt:tt)* ) => {
|
||||
$crate::__guarded! { @parse@async action: [ @expr ] ; $($tt)* }
|
||||
};
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
/// Alias for [`guarded!`].
|
||||
///
|
||||
/// **Note:** For usage with `panic!` or `loop`, see the [module-level documentation](self)
|
||||
/// regarding type inference deadlocks.
|
||||
#[macro_export]
|
||||
macro_rules! defer {
|
||||
( $($tt:tt)* ) => {
|
||||
$crate::guarded! { $($tt)* }
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::panic::catch_unwind;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
#[test]
|
||||
fn trigger_sync_executes_once() {
|
||||
let called = Arc::new(AtomicUsize::new(0));
|
||||
let observed = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let value = 7usize;
|
||||
let guard = {
|
||||
let called = called.clone();
|
||||
let observed = observed.clone();
|
||||
crate::guard!(move [value] {
|
||||
called.fetch_add(1, Ordering::SeqCst);
|
||||
observed.store(value, Ordering::SeqCst);
|
||||
})
|
||||
};
|
||||
|
||||
guard.trigger();
|
||||
|
||||
assert_eq!(called.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(observed.load(Ordering::SeqCst), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defuse_sync_returns_context_without_running_guard() {
|
||||
let called = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let value = String::from("hello");
|
||||
let guard = {
|
||||
let called = called.clone();
|
||||
crate::guard!(move [mut value] {
|
||||
value.push_str(" world");
|
||||
called.fetch_add(1, Ordering::SeqCst);
|
||||
})
|
||||
};
|
||||
|
||||
let context = guard.defuse();
|
||||
assert_eq!(context, "hello");
|
||||
assert_eq!(called.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_sync_triggers_guard() {
|
||||
let called = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
{
|
||||
let called = called.clone();
|
||||
crate::guarded!([called] {
|
||||
called.fetch_add(1, Ordering::SeqCst);
|
||||
});
|
||||
}
|
||||
|
||||
assert_eq!(called.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_propagates_guard_panic() {
|
||||
let dropped = catch_unwind(|| {
|
||||
guarded! {
|
||||
sync {
|
||||
panic!("boom");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
assert!(dropped.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn trigger_async_returns_runnable_task() {
|
||||
let called = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let value = 5usize;
|
||||
let guard = {
|
||||
let called = called.clone();
|
||||
crate::guard!(move [value] async move {
|
||||
called.fetch_add(value, Ordering::SeqCst);
|
||||
})
|
||||
};
|
||||
let task = guard.trigger();
|
||||
task.await;
|
||||
|
||||
assert_eq!(called.load(Ordering::SeqCst), 5);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn drop_async_detaches_task() {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
|
||||
{
|
||||
let mut tx = Some(tx);
|
||||
let value = 9usize;
|
||||
let _guard = crate::guard!(move [value] {
|
||||
let tx = tx.take();
|
||||
async move {
|
||||
if let Some(tx) = tx {
|
||||
let _ = tx.send(value);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let value = tokio::time::timeout(Duration::from_secs(1), rx)
|
||||
.await
|
||||
.expect("detached task should run")
|
||||
.expect("detached task should send value");
|
||||
assert_eq!(value, 9);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn defuse_async_does_not_execute() {
|
||||
let called = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let value = 11usize;
|
||||
let guard = {
|
||||
let called = called.clone();
|
||||
crate::guard!(move [value] async move {
|
||||
called.fetch_add(value, Ordering::SeqCst);
|
||||
})
|
||||
};
|
||||
|
||||
let context = guard.defuse();
|
||||
assert_eq!(context, 11);
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
assert_eq!(called.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guarded_named_mut_binding_updates_context_before_drop() {
|
||||
let committed = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
{
|
||||
let value = 1usize;
|
||||
let step = 2usize;
|
||||
let committed = committed.clone();
|
||||
|
||||
crate::guarded!(scope_guard => [mut value, step] {
|
||||
committed.store(value + step, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
*value += 10;
|
||||
assert_eq!(*value, 11);
|
||||
assert_eq!(*step, 2);
|
||||
|
||||
drop(scope_guard);
|
||||
}
|
||||
|
||||
assert_eq!(committed.load(Ordering::SeqCst), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guard_expression_parses_without_braces() {
|
||||
let observed = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let value = 3usize;
|
||||
let observed_clone = observed.clone();
|
||||
let guard = crate::guard!([value] observed_clone.store(value, Ordering::SeqCst));
|
||||
guard.trigger();
|
||||
|
||||
assert_eq!(observed.load(Ordering::SeqCst), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defer_alias_behaves_like_guarded_statement() {
|
||||
let called = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
{
|
||||
let n = 42usize;
|
||||
let called = called.clone();
|
||||
crate::defer!([n] {
|
||||
called.store(n, Ordering::SeqCst);
|
||||
});
|
||||
}
|
||||
|
||||
assert_eq!(called.load(Ordering::SeqCst), 42);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guard_and_guarded_macro_usage_matrix() {
|
||||
// 1) guard!: block body + trailing comma args + trigger()
|
||||
let sink = Arc::new(AtomicUsize::new(0));
|
||||
let v = 1usize;
|
||||
let sink_clone = sink.clone();
|
||||
let g1 = crate::guard!([v,] {
|
||||
sink_clone.store(v, Ordering::SeqCst);
|
||||
});
|
||||
g1.trigger();
|
||||
assert_eq!(sink.load(Ordering::SeqCst), 1);
|
||||
|
||||
// 2) guard!: expression body (no braces)
|
||||
let sink = Arc::new(AtomicUsize::new(0));
|
||||
let sink_clone = sink.clone();
|
||||
let v = 2usize;
|
||||
let g2 = crate::guard!([v] sink_clone.store(v, Ordering::SeqCst));
|
||||
g2.trigger();
|
||||
assert_eq!(sink.load(Ordering::SeqCst), 2);
|
||||
|
||||
// 3) guard!: explicit sync + no args form
|
||||
let sink = Arc::new(AtomicUsize::new(0));
|
||||
let sink_clone = sink.clone();
|
||||
let g3 = crate::guard!(sync {
|
||||
sink_clone.store(3, Ordering::SeqCst);
|
||||
});
|
||||
g3.trigger();
|
||||
assert_eq!(sink.load(Ordering::SeqCst), 3);
|
||||
|
||||
// 4) guard!: move capture + defuse() prevents execution
|
||||
let sink = Arc::new(AtomicUsize::new(0));
|
||||
let owned = String::from("owned");
|
||||
let sink_clone = sink.clone();
|
||||
let g4 = crate::guard!(move [owned] {
|
||||
if owned == "owned" {
|
||||
sink_clone.store(4, Ordering::SeqCst);
|
||||
}
|
||||
});
|
||||
let context = g4.defuse();
|
||||
assert_eq!(context, "owned");
|
||||
assert_eq!(sink.load(Ordering::SeqCst), 0);
|
||||
|
||||
// 5) guard!: async block inference + trigger() returns task
|
||||
let sink = Arc::new(AtomicUsize::new(0));
|
||||
let sink_clone = sink.clone();
|
||||
let n = 5usize;
|
||||
let g5 = crate::guard!([n] async move {
|
||||
sink_clone.fetch_add(n, Ordering::SeqCst);
|
||||
});
|
||||
g5.trigger().await;
|
||||
assert_eq!(sink.load(Ordering::SeqCst), 5);
|
||||
|
||||
// 6) guarded!: named binding + mut arg visible outside + explicit drop
|
||||
let sink = Arc::new(AtomicUsize::new(0));
|
||||
{
|
||||
let value = 6usize;
|
||||
let delta = 1usize;
|
||||
let sink_clone = sink.clone();
|
||||
|
||||
crate::guarded!(named => [mut value, delta] {
|
||||
sink_clone.store(value + delta, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
*value += 10;
|
||||
assert_eq!(*value, 16);
|
||||
assert_eq!(*delta, 1);
|
||||
drop(named);
|
||||
}
|
||||
assert_eq!(sink.load(Ordering::SeqCst), 17);
|
||||
|
||||
// 7) guarded!: unnamed statement + expression body + implicit drop at scope end
|
||||
let sink = Arc::new(AtomicUsize::new(0));
|
||||
{
|
||||
let n = 7usize;
|
||||
let sink_clone = sink.clone();
|
||||
crate::guarded!([n] sink_clone.store(n, Ordering::SeqCst));
|
||||
}
|
||||
assert_eq!(sink.load(Ordering::SeqCst), 7);
|
||||
|
||||
// 8) guarded!: explicit sync + panic path propagates on drop
|
||||
let dropped = catch_unwind(|| {
|
||||
guarded! {
|
||||
sync {
|
||||
panic!("matrix-boom");
|
||||
}
|
||||
}
|
||||
});
|
||||
assert!(dropped.is_err());
|
||||
|
||||
// 9) guarded!: async inference on drop detaches and executes
|
||||
let (tx, rx) = oneshot::channel();
|
||||
{
|
||||
let tx = Some(tx);
|
||||
crate::guarded!([mut tx] {
|
||||
let tx = tx.take();
|
||||
async move {
|
||||
if let Some(tx) = tx {
|
||||
let _ = tx.send(9usize);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
let detached = tokio::time::timeout(Duration::from_secs(1), rx)
|
||||
.await
|
||||
.expect("detached task should complete")
|
||||
.expect("detached task should send value");
|
||||
assert_eq!(detached, 9);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
pub mod guard;
|
||||
pub mod panic;
|
||||
pub mod string;
|
||||
pub mod task;
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
use crate::utils::guard::ContextGuard;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::ops::DerefMut;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
@@ -80,284 +78,3 @@ impl<Output> Future for CancellableTask<Output> {
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region DetachableTask
|
||||
|
||||
/// A pinned, heap-allocated task.
|
||||
///
|
||||
/// **Why Box?** Heap allocation is required because if the task detaches,
|
||||
/// it outlives the current stack frame. `Pin<Box<_>>` ensures its memory address
|
||||
/// remains completely stable during and after the transfer.
|
||||
type BoxTask<Task> = Pin<Box<Task>>;
|
||||
|
||||
struct DetachableTaskContext<Spawner, Task> {
|
||||
spawner: Spawner,
|
||||
task: Option<BoxTask<Task>>,
|
||||
}
|
||||
type DetachableTaskGuardHelper<Context> = ContextGuard<false, Context, fn(Context)>;
|
||||
type DetachableTaskGuard<Spawner, Task> =
|
||||
DetachableTaskGuardHelper<DetachableTaskContext<Spawner, Task>>;
|
||||
|
||||
/// A task wrapper that executes inline but automatically detaches to a background spawner
|
||||
/// if the current execution context is interrupted or dropped.
|
||||
///
|
||||
/// `DetachableTask` ensures anti-cancellation. If the outer future is dropped (e.g., due to
|
||||
/// a timeout or a `select!` branch failing), the underlying unfinished task is seamlessly
|
||||
/// transferred to a background executor via an RAII guard.
|
||||
///
|
||||
/// # Advantages over `tokio::spawn` + `.await JoinHandle`
|
||||
///
|
||||
/// 1. **Zero Initial Scheduling Overhead**: Prioritizes inline execution. If the task
|
||||
/// completes before being interrupted, it entirely bypasses the runtime's scheduling queue,
|
||||
/// eliminating queuing latency and context-switching CPU costs. Spawning is strictly a fallback.
|
||||
///
|
||||
/// 2. **Context Locality**: Before detachment, the task is polled directly by the caller's thread.
|
||||
/// This implicitly preserves the current execution context, including thread-local storage (TLS),
|
||||
/// Tokio `task_local!` variables, and `tracing` spans, which would otherwise be immediately
|
||||
/// lost or require explicit propagation across task boundaries.
|
||||
pub struct DetachableTask<Spawner, Task> {
|
||||
guard: DetachableTaskGuard<Spawner, Task>,
|
||||
}
|
||||
|
||||
impl<Spawner, Task> DetachableTask<Spawner, Task> {
|
||||
pub fn detach(self) {
|
||||
self.guard.trigger()
|
||||
}
|
||||
|
||||
pub fn reclaim(self) -> BoxTask<Task> {
|
||||
self.guard.defuse().task.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub type TaskSpawner<Task, R = JoinHandle<<Task as Future>::Output>> = fn(BoxTask<Task>) -> R;
|
||||
|
||||
impl DetachableTask<fn(()), ()> {
|
||||
pub fn with_spawner<Spawner, _R, Task>(
|
||||
spawner: Spawner,
|
||||
task: Task,
|
||||
) -> DetachableTask<Spawner, Task>
|
||||
where
|
||||
Spawner: FnOnce(BoxTask<Task>) -> _R,
|
||||
{
|
||||
let context = DetachableTaskContext {
|
||||
spawner,
|
||||
task: Some(Box::pin(task)),
|
||||
};
|
||||
DetachableTask {
|
||||
guard: crate::guard!([context] if let Some(task) = context.task {
|
||||
(context.spawner)(task);
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new<Task>(task: Task) -> DetachableTask<TaskSpawner<Task>, Task>
|
||||
where
|
||||
Task: Future + Send + 'static,
|
||||
<Task as Future>::Output: Send + 'static,
|
||||
{
|
||||
Self::with_spawner(|task| tokio::runtime::Handle::current().spawn(task), task)
|
||||
}
|
||||
}
|
||||
|
||||
impl<Spawner: FnOnce(BoxTask<Task>) -> _R, _R, Task> IntoFuture for DetachableTask<Spawner, Task>
|
||||
where
|
||||
Task: Future,
|
||||
{
|
||||
type Output = Task::Output;
|
||||
type IntoFuture = DetachableTaskFuture<Spawner, Task>;
|
||||
|
||||
fn into_future(self) -> Self::IntoFuture {
|
||||
DetachableTaskFuture { guard: self.guard }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DetachableTaskFuture<Spawner, Task> {
|
||||
guard: DetachableTaskGuard<Spawner, Task>,
|
||||
}
|
||||
|
||||
impl<Spawner: FnOnce(BoxTask<Task>) -> _R, _R, Task> Future for DetachableTaskFuture<Spawner, Task>
|
||||
where
|
||||
Task: Future,
|
||||
{
|
||||
type Output = Task::Output;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
// SAFETY:
|
||||
// 1. We only access the outer struct's unpinned fields.
|
||||
// 2. The inner task remains securely pinned on the heap via `BoxTask<Task>`.
|
||||
// 3. We never expose a mutable, unpinned reference to the underlying task.
|
||||
let this = unsafe { self.get_unchecked_mut() };
|
||||
let context = this.guard.deref_mut();
|
||||
let mut task = context.task.take().expect("polled after completion");
|
||||
let poll = task.as_mut().poll(cx);
|
||||
if poll.is_pending() {
|
||||
context.task = Some(task);
|
||||
}
|
||||
poll
|
||||
}
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_when_dropped() {
|
||||
let spawned = Arc::new(AtomicBool::new(false));
|
||||
{
|
||||
let spawned = spawned.clone();
|
||||
let _task = DetachableTask::new(async move {
|
||||
spawned.store(true, Ordering::SeqCst);
|
||||
});
|
||||
}
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while !spawned.load(Ordering::SeqCst) {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("task should be spawned on drop");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn await_completed_task_does_not_detach() {
|
||||
let spawn_count = Arc::new(AtomicUsize::new(0));
|
||||
let result = {
|
||||
let spawn_count = spawn_count.clone();
|
||||
DetachableTask::with_spawner(
|
||||
move |_| {
|
||||
spawn_count.fetch_add(1, Ordering::SeqCst);
|
||||
},
|
||||
async { 7usize },
|
||||
)
|
||||
.await
|
||||
};
|
||||
|
||||
assert_eq!(result, 7);
|
||||
assert_eq!(spawn_count.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn drop_without_await_and_runs_once() {
|
||||
let spawn_count = Arc::new(AtomicUsize::new(0));
|
||||
let (done_tx, done_rx) = oneshot::channel();
|
||||
|
||||
{
|
||||
let spawn_count = spawn_count.clone();
|
||||
let _task = DetachableTask::with_spawner(
|
||||
move |f| {
|
||||
spawn_count.fetch_add(1, Ordering::SeqCst);
|
||||
tokio::spawn(async move {
|
||||
let result = f.await;
|
||||
let _ = done_tx.send(result);
|
||||
});
|
||||
},
|
||||
async { 42usize },
|
||||
);
|
||||
}
|
||||
|
||||
let detached_result = tokio::time::timeout(Duration::from_secs(1), done_rx)
|
||||
.await
|
||||
.expect("detached task should finish")
|
||||
.expect("detached task should send result");
|
||||
|
||||
assert_eq!(detached_result, 42);
|
||||
assert_eq!(spawn_count.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn drop_after_await_still_detaches() {
|
||||
let spawn_count = Arc::new(AtomicUsize::new(0));
|
||||
let (value_tx, mut value_rx) = mpsc::channel(4);
|
||||
let (done_tx, done_rx) = oneshot::channel();
|
||||
|
||||
let handle = {
|
||||
let future = async move {
|
||||
let mut sum = 0;
|
||||
while let Some(value) = value_rx.recv().await {
|
||||
sum += value;
|
||||
}
|
||||
sum
|
||||
};
|
||||
|
||||
let spawn_count = spawn_count.clone();
|
||||
let task = DetachableTask::with_spawner(
|
||||
move |f| {
|
||||
spawn_count.fetch_add(1, Ordering::SeqCst);
|
||||
tokio::spawn(async move {
|
||||
let result = f.await;
|
||||
let _ = done_tx.send(result);
|
||||
});
|
||||
},
|
||||
future,
|
||||
);
|
||||
|
||||
tokio::spawn(task.into_future())
|
||||
};
|
||||
|
||||
value_tx
|
||||
.send(10)
|
||||
.await
|
||||
.expect("value receiver should still exist");
|
||||
handle.abort();
|
||||
value_tx
|
||||
.send(11)
|
||||
.await
|
||||
.expect("value receiver should still exist");
|
||||
drop(value_tx);
|
||||
|
||||
let detached_result = tokio::time::timeout(Duration::from_secs(1), done_rx)
|
||||
.await
|
||||
.expect("detached polled task should finish")
|
||||
.expect("detached polled task should send result");
|
||||
|
||||
assert_eq!(detached_result, 21);
|
||||
assert_eq!(spawn_count.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn panic_during_inline_poll_does_not_detach_on_drop() {
|
||||
struct PanicOnPollFuture {
|
||||
poll_count: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl Future for PanicOnPollFuture {
|
||||
type Output = ();
|
||||
|
||||
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
self.poll_count.fetch_add(1, Ordering::SeqCst);
|
||||
panic!("panic during inline poll")
|
||||
}
|
||||
}
|
||||
|
||||
let poll_count = Arc::new(AtomicUsize::new(0));
|
||||
let detach_count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let task = {
|
||||
let detach_count = detach_count.clone();
|
||||
DetachableTask::with_spawner(
|
||||
move |_| {
|
||||
detach_count.fetch_add(1, Ordering::SeqCst);
|
||||
},
|
||||
PanicOnPollFuture {
|
||||
poll_count: poll_count.clone(),
|
||||
},
|
||||
)
|
||||
};
|
||||
|
||||
let err = tokio::spawn(task.into_future())
|
||||
.await
|
||||
.expect_err("inline poll panic should propagate");
|
||||
|
||||
assert!(err.is_panic());
|
||||
assert_eq!(poll_count.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(detach_count.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"private": true,
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"caniuse-lite": "1.0.30001791",
|
||||
"minimatch": "10.2.4"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+277
-9
@@ -5,6 +5,7 @@ settings:
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
overrides:
|
||||
caniuse-lite: 1.0.30001791
|
||||
minimatch: 10.2.4
|
||||
|
||||
importers:
|
||||
@@ -58,7 +59,7 @@ importers:
|
||||
devDependencies:
|
||||
'@antfu/eslint-config':
|
||||
specifier: ^3.7.3
|
||||
version: 3.16.0(@typescript-eslint/utils@8.42.0(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3))(@vue/compiler-sfc@3.5.21)(eslint-plugin-format@0.1.3(eslint@9.35.0(jiti@2.5.1)))(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)
|
||||
version: 3.16.0(@typescript-eslint/utils@8.42.0(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3))(@vue/compiler-sfc@3.5.21)(eslint-plugin-format@0.1.3(eslint@9.35.0(jiti@2.5.1)))(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)(vitest@2.1.9(@types/node@22.18.1))
|
||||
'@intlify/unplugin-vue-i18n':
|
||||
specifier: ^5.2.0
|
||||
version: 5.3.1(@vue/compiler-dom@3.5.21)(eslint@9.35.0(jiti@2.5.1))(rollup@4.50.1)(typescript@5.6.3)(vue-i18n@10.0.8(vue@3.5.21(typescript@5.6.3)))(vue@3.5.21(typescript@5.6.3))
|
||||
@@ -286,6 +287,9 @@ importers:
|
||||
vite-plugin-dts:
|
||||
specifier: ^4.3.0
|
||||
version: 4.5.4(@types/node@22.18.1)(rollup@4.50.1)(typescript@5.6.3)(vite@5.4.21(@types/node@22.18.1))
|
||||
vitest:
|
||||
specifier: ^2.1.9
|
||||
version: 2.1.9(@types/node@22.18.1)
|
||||
vue-tsc:
|
||||
specifier: ^2.1.10
|
||||
version: 2.2.12(typescript@5.6.3)
|
||||
@@ -1673,6 +1677,35 @@ packages:
|
||||
vitest:
|
||||
optional: true
|
||||
|
||||
'@vitest/expect@2.1.9':
|
||||
resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
|
||||
|
||||
'@vitest/mocker@2.1.9':
|
||||
resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==}
|
||||
peerDependencies:
|
||||
msw: ^2.4.9
|
||||
vite: ^5.0.0
|
||||
peerDependenciesMeta:
|
||||
msw:
|
||||
optional: true
|
||||
vite:
|
||||
optional: true
|
||||
|
||||
'@vitest/pretty-format@2.1.9':
|
||||
resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==}
|
||||
|
||||
'@vitest/runner@2.1.9':
|
||||
resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==}
|
||||
|
||||
'@vitest/snapshot@2.1.9':
|
||||
resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==}
|
||||
|
||||
'@vitest/spy@2.1.9':
|
||||
resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==}
|
||||
|
||||
'@vitest/utils@2.1.9':
|
||||
resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==}
|
||||
|
||||
'@volar/language-core@2.4.15':
|
||||
resolution: {integrity: sha512-3VHw+QZU0ZG9IuQmzT68IyN4hZNd9GchGPhbD9+pa8CVv7rnoOZwo7T8weIbrRmihqy3ATpdfXFnqRrfPVK6CA==}
|
||||
|
||||
@@ -2072,6 +2105,10 @@ packages:
|
||||
argparse@2.0.1:
|
||||
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
|
||||
|
||||
assertion-error@2.0.1:
|
||||
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
ast-kit@1.4.3:
|
||||
resolution: {integrity: sha512-MdJqjpodkS5J149zN0Po+HPshkTdUyrvF7CKTafUgv69vBSPtncrj+3IiUgqdd7ElIEkbeXCsEouBUwLrw9Ilg==}
|
||||
engines: {node: '>=16.14.0'}
|
||||
@@ -2134,6 +2171,10 @@ packages:
|
||||
peerDependencies:
|
||||
esbuild: '>=0.18'
|
||||
|
||||
cac@6.7.14:
|
||||
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
call-bind-apply-helpers@1.0.2:
|
||||
resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -2146,12 +2187,16 @@ packages:
|
||||
resolution: {integrity: sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==}
|
||||
engines: {node: '>= 6'}
|
||||
|
||||
caniuse-lite@1.0.30001741:
|
||||
resolution: {integrity: sha512-QGUGitqsc8ARjLdgAfxETDhRbJ0REsP6O3I96TAth/mVjh2cYzN2u+3AzPP3aVSm2FehEItaJw1xd+IGBXWeSw==}
|
||||
caniuse-lite@1.0.30001791:
|
||||
resolution: {integrity: sha512-yk0l/YSrOnFZk3UROpDLQD9+kC1l4meK/wed583AXrzoarMGJcbRi2Q4RaUYbKxYAsZ8sWmaSa/DsLmdBeI1vQ==}
|
||||
|
||||
ccount@2.0.1:
|
||||
resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
|
||||
|
||||
chai@5.3.3:
|
||||
resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
chalk@4.1.2:
|
||||
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -2163,6 +2208,10 @@ packages:
|
||||
resolution: {integrity: sha512-aYeC/jDgSEx8SHWZvANYMioYMZ2KX02W6f6uVfyteuCGcadDLcYVHdfdygsTQkQ4TKn5lghoojAsPj5pu0SnvQ==}
|
||||
engines: {pnpm: '>=8'}
|
||||
|
||||
check-error@2.1.3:
|
||||
resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
|
||||
engines: {node: '>= 16'}
|
||||
|
||||
chokidar@3.6.0:
|
||||
resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}
|
||||
engines: {node: '>= 8.10.0'}
|
||||
@@ -2251,6 +2300,10 @@ packages:
|
||||
decode-named-character-reference@1.2.0:
|
||||
resolution: {integrity: sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==}
|
||||
|
||||
deep-eql@5.0.2:
|
||||
resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
deep-is@0.1.4:
|
||||
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
|
||||
|
||||
@@ -2328,6 +2381,9 @@ packages:
|
||||
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
es-module-lexer@1.7.0:
|
||||
resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
|
||||
|
||||
es-object-atoms@1.1.1:
|
||||
resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -2596,6 +2652,10 @@ packages:
|
||||
resolution: {integrity: sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==}
|
||||
engines: {node: '>=16.17'}
|
||||
|
||||
expect-type@1.3.0:
|
||||
resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
exsolve@1.0.7:
|
||||
resolution: {integrity: sha512-VO5fQUzZtI6C+vx4w/4BWJpg3s/5l+6pRQEHzFRM8WFi4XffSP1Z+4qi7GbjWbvRQEbdIco5mIMq+zX4rPuLrw==}
|
||||
|
||||
@@ -3017,6 +3077,9 @@ packages:
|
||||
longest-streak@3.1.0:
|
||||
resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
|
||||
|
||||
loupe@3.2.1:
|
||||
resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}
|
||||
|
||||
lru-cache@10.4.3:
|
||||
resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}
|
||||
|
||||
@@ -3370,6 +3433,10 @@ packages:
|
||||
pathe@2.0.3:
|
||||
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
|
||||
|
||||
pathval@2.0.1:
|
||||
resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}
|
||||
engines: {node: '>= 14.16'}
|
||||
|
||||
perfect-debounce@1.0.0:
|
||||
resolution: {integrity: sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==}
|
||||
|
||||
@@ -3612,6 +3679,9 @@ packages:
|
||||
resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
siginfo@2.0.0:
|
||||
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
|
||||
|
||||
signal-exit@3.0.7:
|
||||
resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}
|
||||
|
||||
@@ -3664,6 +3734,12 @@ packages:
|
||||
resolution: {integrity: sha512-o3yWv49B/o4QZk5ZcsALc6t0+eCelPc44zZsLtCQnZPDwFpDYSWcDnrv2TtMmMbQ7uKo3J0HTURCqckw23czNQ==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
stackback@0.0.2:
|
||||
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
||||
|
||||
std-env@3.10.0:
|
||||
resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
|
||||
|
||||
string-argv@0.3.2:
|
||||
resolution: {integrity: sha512-aqD2Q0144Z+/RqG52NeHEkZauTAUWJO8c6yTftGJKO3Tja5tUgIfmIl6kExvhtxSDP7fXB6DvzkfMpCd/F3G+Q==}
|
||||
engines: {node: '>=0.6.19'}
|
||||
@@ -3753,9 +3829,27 @@ packages:
|
||||
thenify@3.3.1:
|
||||
resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==}
|
||||
|
||||
tinybench@2.9.0:
|
||||
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
|
||||
|
||||
tinyexec@0.3.2:
|
||||
resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
|
||||
|
||||
tinyexec@1.0.1:
|
||||
resolution: {integrity: sha512-5uC6DDlmeqiOwCPmK9jMSdOuZTh8bU39Ys6yidB+UTt5hfZUPGAypSgFRiEp+jbi9qH40BLDvy85jIU88wKSqw==}
|
||||
|
||||
tinypool@1.1.1:
|
||||
resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
|
||||
engines: {node: ^18.0.0 || >=20.0.0}
|
||||
|
||||
tinyrainbow@1.2.0:
|
||||
resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
|
||||
tinyspy@3.0.2:
|
||||
resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
|
||||
to-regex-range@5.0.1:
|
||||
resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
|
||||
engines: {node: '>=8.0'}
|
||||
@@ -3975,6 +4069,11 @@ packages:
|
||||
peerDependencies:
|
||||
vite: ^2.6.0 || ^3.0.0 || ^4.0.0 || ^5.0.0-0 || ^6.0.0-0 || ^7.0.0-0
|
||||
|
||||
vite-node@2.1.9:
|
||||
resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==}
|
||||
engines: {node: ^18.0.0 || >=20.0.0}
|
||||
hasBin: true
|
||||
|
||||
vite-plugin-dts@4.5.4:
|
||||
resolution: {integrity: sha512-d4sOM8M/8z7vRXHHq/ebbblfaxENjogAAekcfcDCCwAyvGqnPrc7f4NZbvItS+g4WTgerW0xDwSz5qz11JT3vg==}
|
||||
peerDependencies:
|
||||
@@ -4050,6 +4149,31 @@ packages:
|
||||
terser:
|
||||
optional: true
|
||||
|
||||
vitest@2.1.9:
|
||||
resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==}
|
||||
engines: {node: ^18.0.0 || >=20.0.0}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
'@edge-runtime/vm': '*'
|
||||
'@types/node': ^18.0.0 || >=20.0.0
|
||||
'@vitest/browser': 2.1.9
|
||||
'@vitest/ui': 2.1.9
|
||||
happy-dom: '*'
|
||||
jsdom: '*'
|
||||
peerDependenciesMeta:
|
||||
'@edge-runtime/vm':
|
||||
optional: true
|
||||
'@types/node':
|
||||
optional: true
|
||||
'@vitest/browser':
|
||||
optional: true
|
||||
'@vitest/ui':
|
||||
optional: true
|
||||
happy-dom:
|
||||
optional: true
|
||||
jsdom:
|
||||
optional: true
|
||||
|
||||
vscode-uri@3.1.0:
|
||||
resolution: {integrity: sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ==}
|
||||
|
||||
@@ -4122,6 +4246,11 @@ packages:
|
||||
engines: {node: '>= 8'}
|
||||
hasBin: true
|
||||
|
||||
why-is-node-running@2.3.0:
|
||||
resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
|
||||
engines: {node: '>=8'}
|
||||
hasBin: true
|
||||
|
||||
word-wrap@1.2.5:
|
||||
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
@@ -4180,7 +4309,7 @@ snapshots:
|
||||
|
||||
'@alloc/quick-lru@5.2.0': {}
|
||||
|
||||
'@antfu/eslint-config@3.16.0(@typescript-eslint/utils@8.42.0(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3))(@vue/compiler-sfc@3.5.21)(eslint-plugin-format@0.1.3(eslint@9.35.0(jiti@2.5.1)))(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)':
|
||||
'@antfu/eslint-config@3.16.0(@typescript-eslint/utils@8.42.0(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3))(@vue/compiler-sfc@3.5.21)(eslint-plugin-format@0.1.3(eslint@9.35.0(jiti@2.5.1)))(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)(vitest@2.1.9(@types/node@22.18.1))':
|
||||
dependencies:
|
||||
'@antfu/install-pkg': 1.1.0
|
||||
'@clack/prompts': 0.9.1
|
||||
@@ -4189,7 +4318,7 @@ snapshots:
|
||||
'@stylistic/eslint-plugin': 2.13.0(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)
|
||||
'@typescript-eslint/eslint-plugin': 8.42.0(@typescript-eslint/parser@8.42.0(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3))(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)
|
||||
'@typescript-eslint/parser': 8.42.0(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)
|
||||
'@vitest/eslint-plugin': 1.3.9(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)
|
||||
'@vitest/eslint-plugin': 1.3.9(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)(vitest@2.1.9(@types/node@22.18.1))
|
||||
eslint: 9.35.0(jiti@2.5.1)
|
||||
eslint-config-flat-gitignore: 1.0.1(eslint@9.35.0(jiti@2.5.1))
|
||||
eslint-flat-config-utils: 1.1.0
|
||||
@@ -5386,16 +5515,57 @@ snapshots:
|
||||
vite: 5.4.21(@types/node@22.18.1)
|
||||
vue: 3.5.21(typescript@5.6.3)
|
||||
|
||||
'@vitest/eslint-plugin@1.3.9(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)':
|
||||
'@vitest/eslint-plugin@1.3.9(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)(vitest@2.1.9(@types/node@22.18.1))':
|
||||
dependencies:
|
||||
'@typescript-eslint/scope-manager': 8.42.0
|
||||
'@typescript-eslint/utils': 8.42.0(eslint@9.35.0(jiti@2.5.1))(typescript@5.6.3)
|
||||
eslint: 9.35.0(jiti@2.5.1)
|
||||
optionalDependencies:
|
||||
typescript: 5.6.3
|
||||
vitest: 2.1.9(@types/node@22.18.1)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@vitest/expect@2.1.9':
|
||||
dependencies:
|
||||
'@vitest/spy': 2.1.9
|
||||
'@vitest/utils': 2.1.9
|
||||
chai: 5.3.3
|
||||
tinyrainbow: 1.2.0
|
||||
|
||||
'@vitest/mocker@2.1.9(vite@5.4.21(@types/node@22.18.1))':
|
||||
dependencies:
|
||||
'@vitest/spy': 2.1.9
|
||||
estree-walker: 3.0.3
|
||||
magic-string: 0.30.18
|
||||
optionalDependencies:
|
||||
vite: 5.4.21(@types/node@22.18.1)
|
||||
|
||||
'@vitest/pretty-format@2.1.9':
|
||||
dependencies:
|
||||
tinyrainbow: 1.2.0
|
||||
|
||||
'@vitest/runner@2.1.9':
|
||||
dependencies:
|
||||
'@vitest/utils': 2.1.9
|
||||
pathe: 1.1.2
|
||||
|
||||
'@vitest/snapshot@2.1.9':
|
||||
dependencies:
|
||||
'@vitest/pretty-format': 2.1.9
|
||||
magic-string: 0.30.18
|
||||
pathe: 1.1.2
|
||||
|
||||
'@vitest/spy@2.1.9':
|
||||
dependencies:
|
||||
tinyspy: 3.0.2
|
||||
|
||||
'@vitest/utils@2.1.9':
|
||||
dependencies:
|
||||
'@vitest/pretty-format': 2.1.9
|
||||
loupe: 3.2.1
|
||||
tinyrainbow: 1.2.0
|
||||
|
||||
'@volar/language-core@2.4.15':
|
||||
dependencies:
|
||||
'@volar/source-map': 2.4.15
|
||||
@@ -5970,6 +6140,8 @@ snapshots:
|
||||
|
||||
argparse@2.0.1: {}
|
||||
|
||||
assertion-error@2.0.1: {}
|
||||
|
||||
ast-kit@1.4.3:
|
||||
dependencies:
|
||||
'@babel/parser': 7.28.4
|
||||
@@ -5985,7 +6157,7 @@ snapshots:
|
||||
autoprefixer@10.4.21(postcss@8.5.6):
|
||||
dependencies:
|
||||
browserslist: 4.25.4
|
||||
caniuse-lite: 1.0.30001741
|
||||
caniuse-lite: 1.0.30001791
|
||||
fraction.js: 4.3.7
|
||||
normalize-range: 0.1.2
|
||||
picocolors: 1.1.1
|
||||
@@ -6018,7 +6190,7 @@ snapshots:
|
||||
|
||||
browserslist@4.25.4:
|
||||
dependencies:
|
||||
caniuse-lite: 1.0.30001741
|
||||
caniuse-lite: 1.0.30001791
|
||||
electron-to-chromium: 1.5.214
|
||||
node-releases: 2.0.20
|
||||
update-browserslist-db: 1.1.3(browserslist@4.25.4)
|
||||
@@ -6034,6 +6206,8 @@ snapshots:
|
||||
esbuild: 0.25.9
|
||||
load-tsconfig: 0.2.5
|
||||
|
||||
cac@6.7.14: {}
|
||||
|
||||
call-bind-apply-helpers@1.0.2:
|
||||
dependencies:
|
||||
es-errors: 1.3.0
|
||||
@@ -6043,10 +6217,18 @@ snapshots:
|
||||
|
||||
camelcase-css@2.0.1: {}
|
||||
|
||||
caniuse-lite@1.0.30001741: {}
|
||||
caniuse-lite@1.0.30001791: {}
|
||||
|
||||
ccount@2.0.1: {}
|
||||
|
||||
chai@5.3.3:
|
||||
dependencies:
|
||||
assertion-error: 2.0.1
|
||||
check-error: 2.1.3
|
||||
deep-eql: 5.0.2
|
||||
loupe: 3.2.1
|
||||
pathval: 2.0.1
|
||||
|
||||
chalk@4.1.2:
|
||||
dependencies:
|
||||
ansi-styles: 4.3.0
|
||||
@@ -6058,6 +6240,8 @@ snapshots:
|
||||
dependencies:
|
||||
'@kurkle/color': 0.3.4
|
||||
|
||||
check-error@2.1.3: {}
|
||||
|
||||
chokidar@3.6.0:
|
||||
dependencies:
|
||||
anymatch: 3.1.3
|
||||
@@ -6138,6 +6322,8 @@ snapshots:
|
||||
dependencies:
|
||||
character-entities: 2.0.2
|
||||
|
||||
deep-eql@5.0.2: {}
|
||||
|
||||
deep-is@0.1.4: {}
|
||||
|
||||
default-browser-id@5.0.0: {}
|
||||
@@ -6198,6 +6384,8 @@ snapshots:
|
||||
|
||||
es-errors@1.3.0: {}
|
||||
|
||||
es-module-lexer@1.7.0: {}
|
||||
|
||||
es-object-atoms@1.1.1:
|
||||
dependencies:
|
||||
es-errors: 1.3.0
|
||||
@@ -6614,6 +6802,8 @@ snapshots:
|
||||
signal-exit: 4.1.0
|
||||
strip-final-newline: 3.0.0
|
||||
|
||||
expect-type@1.3.0: {}
|
||||
|
||||
exsolve@1.0.7: {}
|
||||
|
||||
extend-shallow@2.0.1:
|
||||
@@ -6977,6 +7167,8 @@ snapshots:
|
||||
|
||||
longest-streak@3.1.0: {}
|
||||
|
||||
loupe@3.2.1: {}
|
||||
|
||||
lru-cache@10.4.3: {}
|
||||
|
||||
lru-cache@5.1.1:
|
||||
@@ -7502,6 +7694,8 @@ snapshots:
|
||||
|
||||
pathe@2.0.3: {}
|
||||
|
||||
pathval@2.0.1: {}
|
||||
|
||||
perfect-debounce@1.0.0: {}
|
||||
|
||||
picocolors@1.1.1: {}
|
||||
@@ -7738,6 +7932,8 @@ snapshots:
|
||||
|
||||
shebang-regex@3.0.0: {}
|
||||
|
||||
siginfo@2.0.0: {}
|
||||
|
||||
signal-exit@3.0.7: {}
|
||||
|
||||
signal-exit@4.1.0: {}
|
||||
@@ -7785,6 +7981,10 @@ snapshots:
|
||||
|
||||
stable-hash-x@0.2.0: {}
|
||||
|
||||
stackback@0.0.2: {}
|
||||
|
||||
std-env@3.10.0: {}
|
||||
|
||||
string-argv@0.3.2: {}
|
||||
|
||||
string-width@4.2.3:
|
||||
@@ -7895,8 +8095,18 @@ snapshots:
|
||||
dependencies:
|
||||
any-promise: 1.3.0
|
||||
|
||||
tinybench@2.9.0: {}
|
||||
|
||||
tinyexec@0.3.2: {}
|
||||
|
||||
tinyexec@1.0.1: {}
|
||||
|
||||
tinypool@1.1.1: {}
|
||||
|
||||
tinyrainbow@1.2.0: {}
|
||||
|
||||
tinyspy@3.0.2: {}
|
||||
|
||||
to-regex-range@5.0.1:
|
||||
dependencies:
|
||||
is-number: 7.0.0
|
||||
@@ -8199,6 +8409,24 @@ snapshots:
|
||||
dependencies:
|
||||
vite: 5.4.21(@types/node@22.18.1)
|
||||
|
||||
vite-node@2.1.9(@types/node@22.18.1):
|
||||
dependencies:
|
||||
cac: 6.7.14
|
||||
debug: 4.4.1
|
||||
es-module-lexer: 1.7.0
|
||||
pathe: 1.1.2
|
||||
vite: 5.4.21(@types/node@22.18.1)
|
||||
transitivePeerDependencies:
|
||||
- '@types/node'
|
||||
- less
|
||||
- lightningcss
|
||||
- sass
|
||||
- sass-embedded
|
||||
- stylus
|
||||
- sugarss
|
||||
- supports-color
|
||||
- terser
|
||||
|
||||
vite-plugin-dts@4.5.4(@types/node@22.18.1)(rollup@4.50.1)(typescript@5.6.3)(vite@5.4.21(@types/node@22.18.1)):
|
||||
dependencies:
|
||||
'@microsoft/api-extractor': 7.52.11(@types/node@22.18.1)
|
||||
@@ -8290,6 +8518,41 @@ snapshots:
|
||||
'@types/node': 22.18.1
|
||||
fsevents: 2.3.3
|
||||
|
||||
vitest@2.1.9(@types/node@22.18.1):
|
||||
dependencies:
|
||||
'@vitest/expect': 2.1.9
|
||||
'@vitest/mocker': 2.1.9(vite@5.4.21(@types/node@22.18.1))
|
||||
'@vitest/pretty-format': 2.1.9
|
||||
'@vitest/runner': 2.1.9
|
||||
'@vitest/snapshot': 2.1.9
|
||||
'@vitest/spy': 2.1.9
|
||||
'@vitest/utils': 2.1.9
|
||||
chai: 5.3.3
|
||||
debug: 4.4.1
|
||||
expect-type: 1.3.0
|
||||
magic-string: 0.30.18
|
||||
pathe: 1.1.2
|
||||
std-env: 3.10.0
|
||||
tinybench: 2.9.0
|
||||
tinyexec: 0.3.2
|
||||
tinypool: 1.1.1
|
||||
tinyrainbow: 1.2.0
|
||||
vite: 5.4.21(@types/node@22.18.1)
|
||||
vite-node: 2.1.9(@types/node@22.18.1)
|
||||
why-is-node-running: 2.3.0
|
||||
optionalDependencies:
|
||||
'@types/node': 22.18.1
|
||||
transitivePeerDependencies:
|
||||
- less
|
||||
- lightningcss
|
||||
- msw
|
||||
- sass
|
||||
- sass-embedded
|
||||
- stylus
|
||||
- sugarss
|
||||
- supports-color
|
||||
- terser
|
||||
|
||||
vscode-uri@3.1.0: {}
|
||||
|
||||
vue-chartjs@5.3.2(chart.js@4.5.0)(vue@3.5.21(typescript@5.6.3)):
|
||||
@@ -8359,6 +8622,11 @@ snapshots:
|
||||
dependencies:
|
||||
isexe: 2.0.0
|
||||
|
||||
why-is-node-running@2.3.0:
|
||||
dependencies:
|
||||
siginfo: 2.0.0
|
||||
stackback: 0.0.2
|
||||
|
||||
word-wrap@1.2.5: {}
|
||||
|
||||
wrap-ansi@7.0.0:
|
||||
|
||||
Reference in New Issue
Block a user