1
0
mirror of https://github.com/fumiama/WireGold.git synced 2026-06-05 07:50:24 +08:00

9 Commits

Author SHA1 Message Date
KaranocaVe
80ae21ff10 feat: add Docker image and GHCR workflow (#3) 2026-05-18 17:21:02 +08:00
源文雨
762c5a3692 fix(ttl): map concurrent write 2026-04-12 13:01:39 +08:00
源文雨
3da0369a5f fix: release version tag 2026-04-11 16:05:14 +08:00
源文雨
f0a3440dfb feat(icmp): use fifo instead of pool 2026-04-11 15:35:31 +08:00
源文雨
25c5a5d658 feat: add version tag 2026-04-11 15:24:57 +08:00
源文雨
a85b102426 chore: make lint happy 2026-04-11 15:13:24 +08:00
源文雨
23d9238464 feat(p2p): add ICMP backend support 2026-04-11 15:02:45 +08:00
源文雨
9e642f875a fix(recv): panic on expired fragment get 2026-04-09 01:44:24 +08:00
源文雨
b86a65819c fix(lower): windows ip routing 2026-04-07 18:26:34 +08:00
30 changed files with 1456 additions and 91 deletions

13
.dockerignore Normal file
View File

@@ -0,0 +1,13 @@
.git
.github
.gitignore
.DS_Store
config.yaml
config.yml
build
dist
tmp
*.log
*.out

109
.github/workflows/docker.yml vendored Normal file
View File

@@ -0,0 +1,109 @@
name: docker
on:
pull_request:
push:
branches:
- "**"
tags:
- "v*"
workflow_dispatch:
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
docker-ci:
name: Build Docker image
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build test image
uses: docker/build-push-action@v7
with:
context: .
load: true
tags: wiregold:test
build-args: |
VERSION=ci-${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Smoke test help output
run: docker run --rm wiregold:test -h
- name: Smoke test key generation
run: docker run --rm wiregold:test -g
- name: Smoke test preshared key generation
run: docker run --rm wiregold:test -pg
- name: Smoke test missing TUN message
run: |
set -euo pipefail
output="$(docker run --rm wiregold:test 2>&1 || true)"
printf '%s\n' "$output"
printf '%s' "$output" | grep -F "WireGold requires /dev/net/tun inside the container."
docker-publish:
name: Publish GHCR image
runs-on: ubuntu-latest
needs: docker-ci
if: github.event_name != 'pull_request' && (startsWith(github.ref, 'refs/tags/v') || github.ref == format('refs/heads/{0}', github.event.repository.default_branch))
permissions:
contents: read
packages: write
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') || github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}
labels: |
org.opencontainers.image.title=WireGold
org.opencontainers.image.description=Container image for WireGold, a pure-Go Layer 3 VPN inspired by WireGuard.
- name: Build and push Docker image
id: push
uses: docker/build-push-action@v7
with:
context: .
push: true
platforms: linux/amd64,linux/arm64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
annotations: ${{ steps.meta.outputs.annotations }}
build-args: |
VERSION=${{ steps.meta.outputs.version }}
cache-from: type=gha
cache-to: type=gha,mode=max

View File

@@ -6,52 +6,69 @@ on:
env:
GITHUB_TOKEN: ${{ github.token }}
CGO_ENABLED: 0
LDFLAGS: -s -w -checklinkname=0
VERSION_PKG: github.com/fumiama/WireGold/config
jobs:
my-job:
name: Build WireGold on Push Tag 🚀
build:
name: Build ${{ matrix.name }}
runs-on: ubuntu-latest
strategy:
matrix:
include:
- { name: linux-x64, goos: linux, goarch: amd64 }
- { name: linux-x86, goos: linux, goarch: "386" }
- { name: windows-x64, goos: windows, goarch: amd64, ext: .exe }
- { name: windows-x86, goos: windows, goarch: "386", ext: .exe }
- { name: linux-arm64, goos: linux, goarch: arm64, goarm: "7" }
- { name: linux-armv6, goos: linux, goarch: arm, goarm: "6" }
- { name: linux-mips, goos: linux, goarch: mips }
- { name: linux-mips-softfloat, goos: linux, goarch: mips, gomips: softfloat }
- { name: linux-mipsel, goos: linux, goarch: mipsle }
- { name: linux-mipsel-softfloat, goos: linux, goarch: mipsle, gomips: softfloat }
env:
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
GOARM: ${{ matrix.goarm }}
GOMIPS: ${{ matrix.gomips }}
steps:
- name: Set up Go
uses: actions/setup-go@master
with:
go-version: ^1.25
- name: Check out code into the Go module directory
- name: Check out code
uses: actions/checkout@master
- name: Cache Go
id: cache
uses: actions/cache@v4
with:
# A list of files, directories, and wildcard patterns to cache and restore
path: ~/go/pkg/mod
key: ${{ runner.os }}-build-${{ hashFiles('**/go.sum') }}
- name: Tidy Go modules
run: go mod tidy
- name: Build linux-x64
run: CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-linux-x64 -trimpath
- name: Build linux-x86
run: CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-linux-x86 -trimpath
- name: Build windows-x64
run: CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-windows-x64.exe -trimpath
- name: Build windows-x86
run: CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-windows-x86.exe -trimpath
- name: Build arm64
run: CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GOARM=7 go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-linux-arm64 -trimpath
- name: Build armv6
run: CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-linux-armv6 -trimpath
- name: Build mips
run: CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-linux-mips -trimpath
- name: Build mips-softfloat
run: CGO_ENABLED=0 GOOS=linux GOARCH=mips GOMIPS=softfloat go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-linux-mips-softfloat -trimpath
- name: Build mipsel
run: CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-linux-mipsel -trimpath
- name: Build mipsel-softfloat
run: CGO_ENABLED=0 GOOS=linux GOARCH=mipsle GOMIPS=softfloat go build -ldflags="-s -w -checklinkname=0" -o artifacts/wg-linux-mipsel-softfloat -trimpath
- name: Build
run: go build -ldflags="${LDFLAGS} -X ${VERSION_PKG}.Version=${GITHUB_REF_NAME#v}" -o wg-${{ matrix.name }}${{ matrix.ext }} -trimpath
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: wg-${{ matrix.name }}
path: wg-${{ matrix.name }}${{ matrix.ext }}
release:
name: Upload Release 🚀
needs: build
runs-on: ubuntu-latest
steps:
- name: Download artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
merge-multiple: true
- name: Upload binaries to release
uses: svenstaro/upload-release-action@v2
@@ -60,4 +77,4 @@ jobs:
file: artifacts/wg-*
tag: ${{ github.ref }}
overwrite: true
file_glob: true
file_glob: true

43
Dockerfile Normal file
View File

@@ -0,0 +1,43 @@
# syntax=docker/dockerfile:1.7
FROM --platform=$TARGETPLATFORM golang:1.25.0-bookworm AS build
ARG VERSION=dev
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod \
go mod download
COPY . .
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
go build -trimpath -ldflags="-s -w -checklinkname=0 -X github.com/fumiama/WireGold/config.Version=${VERSION}" \
-o /out/wg .
FROM debian:bookworm-slim
ENV DEBIAN_FRONTEND=noninteractive
LABEL org.opencontainers.image.title="WireGold" \
org.opencontainers.image.description="Container image for WireGold, a pure-Go Layer 3 VPN inspired by WireGuard." \
org.opencontainers.image.source="https://github.com/fumiama/WireGold"
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates iproute2 tini \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /config
COPY --from=build /out/wg /usr/local/bin/wg
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/wg /usr/local/bin/docker-entrypoint.sh \
&& mkdir -p /config
VOLUME ["/config"]
ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/docker-entrypoint.sh"]
CMD ["-c", "/config/config.yaml"]

View File

@@ -4,16 +4,38 @@
</a><br>
<h1>WireGold</h1>
Wire Golang Guard = WireGold<br><br>
English | [中文](README_ZH.md)
</div>
## Usage
> If you are running in windows, remember to select the `wintun.dll` of your arch in `lower/wintun` and place it alongside the compiled exe
## Overview
WireGold is a pure Go Layer 3 VPN inspired by WireGuard.
### Features
- **Encryption**: XChaCha20-Poly1305 (AEAD) + Curve25519 key exchange + BLAKE2B integrity check
- **Transport**: UDP / UDP-Lite / TCP / Raw IP / ICMP
- **Encoding**: Optional Base16384 encoding to traverse text-only filters
- **Anti-censorship**: XOR mask header obfuscation + randomized MTU scaling + optional double-send
- **Compression**: Optional Zstd payload compression
- **NAT traversal**: Built-in Hello/Query/Notify protocol for keepalive and hole punching
- **Routing**: Multi-hop forwarding with TTL decrement and routing table management
- **Key rotation**: 32 preshared key slots with random index selection per packet
## Usage
> On Windows, place the `wintun.dll` matching your architecture (from `lower/wintun/`) alongside the executable.
> For high-latency lossy links, consider pairing with [UDPspeeder](https://github.com/wangyu-/UDPspeeder).
> It is highly recommanded to use [UDPspeeder](https://github.com/wangyu-/UDPspeeder) together if you are using a High-latency Lossy Link
```bash
wg [-c config.yaml] [-d|w] [-g] [-h] [-p] [-l log.txt]
```
#### Instructions
#### Flags
```bash
-c string
specify conf file (default "config.yaml")
@@ -28,18 +50,21 @@ wg [-c config.yaml] [-d|w] [-g] [-h] [-p] [-l log.txt]
-w only show logs above warn level
```
## Config file example
## Configuration
- **macos mojave**: max mtu (under ipv4 endpoint) is `9159`
- **ipv6 endpoint**: the recommand mtu is `1280~1500` to prevent the big segments from being dropped
- **macOS Mojave**: max MTU (IPv4 endpoint) is `9159`
- **IPv6 endpoint**: recommended MTU `12801500` to avoid oversized segment drops
- **ICMP / Raw IP endpoint**: use bare IP address without port (e.g. `0.0.0.0`), requires root/admin privileges
```yaml
IP: 192.168.233.1
SubNet: 192.168.233.0/24
PrivateKey: 暲菉斂狧污爉窫擸紈卆帞蔩慈睠庮扝憚瞼縀
Network: udp # udp (default), udplite, tcp, ip, icmp
EndPoint: 0.0.0.0:56789
MTU: 1504
SpeedLoop: 4096
MaxTTL: 64
Mask: 0x1234567890abcdef
Base14: true
Peers:
@@ -68,11 +93,31 @@ Peers:
AllowTrans: false
```
## Benckmark on localhost
> This benckmark is tested on Mac Book Air M1 within battery mode.
### Configuration Reference
### UDP MTU 4096
```bash
| Field | Description |
|-------|-------------|
| `Network` | Transport protocol: `udp` (default), `udplite`, `tcp`, `ip`, `icmp` |
| `MaxTTL` | Initial TTL for outgoing packets; default `64` |
| `SpeedLoop` | Log receive throughput statistics every N packets; default `4096` |
| `AllowedIPs` | Prefix `x` to accept packets from the subnet without creating a system route; prefix `y` to add an internal route table entry only |
| `Mask` | XOR mask for header obfuscation |
| `Base14` | Enable Base16384 encoding |
| `MTURandomRange` | Randomly shrink MTU by up to this value (never grows), adding traffic fingerprint randomness |
| `DoublePacket` | Send every packet twice to counter heavy packet loss |
| `KeepAliveSeconds` | NAT keepalive interval in seconds; 0 disables keepalive |
| `QueryList` | Peer IPs to query for NAT traversal |
| `UseZstd` | Enable Zstd compression |
| `AllowTrans` | Allow this peer to relay traffic for other peers |
## Benchmark (localhost)
> MacBook Air M1, battery mode
<details>
<summary>UDP MTU 4096</summary>
```
goos: darwin
goarch: arm64
pkg: github.com/fumiama/WireGold/upper/services/tunnel
@@ -102,8 +147,12 @@ BenchmarkTunnelUDP/4096-normal-b14-8 2620 432984 ns/op
BenchmarkTunnelUDP/4096-preshared-nob14-8 2750 395736 ns/op 10.35 MB/s 7348747 B/op 315 allocs/op
BenchmarkTunnelUDP/4096-preshared-b14-8 2628 431785 ns/op 9.49 MB/s 7961597 B/op 407 allocs/op
```
### UDP MTU 1024
```bash
</details>
<details>
<summary>UDP MTU 1024</summary>
```
goos: darwin
goarch: arm64
pkg: github.com/fumiama/WireGold/upper/services/tunnel
@@ -133,8 +182,12 @@ BenchmarkTunnelUDPSmallMTU/4096-normal-b14-8 2240 504749 ns/op
BenchmarkTunnelUDPSmallMTU/4096-preshared-nob14-8 2594 392716 ns/op 10.43 MB/s 7480678 B/op 460 allocs/op
BenchmarkTunnelUDPSmallMTU/4096-preshared-b14-8 2234 506134 ns/op 8.09 MB/s 9066223 B/op 691 allocs/op
```
### TCP MTU 4096
```bash
</details>
<details>
<summary>TCP MTU 4096</summary>
```
goos: darwin
goarch: arm64
pkg: github.com/fumiama/WireGold/upper/services/tunnel
@@ -164,8 +217,12 @@ BenchmarkTunnelTCP/4096-normal-b14-8 2374 465704 ns/op
BenchmarkTunnelTCP/4096-preshared-nob14-8 2532 436310 ns/op 9.39 MB/s 7510565 B/op 477 allocs/op
BenchmarkTunnelTCP/4096-preshared-b14-8 2360 459261 ns/op 8.92 MB/s 8037878 B/op 566 allocs/op
```
### TCP MTU 1024
```bash
</details>
<details>
<summary>TCP MTU 1024</summary>
```
goos: darwin
goarch: arm64
pkg: github.com/fumiama/WireGold/upper/services/tunnel
@@ -195,3 +252,4 @@ BenchmarkTunnelTCPSmallMTU/4096-normal-b14-8 1868 564007 ns/op
BenchmarkTunnelTCPSmallMTU/4096-preshared-nob14-8 2263 491698 ns/op 8.33 MB/s 7925404 B/op 869 allocs/op
BenchmarkTunnelTCPSmallMTU/4096-preshared-b14-8 2050 559663 ns/op 7.32 MB/s 9211292 B/op 1086 allocs/op
```
</details>

254
README_ZH.md Normal file
View File

@@ -0,0 +1,254 @@
<div align="center">
<a href="https://crypko.ai/crypko/G39ZPfer7g6rz/">
<img src=".github/Maria.png" width = "400" alt="WireGold-Maria">
</a><br>
<h1>WireGold</h1>
Wire Golang Guard = WireGold<br><br>
[English](README.md) | 中文
</div>
## 概述
WireGold 是一个纯 Go 实现的第 3 层 VPN灵感来自 WireGuard。
### 主要特性
- **加密**: XChaCha20-Poly1305 (AEAD) + Curve25519 密钥交换 + BLAKE2B 完整性校验
- **传输**: 支持 UDP / UDP-Lite / TCP / Raw IP / ICMP 多种底层传输
- **编码**: 可选 Base16384 编码以穿越文本过滤
- **抗审查**: XOR 掩码混淆报头 + 随机 MTU 放缩 + 可选双倍发包
- **压缩**: 可选 Zstd 数据压缩
- **NAT 穿透**: 内置 Hello/Query/Notify 协议实现 NAT 保活与穿透
- **路由转发**: 支持多跳转发 (TTL 递减) 与路由表管理
- **密钥集**: 支持 32 组预共享密钥混合,随机选择密钥索引
## 使用方法
> Windows 用户需将对应架构的 `wintun.dll` (位于 `lower/wintun/`) 放在可执行文件同目录下
> 高延迟有损链路建议配合 [UDPspeeder](https://github.com/wangyu-/UDPspeeder) 使用
```bash
wg [-c config.yaml] [-d|w] [-g] [-h] [-p] [-l log.txt]
```
#### 参数说明
```bash
-c string
指定配置文件 (默认 "config.yaml")
-d 输出调试日志
-g 生成密钥对
-h 显示帮助
-l string
将日志写入文件 (默认 "-")
-p 显示本机公钥
-pg
生成预共享密钥
-w 仅显示 warn 及以上级别日志
```
## 配置文件示例
- **macOS Mojave**: 最大 MTU (IPv4 endpoint) 为 `9159`
- **IPv6 endpoint**: 推荐 MTU `1280~1500`,避免大分片被丢弃
- **ICMP / Raw IP endpoint**: 使用裸 IP 地址,无需端口号 (如 `0.0.0.0`)。需要 root/管理员权限
```yaml
IP: 192.168.233.1
SubNet: 192.168.233.0/24
PrivateKey: 暲菉斂狧污爉窫擸紈卆帞蔩慈睠庮扝憚瞼縀
Network: udp # udp (默认), udplite, tcp, ip, icmp
EndPoint: 0.0.0.0:56789
MTU: 1504
SpeedLoop: 4096
MaxTTL: 64
Mask: 0x1234567890abcdef
Base14: true
Peers:
-
IP: "192.168.233.2"
PublicKey: 徯萃嵾爻燸攗窍褃冔蒔犡緇袿屿組待族砇嘀
PresharedKey: 瀸敀爅崾嘊嵜紼樴稍毯攣矐訷蟷扛嬋庩崛昀
EndPoint: 1.2.3.4:56789
AllowedIPs: ["192.168.233.2/32", "x192.168.233.3/32"]
KeepAliveSeconds: 0
QueryList: ["192.168.233.3"]
MTU: 1400
MTURandomRange: 128
UseZstd: true
QuerySeconds: 10
AllowTrans: true
-
IP: "192.168.233.3"
PublicKey: 牢喨粷詸衭譛浾蘹櫠砙杹蟫瑳叩刋橋経挵蘀
PresharedKey: 竅琚喫従痸告烈兇厕趭萨假蔛瀇譄施烸蝫瘀
EndPoint: ""
AllowedIPs: ["192.168.233.3/32", "y192.168.66.1/32"]
MTU: 752
DoublePacket: true
KeepAliveSeconds: 0
AllowTrans: false
```
### 配置字段说明
| 字段 | 说明 |
|------|------|
| `Network` | 传输协议: `udp` (默认), `udplite`, `tcp`, `ip`, `icmp` |
| `MaxTTL` | 发包初始 TTL默认 `64` |
| `SpeedLoop` | 每收到 N 个包时输出一次吞吐统计,默认 `4096` |
| `AllowedIPs` | 前缀 `x` 表示只接受该网段报文但不建系统路由;前缀 `y` 表示只添加内部路由表条目 |
| `Mask` | XOR 掩码,用于混淆报头 |
| `Base14` | 启用 Base16384 编码 |
| `MTURandomRange` | 随机缩小 MTU 的范围 (只减不增),增加流量特征随机性 |
| `DoublePacket` | 双倍发包以对抗强丢包链路 |
| `KeepAliveSeconds` | NAT 保活间隔 (秒)0 为不保活 |
| `QueryList` | NAT 穿透时查询的对端 IP 列表 |
| `UseZstd` | 启用 Zstd 压缩 |
| `AllowTrans` | 是否允许为其他 Peer 转发流量 |
## 本地基准测试
> Mac Book Air M1电池供电模式
<details>
<summary>UDP MTU 4096</summary>
```
goos: darwin
goarch: arm64
pkg: github.com/fumiama/WireGold/upper/services/tunnel
cpu: Apple M1
BenchmarkTunnelUDP/1024-plain-nob14-8 4938 228283 ns/op 4.49 MB/s 3642671 B/op 149 allocs/op
BenchmarkTunnelUDP/1024-normal-nob14-8 5100 234118 ns/op 4.37 MB/s 3642409 B/op 147 allocs/op
BenchmarkTunnelUDP/1024-plain-b14-8 4528 249429 ns/op 4.11 MB/s 3825461 B/op 179 allocs/op
BenchmarkTunnelUDP/1024-normal-b14-8 4885 242048 ns/op 4.23 MB/s 3818262 B/op 175 allocs/op
BenchmarkTunnelUDP/1024-preshared-nob14-8 4833 242460 ns/op 4.22 MB/s 3632537 B/op 144 allocs/op
BenchmarkTunnelUDP/1024-preshared-b14-8 4348 239630 ns/op 4.27 MB/s 3820118 B/op 174 allocs/op
BenchmarkTunnelUDP/2048-plain-nob14-8 4766 280419 ns/op 7.30 MB/s 3656588 B/op 148 allocs/op
BenchmarkTunnelUDP/2048-normal-nob14-8 4353 250150 ns/op 8.19 MB/s 3639053 B/op 145 allocs/op
BenchmarkTunnelUDP/2048-plain-b14-8 4136 278223 ns/op 7.36 MB/s 3848032 B/op 178 allocs/op
BenchmarkTunnelUDP/2048-normal-b14-8 4264 268694 ns/op 7.62 MB/s 3842609 B/op 176 allocs/op
BenchmarkTunnelUDP/2048-preshared-nob14-8 4154 262575 ns/op 7.80 MB/s 3640443 B/op 144 allocs/op
BenchmarkTunnelUDP/2048-preshared-b14-8 3932 287082 ns/op 7.13 MB/s 3846167 B/op 176 allocs/op
BenchmarkTunnelUDP/3072-plain-nob14-8 4006 267281 ns/op 11.49 MB/s 3690985 B/op 164 allocs/op
BenchmarkTunnelUDP/3072-normal-nob14-8 3942 271832 ns/op 11.30 MB/s 3670827 B/op 162 allocs/op
BenchmarkTunnelUDP/3072-plain-b14-8 3529 291120 ns/op 10.55 MB/s 3993371 B/op 211 allocs/op
BenchmarkTunnelUDP/3072-normal-b14-8 3614 298778 ns/op 10.28 MB/s 3994267 B/op 211 allocs/op
BenchmarkTunnelUDP/3072-preshared-nob14-8 4036 297819 ns/op 10.31 MB/s 3674026 B/op 162 allocs/op
BenchmarkTunnelUDP/3072-preshared-b14-8 3705 300820 ns/op 10.21 MB/s 3989965 B/op 210 allocs/op
BenchmarkTunnelUDP/4096-plain-nob14-8 2604 398308 ns/op 10.28 MB/s 7389986 B/op 320 allocs/op
BenchmarkTunnelUDP/4096-normal-nob14-8 2744 399739 ns/op 10.25 MB/s 7348911 B/op 316 allocs/op
BenchmarkTunnelUDP/4096-plain-b14-8 2788 430813 ns/op 9.51 MB/s 7965100 B/op 410 allocs/op
BenchmarkTunnelUDP/4096-normal-b14-8 2620 432984 ns/op 9.46 MB/s 7957374 B/op 407 allocs/op
BenchmarkTunnelUDP/4096-preshared-nob14-8 2750 395736 ns/op 10.35 MB/s 7348747 B/op 315 allocs/op
BenchmarkTunnelUDP/4096-preshared-b14-8 2628 431785 ns/op 9.49 MB/s 7961597 B/op 407 allocs/op
```
</details>
<details>
<summary>UDP MTU 1024</summary>
```
goos: darwin
goarch: arm64
pkg: github.com/fumiama/WireGold/upper/services/tunnel
cpu: Apple M1
BenchmarkTunnelUDPSmallMTU/1024-plain-nob14-8 4770 256794 ns/op 3.99 MB/s 3715458 B/op 193 allocs/op
BenchmarkTunnelUDPSmallMTU/1024-normal-nob14-8 4945 242538 ns/op 4.22 MB/s 3681420 B/op 188 allocs/op
BenchmarkTunnelUDPSmallMTU/1024-plain-b14-8 4137 269202 ns/op 3.80 MB/s 4101089 B/op 254 allocs/op
BenchmarkTunnelUDPSmallMTU/1024-normal-b14-8 4592 253461 ns/op 4.04 MB/s 4109262 B/op 253 allocs/op
BenchmarkTunnelUDPSmallMTU/1024-preshared-nob14-8 4764 243752 ns/op 4.20 MB/s 3675691 B/op 186 allocs/op
BenchmarkTunnelUDPSmallMTU/1024-preshared-b14-8 4086 282682 ns/op 3.62 MB/s 4107240 B/op 253 allocs/op
BenchmarkTunnelUDPSmallMTU/2048-plain-nob14-8 4728 252759 ns/op 8.10 MB/s 3762231 B/op 234 allocs/op
BenchmarkTunnelUDPSmallMTU/2048-normal-nob14-8 4245 257036 ns/op 7.97 MB/s 3729842 B/op 232 allocs/op
BenchmarkTunnelUDPSmallMTU/2048-plain-b14-8 3615 308642 ns/op 6.64 MB/s 4469625 B/op 342 allocs/op
BenchmarkTunnelUDPSmallMTU/2048-normal-b14-8 3624 311780 ns/op 6.57 MB/s 4487346 B/op 345 allocs/op
BenchmarkTunnelUDPSmallMTU/2048-preshared-nob14-8 3999 260043 ns/op 7.88 MB/s 3723444 B/op 231 allocs/op
BenchmarkTunnelUDPSmallMTU/2048-preshared-b14-8 3558 315744 ns/op 6.49 MB/s 4476565 B/op 343 allocs/op
BenchmarkTunnelUDPSmallMTU/3072-plain-nob14-8 3814 265654 ns/op 11.56 MB/s 3802900 B/op 280 allocs/op
BenchmarkTunnelUDPSmallMTU/3072-normal-nob14-8 4380 291992 ns/op 10.52 MB/s 3760254 B/op 276 allocs/op
BenchmarkTunnelUDPSmallMTU/3072-plain-b14-8 3340 338760 ns/op 9.07 MB/s 4849826 B/op 434 allocs/op
BenchmarkTunnelUDPSmallMTU/3072-normal-b14-8 3302 345620 ns/op 8.89 MB/s 4852322 B/op 434 allocs/op
BenchmarkTunnelUDPSmallMTU/3072-preshared-nob14-8 4424 265290 ns/op 11.58 MB/s 3761816 B/op 277 allocs/op
BenchmarkTunnelUDPSmallMTU/3072-preshared-b14-8 3148 344490 ns/op 8.92 MB/s 4849613 B/op 434 allocs/op
BenchmarkTunnelUDPSmallMTU/4096-plain-nob14-8 2586 399489 ns/op 10.25 MB/s 7570823 B/op 467 allocs/op
BenchmarkTunnelUDPSmallMTU/4096-normal-nob14-8 2576 402297 ns/op 10.18 MB/s 7504731 B/op 464 allocs/op
BenchmarkTunnelUDPSmallMTU/4096-plain-b14-8 2240 484812 ns/op 8.45 MB/s 9081331 B/op 696 allocs/op
BenchmarkTunnelUDPSmallMTU/4096-normal-b14-8 2240 504749 ns/op 8.11 MB/s 9069168 B/op 693 allocs/op
BenchmarkTunnelUDPSmallMTU/4096-preshared-nob14-8 2594 392716 ns/op 10.43 MB/s 7480678 B/op 460 allocs/op
BenchmarkTunnelUDPSmallMTU/4096-preshared-b14-8 2234 506134 ns/op 8.09 MB/s 9066223 B/op 691 allocs/op
```
</details>
<details>
<summary>TCP MTU 4096</summary>
```
goos: darwin
goarch: arm64
pkg: github.com/fumiama/WireGold/upper/services/tunnel
cpu: Apple M1
BenchmarkTunnelTCP/1024-plain-nob14-8 4627 246837 ns/op 4.15 MB/s 3684040 B/op 201 allocs/op
BenchmarkTunnelTCP/1024-normal-nob14-8 4833 257150 ns/op 3.98 MB/s 3682260 B/op 199 allocs/op
BenchmarkTunnelTCP/1024-plain-b14-8 4396 272838 ns/op 3.75 MB/s 3850134 B/op 231 allocs/op
BenchmarkTunnelTCP/1024-normal-b14-8 4104 252293 ns/op 4.06 MB/s 3844674 B/op 226 allocs/op
BenchmarkTunnelTCP/1024-preshared-nob14-8 4530 264767 ns/op 3.87 MB/s 3680243 B/op 197 allocs/op
BenchmarkTunnelTCP/1024-preshared-b14-8 4231 287111 ns/op 3.57 MB/s 3847164 B/op 227 allocs/op
BenchmarkTunnelTCP/2048-plain-nob14-8 4275 276425 ns/op 7.41 MB/s 3698728 B/op 200 allocs/op
BenchmarkTunnelTCP/2048-normal-nob14-8 4033 261234 ns/op 7.84 MB/s 3701433 B/op 200 allocs/op
BenchmarkTunnelTCP/2048-plain-b14-8 3680 303246 ns/op 6.75 MB/s 3875541 B/op 231 allocs/op
BenchmarkTunnelTCP/2048-normal-b14-8 3626 288219 ns/op 7.11 MB/s 3878505 B/op 230 allocs/op
BenchmarkTunnelTCP/2048-preshared-nob14-8 3868 287679 ns/op 7.12 MB/s 3696931 B/op 200 allocs/op
BenchmarkTunnelTCP/2048-preshared-b14-8 3586 305008 ns/op 6.71 MB/s 3878416 B/op 230 allocs/op
BenchmarkTunnelTCP/3072-plain-nob14-8 3666 298452 ns/op 10.29 MB/s 3767509 B/op 246 allocs/op
BenchmarkTunnelTCP/3072-normal-nob14-8 3450 304848 ns/op 10.08 MB/s 3761811 B/op 246 allocs/op
BenchmarkTunnelTCP/3072-plain-b14-8 3549 315641 ns/op 9.73 MB/s 4032830 B/op 291 allocs/op
BenchmarkTunnelTCP/3072-normal-b14-8 3440 327234 ns/op 9.39 MB/s 4038470 B/op 292 allocs/op
BenchmarkTunnelTCP/3072-preshared-nob14-8 3522 302663 ns/op 10.15 MB/s 3760304 B/op 245 allocs/op
BenchmarkTunnelTCP/3072-preshared-b14-8 3390 326384 ns/op 9.41 MB/s 4040489 B/op 293 allocs/op
BenchmarkTunnelTCP/4096-plain-nob14-8 2431 435457 ns/op 9.41 MB/s 7515476 B/op 480 allocs/op
BenchmarkTunnelTCP/4096-normal-nob14-8 2500 433178 ns/op 9.46 MB/s 7511114 B/op 478 allocs/op
BenchmarkTunnelTCP/4096-plain-b14-8 2337 457177 ns/op 8.96 MB/s 8033760 B/op 568 allocs/op
BenchmarkTunnelTCP/4096-normal-b14-8 2374 465704 ns/op 8.80 MB/s 8040812 B/op 567 allocs/op
BenchmarkTunnelTCP/4096-preshared-nob14-8 2532 436310 ns/op 9.39 MB/s 7510565 B/op 477 allocs/op
BenchmarkTunnelTCP/4096-preshared-b14-8 2360 459261 ns/op 8.92 MB/s 8037878 B/op 566 allocs/op
```
</details>
<details>
<summary>TCP MTU 1024</summary>
```
goos: darwin
goarch: arm64
pkg: github.com/fumiama/WireGold/upper/services/tunnel
cpu: Apple M1
BenchmarkTunnelTCPSmallMTU/1024-plain-nob14-8 3318 312084 ns/op 3.28 MB/s 3797015 B/op 307 allocs/op
BenchmarkTunnelTCPSmallMTU/1024-normal-nob14-8 4102 303641 ns/op 3.37 MB/s 3795618 B/op 308 allocs/op
BenchmarkTunnelTCPSmallMTU/1024-plain-b14-8 3746 314102 ns/op 3.26 MB/s 4147318 B/op 368 allocs/op
BenchmarkTunnelTCPSmallMTU/1024-normal-b14-8 3609 315252 ns/op 3.25 MB/s 4152014 B/op 368 allocs/op
BenchmarkTunnelTCPSmallMTU/1024-preshared-nob14-8 3826 300693 ns/op 3.41 MB/s 3793725 B/op 304 allocs/op
BenchmarkTunnelTCPSmallMTU/1024-preshared-b14-8 3628 327852 ns/op 3.12 MB/s 4150869 B/op 367 allocs/op
BenchmarkTunnelTCPSmallMTU/2048-plain-nob14-8 3553 315709 ns/op 6.49 MB/s 3945193 B/op 426 allocs/op
BenchmarkTunnelTCPSmallMTU/2048-normal-nob14-8 3254 329794 ns/op 6.21 MB/s 3933224 B/op 427 allocs/op
BenchmarkTunnelTCPSmallMTU/2048-plain-b14-8 3222 357250 ns/op 5.73 MB/s 4538189 B/op 529 allocs/op
BenchmarkTunnelTCPSmallMTU/2048-normal-b14-8 3080 359401 ns/op 5.70 MB/s 4555108 B/op 535 allocs/op
BenchmarkTunnelTCPSmallMTU/2048-preshared-nob14-8 3463 320078 ns/op 6.40 MB/s 3936771 B/op 426 allocs/op
BenchmarkTunnelTCPSmallMTU/2048-preshared-b14-8 2990 363645 ns/op 5.63 MB/s 4555897 B/op 535 allocs/op
BenchmarkTunnelTCPSmallMTU/3072-plain-nob14-8 3228 336736 ns/op 9.12 MB/s 4090750 B/op 550 allocs/op
BenchmarkTunnelTCPSmallMTU/3072-normal-nob14-8 3076 347067 ns/op 8.85 MB/s 4084480 B/op 554 allocs/op
BenchmarkTunnelTCPSmallMTU/3072-plain-b14-8 2798 395353 ns/op 7.77 MB/s 4952186 B/op 700 allocs/op
BenchmarkTunnelTCPSmallMTU/3072-normal-b14-8 2725 403959 ns/op 7.60 MB/s 4965324 B/op 705 allocs/op
BenchmarkTunnelTCPSmallMTU/3072-preshared-nob14-8 3366 344086 ns/op 8.93 MB/s 4080821 B/op 549 allocs/op
BenchmarkTunnelTCPSmallMTU/3072-preshared-b14-8 2797 403142 ns/op 7.62 MB/s 4962100 B/op 703 allocs/op
BenchmarkTunnelTCPSmallMTU/4096-plain-nob14-8 2360 490867 ns/op 8.34 MB/s 7940290 B/op 871 allocs/op
BenchmarkTunnelTCPSmallMTU/4096-normal-nob14-8 2223 486839 ns/op 8.41 MB/s 7927235 B/op 872 allocs/op
BenchmarkTunnelTCPSmallMTU/4096-plain-b14-8 2002 557560 ns/op 7.35 MB/s 9201342 B/op 1087 allocs/op
BenchmarkTunnelTCPSmallMTU/4096-normal-b14-8 1868 564007 ns/op 7.26 MB/s 9216972 B/op 1091 allocs/op
BenchmarkTunnelTCPSmallMTU/4096-preshared-nob14-8 2263 491698 ns/op 8.33 MB/s 7925404 B/op 869 allocs/op
BenchmarkTunnelTCPSmallMTU/4096-preshared-b14-8 2050 559663 ns/op 7.32 MB/s 9211292 B/op 1086 allocs/op
```
</details>

View File

@@ -1,3 +1,16 @@
package config
import "time"
// ShowDebugLog turn on to print verbose logs.
const ShowDebugLog = false
// Version will show in help message to distinguish different builds.
// Use -ldflags="-X github.com/fumiama/WireGold/config.Version=x.y.z" to override.
var Version = "dev"
func init() {
if Version == "dev" {
Version = "dev-" + time.Now().Format(time.DateOnly)
}
}

42
docker-entrypoint.sh Normal file
View File

@@ -0,0 +1,42 @@
#!/bin/sh
set -eu
if [ "$#" -eq 0 ]; then
set -- /usr/local/bin/wg -c /config/config.yaml
elif [ "${1#-}" != "$1" ]; then
set -- /usr/local/bin/wg "$@"
fi
if [ "${1:-}" = "/usr/local/bin/wg" ]; then
need_config=1
config_path=/config/config.yaml
prev=
for arg in "$@"; do
case "$arg" in
-g|-pg|-h)
need_config=0
;;
esac
if [ "$prev" = "-c" ]; then
config_path="$arg"
fi
prev="$arg"
done
if [ "$need_config" -eq 1 ] && [ ! -c /dev/net/tun ]; then
echo "WireGold requires /dev/net/tun inside the container." >&2
echo "Run with: --device /dev/net/tun --cap-add NET_ADMIN" >&2
echo "If Network is icmp or ip, add --cap-add NET_RAW as well." >&2
exit 1
fi
if [ "$need_config" -eq 1 ] && [ ! -f "$config_path" ]; then
echo "WireGold config not found: $config_path" >&2
echo "Mount your config into /config or override -c." >&2
exit 1
fi
fi
exec "$@"

9
go.mod
View File

@@ -3,7 +3,7 @@ module github.com/fumiama/WireGold
go 1.25.0
require (
github.com/FloatTech/ttl v0.0.0-20250224045156-012b1463287d
github.com/FloatTech/ttl v0.0.0-20260412050038-bd89b9d66fcd
github.com/RomiChan/syncx v0.0.0-20240418144900-b7402ffdebc7
github.com/fumiama/blake2b-simd v0.0.0-20250228045919-a5dcaba5419a
github.com/fumiama/go-base16384 v1.7.1
@@ -12,12 +12,13 @@ require (
github.com/fumiama/water v0.0.0-20211231134027-da391938d6ac
github.com/klauspost/compress v1.18.5
github.com/sirupsen/logrus v1.9.4
golang.org/x/crypto v0.49.0
golang.org/x/crypto v0.50.0
golang.org/x/net v0.53.0
golang.org/x/sys v0.43.0
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/fumiama/wintun v0.0.0-20211229152851-8bc97c8034c0 // indirect
golang.org/x/sys v0.42.0 // indirect
golang.org/x/text v0.35.0 // indirect
golang.org/x/text v0.36.0 // indirect
)

18
go.sum
View File

@@ -1,5 +1,5 @@
github.com/FloatTech/ttl v0.0.0-20250224045156-012b1463287d h1:mUQ/c3wXKsUGa4Sg9DBy01APXKB68PmobhxOyaJI7lY=
github.com/FloatTech/ttl v0.0.0-20250224045156-012b1463287d/go.mod h1:fHZFWGquNXuHttu9dUYoKuNbm3dzLETnIOnm1muSfDs=
github.com/FloatTech/ttl v0.0.0-20260412050038-bd89b9d66fcd h1:Dt86dtJ5hPFvDIA8cAFYfO+Vc8ikoGf32ndEhbwjYXM=
github.com/FloatTech/ttl v0.0.0-20260412050038-bd89b9d66fcd/go.mod h1:fHZFWGquNXuHttu9dUYoKuNbm3dzLETnIOnm1muSfDs=
github.com/RomiChan/syncx v0.0.0-20240418144900-b7402ffdebc7 h1:S/ferNiehVjNaBMNNBxUjLtVmP/YWD6Yh79RfPv4ehU=
github.com/RomiChan/syncx v0.0.0-20240418144900-b7402ffdebc7/go.mod h1:vD7Ra3Q9onRtojoY5sMCLQ7JBgjUsrXDnDKyFxqpf9w=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -30,18 +30,20 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@@ -5,7 +5,6 @@ import (
"errors"
"net"
"sync/atomic"
"time"
"github.com/fumiama/WireGold/config"
"github.com/fumiama/WireGold/gold/head"
@@ -46,8 +45,8 @@ type Link struct {
keys [32]cipher.AEAD
// 本机信息
me *Me
// 最后一次收到报文的时间
lastalive *time.Time
// 最后一次收到报文的时间 (UnixNano)
lastalive atomic.Int64
// 是否允许转发
allowtrans bool
// 是否对数据进行 zstd 压缩

View File

@@ -208,7 +208,10 @@ func (m *Me) NetworkConfigs() []any {
func (m *Me) Close() error {
for i := 0; i < len(m.jobs); i++ {
close(m.jobs[i])
jb := m.jobs[i]
if jb != nil {
close(jb)
}
}
m.connections = nil
if bin.IsNonNilInterface(m.conn) {

View File

@@ -2,9 +2,7 @@ package link
import (
"encoding/json"
"sync/atomic"
"time"
"unsafe"
"github.com/sirupsen/logrus"
@@ -23,8 +21,8 @@ func (l *Link) keepAlive(dur int64) {
if l.me.connections == nil {
return
}
la := (*time.Time)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&l.lastalive))))
if la != nil && time.Since(*la) > 10*time.Second*time.Duration(dur) { // 可能已经被阻断, 断开重连
la := l.lastalive.Load()
if la != 0 && time.Since(time.Unix(0, la)) > 10*time.Second*time.Duration(dur) { // 可能已经被阻断, 断开重连
logrus.Warnln(file.Header(), "no response after 10 keep alive tries, re-connecting...")
err := l.me.Restart()
if err != nil {

View File

@@ -2,9 +2,7 @@ package link
import (
"net"
"sync/atomic"
"time"
"unsafe"
curve "github.com/fumiama/go-x25519"
"github.com/sirupsen/logrus"
@@ -139,8 +137,8 @@ func (m *Me) extractPeer(srcip, dstip net.IP, addr p2p.EndPoint) *Link {
logrus.Warnln(file.Header(), "packet from", srcip, "to", dstip, "is refused")
return nil
}
if bin.IsNilInterface(p.endpoint) || !p.endpoint.Euqal(addr) {
if m.ep.Network() == "tcp" && !addr.Euqal(p.endpoint) {
if bin.IsNilInterface(p.endpoint) || !p.endpoint.Equal(addr) {
if m.ep.Network() == "tcp" && !addr.Equal(p.endpoint) {
logrus.Infoln(file.Header(), "set endpoint of peer", p.peerip, "to", addr.String())
p.endpoint = addr
} else { // others are all no status link
@@ -148,7 +146,6 @@ func (m *Me) extractPeer(srcip, dstip net.IP, addr p2p.EndPoint) *Link {
p.endpoint = addr
}
}
now := time.Now()
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&p.lastalive)), unsafe.Pointer(&now))
p.lastalive.Store(time.Now().UnixNano())
return p
}

View File

@@ -152,10 +152,18 @@ func (m *Me) wait(data []byte, addr p2p.EndPoint) (h head.PacketBytes) {
h, got := m.recving.GetOrSet(uint16(seq), header)
if got {
if h == header {
if !h.HasInit() {
// GetOrSet found an expired entry: it deleted it and
// returned zero-value while reporting got=true, but did
// NOT store our header. Re-store it now.
m.recving.Set(uint16(seq), header)
h = header
got = false
} else if h == header {
panic("unexpected multi-put found")
} else {
header.ManualDestroy()
}
header.ManualDestroy()
}
if config.ShowDebugLog {
logrus.Debugln("[recv]", strconv.FormatUint(uint64(seq&0xffff), 16), "get frag part isnew:", !got)

View File

@@ -75,16 +75,12 @@ func (l *Link) write2peer(b pbuf.Bytes, seq uint32) {
if l.doublepacket {
err := l.write2peer1(b, seq)
if err != nil {
if config.ShowDebugLog {
logrus.Warnln("[send] double wr2peer", l.peerip, "err:", err)
}
logrus.Warnln("[send] double wr2peer", l.peerip, "err:", err)
}
}
err := l.write2peer1(b, seq)
if err != nil {
if config.ShowDebugLog {
logrus.Warnln("[send] wr2peer", l.peerip, "err:", err)
}
logrus.Warnln("[send] wr2peer", l.peerip, "err:", err)
}
}

View File

@@ -23,7 +23,7 @@ func Register(network string, initializer Initializer) (actual Initializer, hase
type EndPoint interface {
fmt.Stringer
Network() string
Euqal(EndPoint) bool
Equal(EndPoint) bool
Listen() (Conn, error)
}

295
gold/p2p/icmp/icmp.go Normal file
View File

@@ -0,0 +1,295 @@
package icmp
import (
"errors"
"net"
"net/netip"
"os"
"sync"
"sync/atomic"
"github.com/RomiChan/syncx"
"github.com/fumiama/WireGold/config"
"github.com/fumiama/WireGold/gold/p2p"
"github.com/fumiama/orbyte/pbuf"
"github.com/sirupsen/logrus"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
var (
ErrInvalidBodyType = errors.New("invalid body type")
)
var (
echoid = os.Getpid()
)
// seqFIFO is a FIFO queue that generates new sequence numbers when empty.
type seqFIFO struct {
mu sync.Mutex
q []uintptr
next *atomic.Uintptr
}
func (f *seqFIFO) Get() uintptr {
f.mu.Lock()
defer f.mu.Unlock()
if len(f.q) > 0 {
v := f.q[0]
copy(f.q, f.q[1:])
f.q = f.q[:len(f.q)-1]
return v
}
return f.next.Add(1)
}
func (f *seqFIFO) Put(v uintptr) {
f.mu.Lock()
defer f.mu.Unlock()
if len(f.q) == 0 {
f.q = make([]uintptr, 1, 128)
f.q[0] = v
return
}
if len(f.q) < cap(f.q) {
f.q = append(f.q, v)
return
}
copy(f.q, f.q[1:])
f.q[len(f.q)-1] = v
}
// peerState holds per-peer ICMP echo state within a Conn.
type peerState struct {
id int
seq atomic.Uintptr
seqfifo seqFIFO
}
func newPeerState() *peerState {
ps := &peerState{}
ps.seqfifo.next = &ps.seq
return ps
}
type EndPoint netip.Addr
func (ep *EndPoint) String() string {
return (*netip.Addr)(ep).String()
}
func (ep *EndPoint) Network() string {
return "icmp"
}
func (ep *EndPoint) Equal(ep2 p2p.EndPoint) bool {
if ep == nil || ep2 == nil {
return ep == nil && ep2 == nil
}
ipep2, ok := ep2.(*EndPoint)
if !ok {
return false
}
ipep1 := ep
return (*netip.Addr)(ipep1).Compare(*(*netip.Addr)(ipep2)) == 0
}
// network get ipv4/ipv6 info and choose different options.
func (ep *EndPoint) network() (string, *netip.Addr) {
nw := "ip4:icmp"
if (*netip.Addr)(ep).Is6() {
nw = "ip6:ipv6-icmp"
}
return nw, (*netip.Addr)(ep)
}
func (ep *EndPoint) Listen() (p2p.Conn, error) {
nw, addr := ep.network()
conn, err := icmp.ListenPacket(nw, addr.String())
if err != nil {
return nil, err
}
return &Conn{inner: conn}, nil
}
type Conn struct {
inner *icmp.PacketConn
peers syncx.Map[netip.Addr, *peerState]
}
func (conn *Conn) getOrCreatePeerState(addr netip.Addr) *peerState {
if ps, ok := conn.peers.Load(addr); ok {
return ps
}
ps := newPeerState()
actual, _ := conn.peers.LoadOrStore(addr, ps)
return actual
}
func (conn *Conn) Close() error {
return conn.inner.Close()
}
func (conn *Conn) String() string {
return conn.inner.LocalAddr().String()
}
func (conn *Conn) LocalAddr() p2p.EndPoint {
eps := conn.inner.LocalAddr().String()
addr, err := netip.ParseAddrPort(eps)
if err == nil {
eps = addr.Addr().String()
}
ep, _ := NewEndpoint(eps)
return ep
}
func (conn *Conn) ReadFromPeer(b []byte) (n int, ep p2p.EndPoint, err error) {
buf := pbuf.NewBytes(8192)
defer buf.ManualDestroy()
var ipaddr netip.Addr
buf.V(func(data []byte) {
ok := false
var msg *icmp.Message
for !ok {
var (
cnt int
addr net.Addr
)
cnt, addr, err = conn.inner.ReadFrom(data)
if err != nil {
if config.ShowDebugLog {
logrus.Debugln("[icmp] recv ReadFrom err:", err)
}
return
}
ipaddr, err = netip.ParseAddr(addr.String())
if err != nil {
if config.ShowDebugLog {
logrus.Debugln("[icmp] recv ParseAddr err:", err, ", addr:", addr)
}
return
}
ep, err = NewEndpoint(ipaddr.String())
if err != nil {
if config.ShowDebugLog {
logrus.Debugln("[icmp] recv NewEndpoint err:", err, ", addr:", addr)
}
return
}
proton := ipv4.ICMPTypeEcho.Protocol()
if ipaddr.Is6() {
proton = ipv6.ICMPTypeEchoRequest.Protocol()
}
msg, err = icmp.ParseMessage(proton, data[:cnt])
if err != nil {
if config.ShowDebugLog {
logrus.Debugln("[icmp] recv ParseMessage err:", err, ", addr:", addr)
}
return
}
ok = msg.Type == ipv4.ICMPTypeEcho || msg.Type == ipv4.ICMPTypeEchoReply
if ipaddr.Is6() {
ok = msg.Type == ipv6.ICMPTypeEchoRequest || msg.Type == ipv6.ICMPTypeEchoReply
}
ok = ok && msg.Code == 1
if config.ShowDebugLog {
logrus.Debugln("[icmp] recv from", ipaddr, ", is valid:", ok)
}
}
body, okk := msg.Body.(*icmp.Echo)
if !okk {
err = ErrInvalidBodyType
return
}
if msg.Type == ipv4.ICMPTypeEcho || msg.Type == ipv6.ICMPTypeEchoRequest {
ps := conn.getOrCreatePeerState(ipaddr)
ps.id = body.ID
ps.seq.Store(uintptr(body.Seq))
ps.seqfifo.Put(uintptr(body.Seq))
}
n = copy(b, body.Data)
if config.ShowDebugLog {
logrus.Debugln("[icmp] recv", n, "bytes data from", ipaddr)
}
})
return
}
func (conn *Conn) WriteToPeer(b []byte, ep p2p.EndPoint) (int, error) {
icmpep, ok := ep.(*EndPoint)
if !ok {
return 0, p2p.ErrEndpointTypeMistatch
}
addr := (*netip.Addr)(icmpep)
ps := conn.getOrCreatePeerState(*addr)
seq := int(ps.seqfifo.Get())
id := ps.id
isrequest := id == 0
if isrequest {
id = echoid
}
var (
ip net.IP
msg icmp.Message
)
if addr.Is4() {
x := addr.As4()
ip = x[:]
msg = icmp.Message{
Code: 1,
Body: &icmp.Echo{
ID: id,
Seq: seq,
Data: b,
},
}
if isrequest {
msg.Type = ipv4.ICMPTypeEcho
} else {
msg.Type = ipv4.ICMPTypeEchoReply
}
} else {
x := addr.As16()
ip = x[:]
msg = icmp.Message{
Code: 1,
Body: &icmp.Echo{
ID: id,
Seq: seq,
Data: b,
},
}
if isrequest {
msg.Type = ipv6.ICMPTypeEchoRequest
} else {
msg.Type = ipv6.ICMPTypeEchoReply
}
}
buf := pbuf.NewBytes(8192)
defer buf.ManualDestroy()
var (
data []byte
err error
n int
)
buf.V(func(bin []byte) {
data, err = msg.Marshal(bin[:0])
if err != nil {
return
}
_, err = conn.inner.WriteTo(data, &net.IPAddr{
IP: ip,
Zone: addr.Zone(),
})
if err == nil {
n = len(b)
}
})
return n, err
}

26
gold/p2p/icmp/init.go Normal file
View File

@@ -0,0 +1,26 @@
// Package icmp for non-privileged datagram-oriented ICMP endpoints,
// currently only Darwin and Linux support this.
package icmp
import (
"net/netip"
"github.com/fumiama/WireGold/gold/p2p"
"github.com/fumiama/WireGold/internal/file"
)
func NewEndpoint(endpoint string, _ ...any) (p2p.EndPoint, error) {
addr, err := netip.ParseAddr(endpoint)
if err != nil {
return nil, err
}
return (*EndPoint)(&addr), nil
}
func init() {
name := file.FolderName()
_, hasexist := p2p.Register(name, NewEndpoint)
if hasexist {
panic("network " + name + " has been registered")
}
}

View File

@@ -20,7 +20,7 @@ func (ep *EndPoint) Network() string {
return ep.addr.Network()
}
func (ep *EndPoint) Euqal(ep2 p2p.EndPoint) bool {
func (ep *EndPoint) Equal(ep2 p2p.EndPoint) bool {
if ep == nil || ep2 == nil {
return ep == nil && ep2 == nil
}
@@ -64,6 +64,9 @@ func (conn *Conn) LocalAddr() p2p.EndPoint {
func (conn *Conn) ReadFromPeer(b []byte) (int, p2p.EndPoint, error) {
n, addr, err := conn.conn.ReadFromIP(b)
if err != nil {
return 0, nil, err
}
return n, &EndPoint{
addr: addr,
ptcl: conn.ep.ptcl,

View File

@@ -32,7 +32,7 @@ func (ep *EndPoint) Network() string {
return ep.addr.Network()
}
func (ep *EndPoint) Euqal(ep2 p2p.EndPoint) bool {
func (ep *EndPoint) Equal(ep2 p2p.EndPoint) bool {
if ep == nil || ep2 == nil {
return ep == nil && ep2 == nil
}

View File

@@ -16,7 +16,7 @@ func (ep *EndPoint) Network() string {
return (*net.UDPAddr)(ep).Network()
}
func (ep *EndPoint) Euqal(ep2 p2p.EndPoint) bool {
func (ep *EndPoint) Equal(ep2 p2p.EndPoint) bool {
if ep == nil || ep2 == nil {
return ep == nil && ep2 == nil
}
@@ -50,6 +50,9 @@ func (conn *Conn) LocalAddr() p2p.EndPoint {
func (conn *Conn) ReadFromPeer(b []byte) (int, p2p.EndPoint, error) {
n, addr, err := (*net.UDPConn)(conn).ReadFromUDP(b)
if err != nil {
return 0, nil, err
}
return n, (*EndPoint)(addr), err
}

View File

@@ -18,7 +18,7 @@ func (ep *EndPoint) Network() string {
return "udplite"
}
func (ep *EndPoint) Euqal(ep2 p2p.EndPoint) bool {
func (ep *EndPoint) Equal(ep2 p2p.EndPoint) bool {
if ep == nil || ep2 == nil {
return ep == nil && ep2 == nil
}
@@ -52,6 +52,9 @@ func (conn *Conn) LocalAddr() p2p.EndPoint {
func (conn *Conn) ReadFromPeer(b []byte) (int, p2p.EndPoint, error) {
n, addr, err := (*net.UDPConn)(conn).ReadFromUDP(b)
if err != nil {
return 0, nil, err
}
return n, (*EndPoint)(addr), err
}

View File

@@ -39,7 +39,7 @@ func init() {
if err == nil {
p, ok := peer.Me().IsInPeer(ps)
if ok {
if bin.IsNilInterface(p.EndPoint()) || !p.EndPoint().Euqal(addr) {
if bin.IsNilInterface(p.EndPoint()) || !p.EndPoint().Equal(addr) {
p.SetEndPoint(addr)
logrus.Infoln(file.Header(), "notify set ep of peer", ps, "to", ep)
}

View File

@@ -3,17 +3,24 @@
package lower
import "net"
import (
"net"
"strconv"
)
func (n *NICIO) Up() {
execute("cmd", "/c", "netsh interface ip set address name=\""+n.ifce.Name()+"\" source=static addr=\""+n.ip.String()+"\" mask=\""+(net.IP)(n.subnet.Mask).String()+"\" gateway=none")
execute("cmd", "/c", "netsh interface ipv4 set subinterface \""+n.ifce.Name()+"\" mtu="+n.mtu)
iface, err := net.InterfaceByName(n.ifce.Name())
if err != nil {
panic(err)
}
for _, c := range n.cidrs {
ip, cidr, err := net.ParseCIDR(c)
if err != nil {
panic(err)
}
execute("cmd", "/c", "route ADD "+ip.String()+" MASK "+(net.IP)(cidr.Mask).String()+" "+n.ip.String())
execute("cmd", "/c", "route ADD "+ip.String()+" MASK "+(net.IP)(cidr.Mask).String()+" "+n.ip.String()+" IF "+strconv.Itoa(iface.Index))
}
}

View File

@@ -168,7 +168,14 @@ func main() {
}
func displayHelp(hint string) {
fmt.Println(hint)
if hint != "" {
fmt.Println(hint)
fmt.Println("")
}
fmt.Println("WireGold Version:", config.Version)
fmt.Println("Author: Fumiama Minamoto")
fmt.Println("Released with GPL-3.0 license")
fmt.Println("")
flag.Usage()
os.Exit(0)
}

View File

@@ -8,6 +8,7 @@ import (
"github.com/sirupsen/logrus"
_ "github.com/fumiama/WireGold/gold/p2p/icmp" // support icmp connection
_ "github.com/fumiama/WireGold/gold/p2p/ip" // support ip connection
_ "github.com/fumiama/WireGold/gold/p2p/tcp" // support tcp connection
_ "github.com/fumiama/WireGold/gold/p2p/udp" // support udp connection

View File

@@ -0,0 +1,466 @@
//go:build linux
package tunnel
import (
"bytes"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strconv"
"testing"
"time"
curve "github.com/fumiama/go-x25519"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
"github.com/fumiama/WireGold/gold/link"
)
const (
icmpNS1 = "wgtest_ns1"
icmpNS2 = "wgtest_ns2"
icmpIP1 = "10.0.0.1"
icmpIP2 = "10.0.0.2"
icmpVeth1 = "veth1"
icmpVeth2 = "veth2"
)
// setupICMPNetns creates two network namespaces connected by a veth pair.
// It returns a cleanup function. Requires root.
func setupICMPNetns(t *testing.T) func() {
t.Helper()
cmds := [][]string{
{"ip", "netns", "add", icmpNS1},
{"ip", "netns", "add", icmpNS2},
{"ip", "link", "add", icmpVeth1, "type", "veth", "peer", "name", icmpVeth2},
{"ip", "link", "set", icmpVeth1, "netns", icmpNS1},
{"ip", "link", "set", icmpVeth2, "netns", icmpNS2},
{"ip", "netns", "exec", icmpNS1, "ifconfig", icmpVeth1, icmpIP1, "up"},
{"ip", "netns", "exec", icmpNS2, "ifconfig", icmpVeth2, icmpIP2, "up"},
}
for _, args := range cmds {
if out, err := exec.Command(args[0], args[1:]...).CombinedOutput(); err != nil {
// best-effort cleanup
exec.Command("ip", "netns", "del", icmpNS1).Run()
exec.Command("ip", "netns", "del", icmpNS2).Run()
t.Fatalf("setup netns: %v failed: %v\n%s", args, err, out)
}
}
return func() {
exec.Command("ip", "netns", "del", icmpNS1).Run()
exec.Command("ip", "netns", "del", icmpNS2).Run()
}
}
// enterNetns pins the current goroutine to its OS thread, switches into
// the named network namespace, and returns a function that restores the
// original namespace and unlocks the thread.
func enterNetns(nsName string) (func(), error) {
runtime.LockOSThread()
origFd, err := unix.Open("/proc/self/ns/net", unix.O_RDONLY|unix.O_CLOEXEC, 0)
if err != nil {
runtime.UnlockOSThread()
return nil, fmt.Errorf("open current netns: %w", err)
}
targetFd, err := unix.Open("/var/run/netns/"+nsName, unix.O_RDONLY|unix.O_CLOEXEC, 0)
if err != nil {
unix.Close(origFd)
runtime.UnlockOSThread()
return nil, fmt.Errorf("open target netns %s: %w", nsName, err)
}
if err := unix.Setns(targetFd, unix.CLONE_NEWNET); err != nil {
unix.Close(targetFd)
unix.Close(origFd)
runtime.UnlockOSThread()
return nil, fmt.Errorf("setns to %s: %w", nsName, err)
}
unix.Close(targetFd)
return func() {
unix.Setns(origFd, unix.CLONE_NEWNET)
unix.Close(origFd)
runtime.UnlockOSThread()
}, nil
}
// initMeInNetns initializes a link.Me at dst inside the given network namespace.
// The underlying socket fd remains bound to that namespace after return.
func initMeInNetns(t testing.TB, nsName string, cfg *link.MyConfig, dst *link.Me) {
t.Helper()
var merr any
done := make(chan struct{})
go func() {
defer func() {
if r := recover(); r != nil {
merr = r
}
close(done)
}()
restore, err := enterNetns(nsName)
if err != nil {
merr = err
return
}
defer restore()
*dst = link.NewMe(cfg)
}()
<-done
if merr != nil {
t.Fatalf("initMeInNetns(%s): %v", nsName, merr)
}
}
func TestTunnelICMP(t *testing.T) {
if os.Getuid() != 0 {
t.Skip("skipping ICMP test: requires root")
}
for i := 1; i <= 4; i++ {
sz := 1024 * i
if !t.Run(strconv.Itoa(sz), func(t *testing.T) {
testTunnelICMP(t, uint16(sz))
}) {
return
}
}
}
func testTunnelICMP(t *testing.T, mtu uint16) {
logrus.SetLevel(logrus.DebugLevel)
logrus.SetFormatter(&logFormat{enableColor: false})
cleanup := setupICMPNetns(t)
defer cleanup()
testICMPTunnel(t, true, false, nil, mtu) // plain text
testICMPTunnel(t, false, false, nil, mtu) // normal
testICMPTunnel(t, true, true, nil, mtu) // plain text + base14
testICMPTunnel(t, false, true, nil, mtu) // normal + base14
var buf [32]byte
if _, err := rand.Read(buf[:]); err != nil {
t.Fatal(err)
}
testICMPTunnel(t, false, false, &buf, mtu) // preshared
testICMPTunnel(t, false, true, &buf, mtu) // preshared + base14
}
func testICMPTunnel(t *testing.T, isplain, isbase14 bool, pshk *[32]byte, mtu uint16) {
nw := "icmp"
fmt.Println("start", nw, "testing, mtu", mtu, "plain", isplain, "b14", isbase14, "pshk", pshk != nil)
selfpk, err := curve.New(nil)
if err != nil {
t.Fatal(err)
}
peerpk, err := curve.New(nil)
if err != nil {
t.Fatal(err)
}
t.Log("my priv key:", hex.EncodeToString(selfpk.Private()[:]))
t.Log("my publ key:", hex.EncodeToString(selfpk.Public()[:]))
t.Log("peer priv key:", hex.EncodeToString(peerpk.Private()[:]))
t.Log("peer publ key:", hex.EncodeToString(peerpk.Public()[:]))
var m link.Me
initMeInNetns(t, icmpNS1, &link.MyConfig{
MyIPwithMask: "192.168.1.2/32",
MyEndpoint: icmpIP1,
Network: nw,
PrivateKey: selfpk.Private(),
SrcPort: 1,
DstPort: 1,
MTU: mtu,
Base14: isbase14,
}, &m)
defer m.Close()
var p link.Me
initMeInNetns(t, icmpNS2, &link.MyConfig{
MyIPwithMask: "192.168.1.3/32",
MyEndpoint: icmpIP2,
Network: nw,
PrivateKey: peerpk.Private(),
SrcPort: 1,
DstPort: 1,
MTU: mtu,
Base14: isbase14,
}, &p)
defer p.Close()
ppp := peerpk.Public()
spp := selfpk.Public()
if isplain {
ppp = nil
spp = nil
}
m.AddPeer(&link.PeerConfig{
PeerIP: "192.168.1.3",
EndPoint: icmpIP2,
AllowedIPs: []string{"192.168.1.3/32"},
PubicKey: ppp,
PresharedKey: pshk,
MTU: mtu,
MTURandomRange: mtu / 2,
UseZstd: true,
DoublePacket: true,
})
p.AddPeer(&link.PeerConfig{
PeerIP: "192.168.1.2",
EndPoint: icmpIP1,
AllowedIPs: []string{"192.168.1.2/32"},
PubicKey: spp,
PresharedKey: pshk,
MTU: mtu,
MTURandomRange: mtu / 2,
UseZstd: true,
})
tunnme, err := Create(&m, "192.168.1.3")
if err != nil {
t.Fatal(err)
}
tunnme.Start(1, 1, 4096)
tunnpeer, err := Create(&p, "192.168.1.2")
if err != nil {
t.Fatal(err)
}
tunnpeer.Start(1, 1, 4096)
time.Sleep(time.Second) // wait link up
sendb := ([]byte)("1234")
go tunnme.Write(sendb)
buf := make([]byte, 4)
tunnpeer.Read(buf)
if string(sendb) != string(buf) {
logrus.Errorln("error: recv", buf, "expect", sendb)
t.Fail()
}
sendb = make([]byte, mtu+4)
for i := 0; i < len(sendb); i++ {
sendb[i] = byte(i)
}
for i := 1; i < len(sendb); i++ {
rand.Read(sendb[:i])
go tunnme.Write(sendb[:i])
rbuf := make([]byte, i)
_, err = io.ReadFull(&tunnpeer, rbuf)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(sendb[:i], rbuf) {
t.Fatal("error: recv", i, "bytes data")
}
}
for i := 0; i < len(sendb); i++ {
sendb[i] = ^byte(i)
}
tunnme.Write(sendb)
rd := bytes.NewBuffer(nil)
tm := time.AfterFunc(time.Second*2, func() {
tunnme.Stop()
tunnpeer.Stop()
})
defer tm.Stop()
_, err = io.CopyBuffer(rd, &tunnpeer, make([]byte, 200))
if err != nil {
t.Fatal(err)
}
if string(sendb) != rd.String() {
t.Fatal("error: recv fragmented data")
}
}
func BenchmarkTunnelICMP(b *testing.B) {
if os.Getuid() != 0 {
b.Skip("skipping ICMP benchmark: requires root")
}
benchmarkTunnelNetworkICMP(b, 4096)
}
func BenchmarkTunnelICMPSmallMTU(b *testing.B) {
if os.Getuid() != 0 {
b.Skip("skipping ICMP benchmark: requires root")
}
benchmarkTunnelNetworkICMP(b, 1024)
}
func benchmarkTunnelNetworkICMP(b *testing.B, mtu uint16) {
logrus.SetLevel(logrus.ErrorLevel)
logrus.SetFormatter(&logFormat{enableColor: false})
cleanup := setupICMPBenchNetns(b)
defer cleanup()
for i := 1; i <= 4; i++ {
sz := 1024 * i
b.Run(fmt.Sprintf("%d-plain-nob14", sz), func(b *testing.B) {
benchmarkICMPTunnel(b, sz, true, false, nil, mtu)
})
b.Run(fmt.Sprintf("%d-normal-nob14", sz), func(b *testing.B) {
benchmarkICMPTunnel(b, sz, false, false, nil, mtu)
})
b.Run(fmt.Sprintf("%d-plain-b14", sz), func(b *testing.B) {
benchmarkICMPTunnel(b, sz, true, true, nil, mtu)
})
b.Run(fmt.Sprintf("%d-normal-b14", sz), func(b *testing.B) {
benchmarkICMPTunnel(b, sz, false, true, nil, mtu)
})
var buf [32]byte
if _, err := rand.Read(buf[:]); err != nil {
b.Fatal(err)
}
b.Run(fmt.Sprintf("%d-preshared-nob14", sz), func(b *testing.B) {
benchmarkICMPTunnel(b, sz, false, false, &buf, mtu)
})
b.Run(fmt.Sprintf("%d-preshared-b14", sz), func(b *testing.B) {
benchmarkICMPTunnel(b, sz, false, true, &buf, mtu)
})
}
}
func setupICMPBenchNetns(b *testing.B) func() {
b.Helper()
cmds := [][]string{
{"ip", "netns", "add", icmpNS1},
{"ip", "netns", "add", icmpNS2},
{"ip", "link", "add", icmpVeth1, "type", "veth", "peer", "name", icmpVeth2},
{"ip", "link", "set", icmpVeth1, "netns", icmpNS1},
{"ip", "link", "set", icmpVeth2, "netns", icmpNS2},
{"ip", "netns", "exec", icmpNS1, "ifconfig", icmpVeth1, icmpIP1, "up"},
{"ip", "netns", "exec", icmpNS2, "ifconfig", icmpVeth2, icmpIP2, "up"},
}
for _, args := range cmds {
if out, err := exec.Command(args[0], args[1:]...).CombinedOutput(); err != nil {
exec.Command("ip", "netns", "del", icmpNS1).Run()
exec.Command("ip", "netns", "del", icmpNS2).Run()
b.Fatalf("setup netns: %v failed: %v\n%s", args, err, out)
}
}
return func() {
exec.Command("ip", "netns", "del", icmpNS1).Run()
exec.Command("ip", "netns", "del", icmpNS2).Run()
}
}
func benchmarkICMPTunnel(b *testing.B, sz int, isplain, isbase14 bool, pshk *[32]byte, mtu uint16) {
nw := "icmp"
selfpk, err := curve.New(nil)
if err != nil {
b.Fatal(err)
}
peerpk, err := curve.New(nil)
if err != nil {
b.Fatal(err)
}
var m link.Me
initMeInNetns(b, icmpNS1, &link.MyConfig{
MyIPwithMask: "192.168.1.2/32",
MyEndpoint: icmpIP1,
Network: nw,
PrivateKey: selfpk.Private(),
SrcPort: 1,
DstPort: 1,
MTU: mtu,
Base14: isbase14,
}, &m)
defer m.Close()
var p link.Me
initMeInNetns(b, icmpNS2, &link.MyConfig{
MyIPwithMask: "192.168.1.3/32",
MyEndpoint: icmpIP2,
Network: nw,
PrivateKey: peerpk.Private(),
SrcPort: 1,
DstPort: 1,
MTU: mtu,
Base14: isbase14,
}, &p)
defer p.Close()
ppp := peerpk.Public()
spp := selfpk.Public()
if isplain {
ppp = nil
spp = nil
}
m.AddPeer(&link.PeerConfig{
PeerIP: "192.168.1.3",
EndPoint: icmpIP2,
AllowedIPs: []string{"192.168.1.3/32"},
PubicKey: ppp,
PresharedKey: pshk,
MTU: mtu,
MTURandomRange: mtu / 2,
UseZstd: true,
DoublePacket: true,
})
p.AddPeer(&link.PeerConfig{
PeerIP: "192.168.1.2",
EndPoint: icmpIP1,
AllowedIPs: []string{"192.168.1.2/32"},
PubicKey: spp,
PresharedKey: pshk,
MTU: mtu,
MTURandomRange: mtu / 2,
UseZstd: true,
})
tunnme, err := Create(&m, "192.168.1.3")
if err != nil {
b.Fatal(err)
}
tunnme.Start(1, 1, 4096)
tunnpeer, err := Create(&p, "192.168.1.2")
if err != nil {
b.Fatal(err)
}
tunnpeer.Start(1, 1, 4096)
time.Sleep(time.Second) // wait link up
b.SetBytes(int64(sz))
b.ResetTimer()
sendb := make([]byte, sz)
for i := 0; i < b.N; i++ {
rand.Read(sendb)
go tunnme.Write(sendb)
buf := make([]byte, sz)
_, err = io.ReadFull(&tunnpeer, buf)
if err != nil {
b.Fatal(err)
}
}
b.StopTimer()
time.Sleep(time.Second) // wait packets all received
tunnme.Stop()
tunnpeer.Stop()
}

View File

@@ -103,14 +103,14 @@ func testTunnel(t *testing.T, nw string, isplain, isbase14 bool, pshk *[32]byte,
t.Log("peer publ key:", hex.EncodeToString(peerpk.Public()[:]))
epm := "127.0.0.1"
if nw != "ip" {
if nw != "ip" && nw != "icmp" {
epm += ":0"
}
// under macos you need to run
//
// sudo ifconfig lo0 alias 127.0.0.2
epp := "127.0.0.2"
if nw != "ip" {
if nw != "ip" && nw != "icmp" {
epp += ":0"
}
@@ -238,14 +238,14 @@ func benchmarkTunnel(b *testing.B, sz int, nw string, isplain, isbase14 bool, ps
}
epm := "127.0.0.1"
if nw != "ip" {
if nw != "ip" && nw != "icmp" {
epm += ":0"
}
// under macos you need to run
//
// sudo ifconfig lo0 alias 127.0.0.2
epp := "127.0.0.2"
if nw != "ip" {
if nw != "ip" && nw != "icmp" {
epp += ":0"
}

View File

@@ -9,6 +9,7 @@ import (
curve "github.com/fumiama/go-x25519"
"github.com/sirupsen/logrus"
_ "github.com/fumiama/WireGold/gold/p2p/icmp" // support icmp connection
_ "github.com/fumiama/WireGold/gold/p2p/ip" // support ip connection
_ "github.com/fumiama/WireGold/gold/p2p/tcp" // support tcp connection
_ "github.com/fumiama/WireGold/gold/p2p/udp" // support udp connection