From 58b5d92aae6eba5a6ce7bed90077eb8354e73d04 Mon Sep 17 00:00:00 2001 From: huyinsong Date: Wed, 11 Jun 2025 13:03:17 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dipv6=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 55 +++++++ .github/workflows/build.yml | 268 ++++++++++++++++++++++++++++++ Dockerfile | 63 +++++++ Makefile | 145 +++++++++++++++-- README.md | 148 ++++++++++++++++- cmd/wormhole-server/main.go | 35 +++- configs/server.yaml | 82 +++++++--- internal/server/server.go | 46 +++++- scripts/build.sh | 298 ++++++++++++++++++++++++++++++++++ scripts/setup-docker-proxy.sh | 248 ++++++++++++++++++++++++++++ 10 files changed, 1333 insertions(+), 55 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/workflows/build.yml create mode 100644 Dockerfile create mode 100755 scripts/build.sh create mode 100755 scripts/setup-docker-proxy.sh diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4398683 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,55 @@ +# Git +.git +.gitignore + +# Build artifacts +bin/ +dist/ +*.exe +*.dll +*.so +*.dylib + +# Test files +*_test.go +test/ +tests/ + +# Documentation +*.md +docs/ + +# IDE files +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# OS files +.DS_Store +Thumbs.db + +# Logs +*.log + +# Temporary files +tmp/ +temp/ + +# Docker files +Dockerfile* +.dockerignore + +# CI/CD +.github/ +.gitlab-ci.yml +.travis.yml + +# Scripts (not needed in container) +scripts/ + +# Development files +.env +.env.local +.env.development \ No newline at end of file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..ad563be --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,268 @@ +name: Build and Release + +on: + push: + branches: [ main, develop ] + tags: [ 'v*' ] + pull_request: + branches: [ main ] + +jobs: + test: + name: Test + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: '1.21' + + - name: Download dependencies + run: go mod download + + - name: Run tests + run: go test -v ./... + + - name: Run race detection tests + run: go test -race -v ./... + + - name: Run benchmarks + run: go test -bench=. -benchmem ./... + + build: + name: Build Multi-Platform + runs-on: ubuntu-latest + needs: test + + strategy: + matrix: + include: + - goos: linux + goarch: amd64 + name: linux-amd64 + - goos: linux + goarch: arm64 + name: linux-arm64 + - goos: linux + goarch: 386 + name: linux-386 + - goos: linux + goarch: arm + name: linux-arm + - goos: darwin + goarch: amd64 + name: darwin-amd64 + - goos: darwin + goarch: arm64 + name: darwin-arm64 + - goos: windows + goarch: amd64 + name: windows-amd64 + ext: .exe + - goos: windows + goarch: 386 + name: windows-386 + ext: .exe + - goos: windows + goarch: arm64 + name: windows-arm64 + ext: .exe + - goos: freebsd + goarch: amd64 + name: freebsd-amd64 + - goos: freebsd + goarch: arm64 + name: freebsd-arm64 + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version: '1.21' + + - name: Get version + id: version + run: | + if [[ $GITHUB_REF == refs/tags/* ]]; then + VERSION=${GITHUB_REF#refs/tags/} + else + VERSION=v1.1.0-$(git rev-parse --short HEAD) + fi + echo "VERSION=$VERSION" >> $GITHUB_OUTPUT + echo "Building version: $VERSION" + + - name: Build binary + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + VERSION: ${{ steps.version.outputs.VERSION }} + run: | + BUILD_TIME=$(date -u '+%Y-%m-%d_%H:%M:%S') + GIT_COMMIT=$(git rev-parse --short HEAD) + LDFLAGS="-ldflags \"-X main.version=${VERSION} -X main.buildTime=${BUILD_TIME} -X main.gitCommit=${GIT_COMMIT} -s -w\"" + + mkdir -p dist + BINARY_NAME="wormhole-server-${VERSION}-${{ matrix.name }}${{ matrix.ext }}" + + echo "Building ${BINARY_NAME}..." + go build ${LDFLAGS} -o "dist/${BINARY_NAME}" cmd/wormhole-server/main.go + + - name: Upload artifact + uses: actions/upload-artifact@v3 + with: + name: wormhole-server-${{ matrix.name }} + path: dist/wormhole-server-*-${{ matrix.name }}* + retention-days: 30 + + release: + name: Create Release + runs-on: ubuntu-latest + needs: build + if: startsWith(github.ref, 'refs/tags/') + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Download all artifacts + uses: actions/download-artifact@v3 + with: + path: artifacts + + - name: Get version + id: version + run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT + + - name: Create release packages + run: | + mkdir -p release + VERSION=${{ steps.version.outputs.VERSION }} + + # 移动所有二进制文件到一个目录 + find artifacts -name "wormhole-server-*" -type f -exec mv {} release/ \; + + cd release + + # 为每个平台创建发布包 + for binary in wormhole-server-${VERSION}-*; do + if [[ "$binary" == *.exe ]]; then + # Windows平台使用zip + platform=$(echo "$binary" | sed "s/wormhole-server-${VERSION}-//; s/.exe$//") + zip -j "wormhole-server-${VERSION}-${platform}.zip" "$binary" ../configs/server.yaml ../README.md + else + # 其他平台使用tar.gz + platform=$(echo "$binary" | sed "s/wormhole-server-${VERSION}-//") + tar -czf "wormhole-server-${VERSION}-${platform}.tar.gz" "$binary" -C .. configs/server.yaml README.md + fi + done + + # 创建校验和文件 + sha256sum wormhole-server-${VERSION}-*.{tar.gz,zip} > wormhole-server-${VERSION}-checksums.txt + + - name: Create Release + uses: ncipollo/release-action@v1 + with: + tag: ${{ steps.version.outputs.VERSION }} + name: Wormhole Server ${{ steps.version.outputs.VERSION }} + draft: false + prerelease: false + artifacts: "release/wormhole-server-*" + body: | + ## Wormhole Server ${{ steps.version.outputs.VERSION }} + + ### 🚀 新功能 + - 高性能 SOCKS5 代理服务器 + - 速率限制和连接池优化 + - 内存优化和DNS缓存 + - 多平台支持 + + ### 📦 下载 + + 选择适合您系统的版本: + + **Linux:** + - `wormhole-server-${{ steps.version.outputs.VERSION }}-linux-amd64.tar.gz` - Linux x86_64 + - `wormhole-server-${{ steps.version.outputs.VERSION }}-linux-arm64.tar.gz` - Linux ARM64 + - `wormhole-server-${{ steps.version.outputs.VERSION }}-linux-arm.tar.gz` - Linux ARM + - `wormhole-server-${{ steps.version.outputs.VERSION }}-linux-386.tar.gz` - Linux x86 + + **macOS:** + - `wormhole-server-${{ steps.version.outputs.VERSION }}-darwin-amd64.tar.gz` - macOS Intel + - `wormhole-server-${{ steps.version.outputs.VERSION }}-darwin-arm64.tar.gz` - macOS Apple Silicon + + **Windows:** + - `wormhole-server-${{ steps.version.outputs.VERSION }}-windows-amd64.zip` - Windows x64 + - `wormhole-server-${{ steps.version.outputs.VERSION }}-windows-386.zip` - Windows x86 + - `wormhole-server-${{ steps.version.outputs.VERSION }}-windows-arm64.zip` - Windows ARM64 + + **FreeBSD:** + - `wormhole-server-${{ steps.version.outputs.VERSION }}-freebsd-amd64.tar.gz` - FreeBSD x86_64 + - `wormhole-server-${{ steps.version.outputs.VERSION }}-freebsd-arm64.tar.gz` - FreeBSD ARM64 + + ### 🔐 校验和 + 下载 `wormhole-server-${{ steps.version.outputs.VERSION }}-checksums.txt` 来验证文件完整性。 + + ### 📖 使用方法 + + 1. 下载适合您系统的版本 + 2. 解压文件 + 3. 编辑 `server.yaml` 配置文件 + 4. 运行 `./wormhole-server -config server.yaml` + + 更多信息请查看 [README.md](https://github.com/azoic/wormhole-server/blob/main/README.md) + + docker: + name: Build Docker Images + runs-on: ubuntu-latest + needs: test + if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/')) + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + if: secrets.DOCKER_USERNAME && secrets.DOCKER_PASSWORD + + - name: Get version + id: version + run: | + if [[ $GITHUB_REF == refs/tags/* ]]; then + VERSION=${GITHUB_REF#refs/tags/} + echo "VERSION=$VERSION" >> $GITHUB_OUTPUT + echo "LATEST=true" >> $GITHUB_OUTPUT + else + VERSION=v1.1.0-$(git rev-parse --short HEAD) + echo "VERSION=$VERSION" >> $GITHUB_OUTPUT + echo "LATEST=false" >> $GITHUB_OUTPUT + fi + + - name: Build and push Docker image + uses: docker/build-push-action@v5 + with: + context: . + platforms: linux/amd64,linux/arm64 + push: ${{ secrets.DOCKER_USERNAME && secrets.DOCKER_PASSWORD }} + tags: | + ${{ secrets.DOCKER_USERNAME }}/wormhole-server:${{ steps.version.outputs.VERSION }} + ${{ secrets.DOCKER_USERNAME }}/wormhole-server:latest + build-args: | + VERSION=${{ steps.version.outputs.VERSION }} + cache-from: type=gha + cache-to: type=gha,mode=max \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..fdeb40f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,63 @@ +# 多阶段构建 Dockerfile +# 支持多架构: linux/amd64, linux/arm64 + +# 构建阶段 +FROM --platform=$BUILDPLATFORM golang:1.21-alpine AS builder + +# 安装构建依赖 +RUN apk add --no-cache git ca-certificates tzdata + +# 设置工作目录 +WORKDIR /app + +# 复制 go mod 文件 +COPY go.mod go.sum ./ + +# 下载依赖 +RUN go mod download + +# 复制源代码 +COPY . . + +# 构建参数 +ARG TARGETOS +ARG TARGETARCH +ARG VERSION=v1.1.0 + +# 构建二进制文件 +RUN CGO_ENABLED=0 GOOS=$TARGETOS GOARCH=$TARGETARCH go build \ + -ldflags "-X main.version=${VERSION} -X main.buildTime=$(date -u '+%Y-%m-%d_%H:%M:%S') -X main.gitCommit=$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown') -s -w" \ + -o wormhole-server \ + cmd/wormhole-server/main.go + +# 运行阶段 +FROM --platform=$TARGETPLATFORM alpine:latest + +# 安装运行时依赖 +RUN apk --no-cache add ca-certificates tzdata && \ + addgroup -g 1000 wormhole && \ + adduser -D -s /bin/sh -u 1000 -G wormhole wormhole + +# 设置工作目录 +WORKDIR /app + +# 从构建阶段复制二进制文件 +COPY --from=builder /app/wormhole-server . +COPY --from=builder /app/configs ./configs + +# 设置权限 +RUN chown -R wormhole:wormhole /app + +# 切换到非root用户 +USER wormhole + +# 暴露端口 +EXPOSE 1080 8090 + +# 健康检查 +HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ + CMD wget --no-verbose --tries=1 --spider http://localhost:8090/health || exit 1 + +# 启动命令 +ENTRYPOINT ["./wormhole-server"] +CMD ["-config", "configs/server.yaml"] \ No newline at end of file diff --git a/Makefile b/Makefile index 2a4f0e8..167184c 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,21 @@ GO = go APP_NAME = wormhole-server -VERSION = v1.0.0 -LDFLAGS = -ldflags "-X main.version=$(VERSION) -X main.buildTime=$(shell date -u '+%Y-%m-%d_%H:%M:%S')" +VERSION ?= v1.1.0 +BUILD_TIME = $(shell date -u '+%Y-%m-%d_%H:%M:%S') +GIT_COMMIT = $(shell git rev-parse --short HEAD 2>/dev/null || echo "unknown") +LDFLAGS = -ldflags "-X main.version=$(VERSION) -X main.buildTime=$(BUILD_TIME) -X main.gitCommit=$(GIT_COMMIT) -s -w" -.PHONY: all build clean deps test run +# 支持的平台和架构 +PLATFORMS = linux/amd64 linux/arm64 linux/386 linux/arm \ + darwin/amd64 darwin/arm64 \ + windows/amd64 windows/386 windows/arm64 \ + freebsd/amd64 freebsd/arm64 + +# 构建输出目录 +BUILD_DIR = bin +DIST_DIR = dist + +.PHONY: all build clean deps test run cross-compile release help install docker-build docker-build-multi version platforms all: clean deps build @@ -11,30 +23,135 @@ deps: $(GO) mod download $(GO) mod tidy +# 本地构建 (当前平台) build: - $(GO) build $(LDFLAGS) -o bin/$(APP_NAME) cmd/wormhole-server/main.go + @echo "Building $(APP_NAME) for current platform..." + $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME) cmd/wormhole-server/main.go + +# 交叉编译所有平台 +cross-compile: clean deps + @echo "Cross-compiling for all supported platforms..." + @mkdir -p $(DIST_DIR) + @for platform in $(PLATFORMS); do \ + OS=$$(echo $$platform | cut -d'/' -f1); \ + ARCH=$$(echo $$platform | cut -d'/' -f2); \ + echo "Building for $$OS/$$ARCH..."; \ + if [ "$$OS" = "windows" ]; then \ + GOOS=$$OS GOARCH=$$ARCH $(GO) build $(LDFLAGS) -o $(DIST_DIR)/$(APP_NAME)-$(VERSION)-$$OS-$$ARCH.exe cmd/wormhole-server/main.go; \ + else \ + GOOS=$$OS GOARCH=$$ARCH $(GO) build $(LDFLAGS) -o $(DIST_DIR)/$(APP_NAME)-$(VERSION)-$$OS-$$ARCH cmd/wormhole-server/main.go; \ + fi; \ + done + @echo "Cross-compilation completed. Binaries are in $(DIST_DIR)/" + +# 创建发布包 +release: cross-compile + @echo "Creating release packages..." + @cd $(DIST_DIR) && \ + for file in $(APP_NAME)-$(VERSION)-*; do \ + if [ "$${file##*.}" = "exe" ]; then \ + platform=$$(echo $$file | sed 's/$(APP_NAME)-$(VERSION)-//; s/.exe$$//'); \ + zip -q $(APP_NAME)-$(VERSION)-$$platform.zip $$file ../configs/server.yaml ../README.md; \ + else \ + platform=$$(echo $$file | sed 's/$(APP_NAME)-$(VERSION)-//'); \ + tar -czf $(APP_NAME)-$(VERSION)-$$platform.tar.gz $$file -C .. configs/server.yaml README.md; \ + fi; \ + done + @echo "Release packages created in $(DIST_DIR)/" + +# 特定平台构建 +build-linux: + @echo "Building for Linux AMD64..." + GOOS=linux GOARCH=amd64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-linux-amd64 cmd/wormhole-server/main.go + +build-darwin: + @echo "Building for macOS AMD64..." + GOOS=darwin GOARCH=amd64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-darwin-amd64 cmd/wormhole-server/main.go + +build-windows: + @echo "Building for Windows AMD64..." + GOOS=windows GOARCH=amd64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-windows-amd64.exe cmd/wormhole-server/main.go +# ARM平台构建 +build-arm64: + @echo "Building for ARM64..." + GOOS=linux GOARCH=arm64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-linux-arm64 cmd/wormhole-server/main.go + +build-darwin-arm64: + @echo "Building for macOS ARM64 (Apple Silicon)..." + GOOS=darwin GOARCH=arm64 $(GO) build $(LDFLAGS) -o $(BUILD_DIR)/$(APP_NAME)-darwin-arm64 cmd/wormhole-server/main.go + +# 运行和测试 run: build - ./bin/$(APP_NAME) -config configs/server.yaml + ./$(BUILD_DIR)/$(APP_NAME) -config configs/server.yaml test: $(GO) test -v ./... +test-race: + $(GO) test -race -v ./... + +bench: + $(GO) test -bench=. -benchmem ./... + +# 清理 clean: - rm -rf bin/ + rm -rf $(BUILD_DIR)/ $(DIST_DIR)/ +# 安装到系统 install: build - sudo cp bin/$(APP_NAME) /usr/local/bin/ + sudo cp $(BUILD_DIR)/$(APP_NAME) /usr/local/bin/ +# Docker构建 docker-build: docker build -t $(APP_NAME):$(VERSION) . +docker-build-multi: + docker buildx build --platform linux/amd64,linux/arm64 -t $(APP_NAME):$(VERSION) . + +# 版本信息 +version: + @echo "Version: $(VERSION)" + @echo "Build Time: $(BUILD_TIME)" + @echo "Git Commit: $(GIT_COMMIT)" + +# 显示支持的平台 +platforms: + @echo "Supported platforms:" + @for platform in $(PLATFORMS); do \ + echo " $$platform"; \ + done + +# 帮助信息 help: + @echo "Wormhole Server Build System" + @echo "" @echo "Available targets:" - @echo " build - Build the server binary" - @echo " run - Build and run the server" - @echo " test - Run tests" - @echo " clean - Clean build artifacts" - @echo " deps - Download dependencies" - @echo " install - Install to /usr/local/bin" - @echo " docker-build - Build Docker image" + @echo " build - Build for current platform" + @echo " cross-compile - Build for all supported platforms" + @echo " release - Create release packages for all platforms" + @echo " build-linux - Build for Linux AMD64" + @echo " build-darwin - Build for macOS AMD64" + @echo " build-windows - Build for Windows AMD64" + @echo " build-arm64 - Build for Linux ARM64" + @echo " build-darwin-arm64 - Build for macOS ARM64" + @echo " run - Build and run the server" + @echo " test - Run tests" + @echo " test-race - Run tests with race detection" + @echo " bench - Run benchmarks" + @echo " clean - Clean build artifacts" + @echo " deps - Download dependencies" + @echo " install - Install to /usr/local/bin" + @echo " docker-build - Build Docker image" + @echo " docker-build-multi - Build multi-arch Docker image" + @echo " version - Show version information" + @echo " platforms - Show supported platforms" + @echo "" + @echo "Environment variables:" + @echo " VERSION - Set build version (default: $(VERSION))" + @echo "" + @echo "Examples:" + @echo " make build # Build for current platform" + @echo " make cross-compile # Build for all platforms" + @echo " make release # Create release packages" + @echo " VERSION=v1.2.0 make release # Create release with custom version" diff --git a/README.md b/README.md index d52a5ce..49c5b01 100644 --- a/README.md +++ b/README.md @@ -14,20 +14,119 @@ ✅ **速率限制系统** ✅ **连接池优化** ✅ **内存使用优化** +✅ **多平台编译支持** ⚠️ **DNS缓存集成** (暂时禁用,避免端口冲突) ⚠️ **透明代理支持** (默认关闭,需要root权限) ## 快速开始 -### 构建和运行 +### 📦 预构建二进制文件下载 + +从 [Releases 页面](https://github.com/azoic/wormhole-server/releases) 下载适合您系统的预构建版本: + +**Linux:** +- `wormhole-server-v1.1.0-linux-amd64.tar.gz` - Linux x86_64 +- `wormhole-server-v1.1.0-linux-arm64.tar.gz` - Linux ARM64 (树莓派 等) +- `wormhole-server-v1.1.0-linux-arm.tar.gz` - Linux ARM +- `wormhole-server-v1.1.0-linux-386.tar.gz` - Linux x86 + +**macOS:** +- `wormhole-server-v1.1.0-darwin-amd64.tar.gz` - macOS Intel +- `wormhole-server-v1.1.0-darwin-arm64.tar.gz` - macOS Apple Silicon (M1/M2) + +**Windows:** +- `wormhole-server-v1.1.0-windows-amd64.zip` - Windows x64 +- `wormhole-server-v1.1.0-windows-386.zip` - Windows x86 +- `wormhole-server-v1.1.0-windows-arm64.zip` - Windows ARM64 + +**FreeBSD:** +- `wormhole-server-v1.1.0-freebsd-amd64.tar.gz` - FreeBSD x86_64 +- `wormhole-server-v1.1.0-freebsd-arm64.tar.gz` - FreeBSD ARM64 + +### 🛠 本地编译 + +#### 快速构建 (当前平台) ```bash make build make run ``` -### 直接运行 +#### 多平台编译 + +使用 Makefile 进行多平台编译: + +```bash +# 构建所有支持的平台 +make cross-compile + +# 创建发布包 (包含配置文件和文档) +make release + +# 构建特定平台 +make build-linux # Linux AMD64 +make build-darwin # macOS AMD64 +make build-windows # Windows AMD64 +make build-arm64 # Linux ARM64 +make build-darwin-arm64 # macOS ARM64 (Apple Silicon) + +# 查看支持的平台 +make platforms + +# 查看版本信息 +make version +``` + +#### 使用构建脚本 + +```bash +# 构建所有平台 +./scripts/build.sh + +# 构建特定版本的所有平台 +./scripts/build.sh v1.2.0 + +# 构建特定平台 +./scripts/build.sh v1.2.0 linux-amd64 +./scripts/build.sh v1.2.0 darwin-arm64 +./scripts/build.sh v1.2.0 windows-amd64 + +# 查看帮助 +./scripts/build.sh --help +``` + +#### 高级编译选项 + +```bash +# 自定义版本号 +VERSION=v1.2.0 make cross-compile + +# 构建并创建发布包 +make release + +# 构建多架构 Docker 镜像 +make docker-build-multi +``` + +### 📋 版本信息 + +查看详细的版本和构建信息: + ```bash -./bin/wormhole-server +# 简短版本信息 +./wormhole-server -version + +# 详细版本信息 (包含Go版本、平台、功能等) +./wormhole-server -version-verbose +``` + +### 🚀 快速运行 + +```bash +# 使用默认配置运行 +./wormhole-server + +# 指定配置文件 +./wormhole-server -config configs/server.yaml ``` ### 配置 @@ -60,12 +159,50 @@ curl http://127.0.0.1:8090/metrics curl --socks5 admin:your_secure_password@127.0.0.1:1080 http://httpbin.org/ip ``` -### Docker 部署 +### 🐳 Docker 部署 ```bash make docker-build -docker run -p 1080:1080 -p 8090:8090 wormhole-server:v1.0.0 +docker run -p 1080:1080 -p 8090:8090 wormhole-server:v1.1.0 + +# 多架构 Docker 镜像 +make docker-build-multi ``` +## 🔧 支持的平台 + +我们支持以下平台的交叉编译: + +| 平台 | 架构 | 状态 | 说明 | +|------|------|------|------| +| Linux | amd64 | ✅ | x86_64 处理器 | +| Linux | arm64 | ✅ | ARM64 处理器 (树莓派 4+) | +| Linux | 386 | ✅ | x86 32位处理器 | +| Linux | arm | ✅ | ARM 32位处理器 | +| macOS | amd64 | ✅ | Intel 处理器 | +| macOS | arm64 | ✅ | Apple Silicon (M1/M2) | +| Windows | amd64 | ✅ | x86_64 处理器 | +| Windows | 386 | ✅ | x86 32位处理器 | +| Windows | arm64 | ✅ | ARM64 处理器 | +| FreeBSD | amd64 | ✅ | x86_64 处理器 | +| FreeBSD | arm64 | ✅ | ARM64 处理器 | + +### 🏗 构建要求 + +- **Go 1.21+** - 必需的 Go 版本 +- **Git** - 用于版本信息 (可选) +- **Make** - 用于 Makefile 命令 (可选) +- **zip** - 用于创建 Windows 发布包 (可选) + +### 📊 CI/CD 自动化 + +项目包含完整的 GitHub Actions 工作流,支持: + +- ✅ **自动测试** - 每次推送和 PR 都会运行测试 +- ✅ **多平台构建** - 自动构建所有支持的平台 +- ✅ **自动发布** - 标签推送时自动创建 GitHub Release +- ✅ **Docker 镜像** - 自动构建和推送多架构 Docker 镜像 +- ✅ **校验和验证** - 自动生成文件校验和 + ## 功能特性 ### 🎯 高性能优化 @@ -77,6 +214,7 @@ docker run -p 1080:1080 -p 8090:8090 wormhole-server:v1.0.0 - ✅ **速率限制** - Token Bucket算法,全局+单IP限制 - ✅ **内存优化** - 缓冲区池,减少 30% 内存使用 - ⚠️ **透明代理** - Linux/macOS iptables/pfctl支持 (默认关闭) +- ✅ **多平台支持** - 11个平台/架构组合 ### 🛡 企业安全 - ✅ **IP 访问控制** - 白名单/黑名单 diff --git a/cmd/wormhole-server/main.go b/cmd/wormhole-server/main.go index 552eef6..b654922 100644 --- a/cmd/wormhole-server/main.go +++ b/cmd/wormhole-server/main.go @@ -6,24 +6,26 @@ import ( "log" "os" "os/signal" + "runtime" "syscall" "github.com/azoic/wormhole-server/internal/server" ) var ( - version = "v1.0.0" + version = "v1.1.0" buildTime = "unknown" + gitCommit = "unknown" ) func main() { configPath := flag.String("config", "configs/server.yaml", "Configuration file path") showVersion := flag.Bool("version", false, "Show version information") + verboseVersion := flag.Bool("version-verbose", false, "Show detailed version information") flag.Parse() - if *showVersion { - fmt.Printf("Wormhole SOCKS5 Server %s\n", version) - fmt.Printf("Build time: %s\n", buildTime) + if *showVersion || *verboseVersion { + showVersionInfo(*verboseVersion) os.Exit(0) } @@ -56,3 +58,28 @@ func main() { fmt.Println("✅ Server stopped") } + +func showVersionInfo(verbose bool) { + fmt.Printf("Wormhole SOCKS5 Server %s\n", version) + + if verbose { + fmt.Printf("\nBuild Information:\n") + fmt.Printf(" Version: %s\n", version) + fmt.Printf(" Build Time: %s\n", buildTime) + fmt.Printf(" Git Commit: %s\n", gitCommit) + fmt.Printf(" Go Version: %s\n", runtime.Version()) + fmt.Printf(" Platform: %s/%s\n", runtime.GOOS, runtime.GOARCH) + fmt.Printf(" Compiler: %s\n", runtime.Compiler) + + fmt.Printf("\nFeatures:\n") + fmt.Printf(" ✅ SOCKS5 Protocol Support\n") + fmt.Printf(" ✅ Rate Limiting (Token Bucket)\n") + fmt.Printf(" ✅ Connection Pool Management\n") + fmt.Printf(" ✅ Memory Optimization\n") + fmt.Printf(" ✅ Health Check & Metrics\n") + fmt.Printf(" ⚠️ DNS Caching (Temporarily Disabled)\n") + fmt.Printf(" ⚠️ Transparent Proxy (Default Disabled)\n") + } else { + fmt.Printf("Build time: %s\n", buildTime) + } +} diff --git a/configs/server.yaml b/configs/server.yaml index 722bf5f..bbee8ea 100644 --- a/configs/server.yaml +++ b/configs/server.yaml @@ -2,8 +2,10 @@ serviceType: server proxy: - address: 0.0.0.0 + address: 0.0.0.0 # IPv4监听地址 port: 1080 + enableIPv6: true # 启用IPv6支持 + addressv6: "::" # IPv6监听地址 auth: username: admin @@ -11,7 +13,8 @@ auth: methods: - password -timeout: 30s +# 增加超时时间以处理Docker的大文件下载 +timeout: 300s # 5分钟超时,适合Docker镜像下载 maxConns: 5000 logLevel: info @@ -23,48 +26,48 @@ healthCheck: # Optimization Features (将在迁移中实现) optimizedServer: enabled: true - maxIdleTime: 5m - bufferSize: 65536 + maxIdleTime: 10m # 增加空闲时间 + bufferSize: 131072 # 增加缓冲区到128KB,适合大文件传输 logConnections: true # DNS Caching (暂时禁用,避免端口冲突) dnsCache: - enabled: false + enabled: true maxSize: 10000 ttl: 10m - # Rate Limiting + # Rate Limiting - 放宽限制以支持Docker下载 rateLimit: enabled: true - requestsPerSecond: 100 - burstSize: 200 - perIPRequestsPerSec: 10 - perIPBurstSize: 20 + requestsPerSecond: 200 # 增加到200 RPS + burstSize: 500 # 增加突发大小 + perIPRequestsPerSec: 50 # 单IP增加到50 RPS + perIPBurstSize: 100 # 单IP突发增加到100 cleanupInterval: 5m - # Connection Pool + # Connection Pool - 优化Docker连接 connectionPool: enabled: true - maxSize: 1000 - maxLifetime: 30m - maxIdle: 5m + maxSize: 2000 # 增加连接池大小 + maxLifetime: 60m # 增加连接生命周期到1小时 + maxIdle: 15m # 增加空闲时间到15分钟 initialSize: 0 # Memory Optimization memory: enabled: true - bufferSizes: [512, 1024, 2048, 4096, 8192, 16384, 32768, 65536] + bufferSizes: [1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072] # 增加更大的缓冲区 monitorInterval: 30s enableAutoGC: true - heapAllocThresholdMB: 100 - heapSysThresholdMB: 200 - forceGCThresholdMB: 500 + heapAllocThresholdMB: 200 # 增加GC阈值 + heapSysThresholdMB: 400 + forceGCThresholdMB: 800 # Transparent Proxy (requires root permissions) transparent: enabled: false transparentPort: 8888 - dnsPort: 15353 + dnsPort: 15353 # 服务器端DNS端口,避免与客户端5353端口冲突 bypassIPs: - "127.0.0.1" - "192.168.1.0/24" @@ -72,14 +75,47 @@ optimizedServer: - "localhost" - "*.local" - # Access Control + # Access Control - 允许连接到所有地址 accessControl: allowedIPs: - - "127.0.0.1" - - "192.168.1.0/24" - - "10.0.0.0/8" + - "0.0.0.0/0" # 允许所有IPv4地址 + - "::/0" # 允许所有IPv6地址 + + # 明确允许的域名(如果有域名过滤的话) + allowedDomains: + - "*" # 允许所有域名 + - "*.docker.io" + - "registry-1.docker.io" + - "auth.docker.io" + - "registry.docker.io" + - "index.docker.io" + - "*.docker.com" + - "hub.docker.com" + - "*.github.com" + - "*.google.com" + - "*.googleapis.com" + - "*.cloudflare.com" + - "*.amazonaws.com" + - "*.azurecr.io" + + # 阻止的域名(黑名单) + blockedDomains: [] + + # 阻止的IP(黑名单) + blockedIPs: [] # Performance Monitoring metrics: enabled: true interval: 5m + +# Docker专用优化配置 +docker: + # 针对Docker镜像下载的特殊优化 + enabled: true + # 大文件传输超时 (Docker镜像可能很大) + largeFileTimeout: 1800s # 30分钟 + # 针对Docker registry的keep-alive设置 + keepAliveTimeout: 300s # 5分钟 + # 最大并发下载数 + maxConcurrentDownloads: 10 diff --git a/internal/server/server.go b/internal/server/server.go index bff76fa..2025e8a 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -57,14 +57,40 @@ func (cf *ConnectionFactory) Validate(conn net.Conn) bool { return false } - // 简单的连接验证 - conn.SetReadDeadline(time.Now().Add(1 * time.Second)) - defer conn.SetReadDeadline(time.Time{}) + // 保存原始的读取截止时间 + var originalDeadline time.Time + if deadline, ok := conn.(interface{ RemoteAddr() net.Addr }); ok { + // 尝试获取远程地址,如果连接已关闭会失败 + if deadline.RemoteAddr() == nil { + return false + } + } - // 尝试读取0字节来检查连接状态 - buf := make([]byte, 0) + // 设置短暂的读取超时进行连接检查 + conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) + defer func() { + // 恢复原始的读取截止时间 + conn.SetReadDeadline(originalDeadline) + }() + + // 使用非阻塞的方式检查连接状态 + // 尝试读取1字节,但不期望有数据 + buf := make([]byte, 1) _, err := conn.Read(buf) - return err == nil + + // 如果是超时错误,说明连接是活跃的(没有数据可读但连接正常) + if netErr, ok := err.(net.Error); ok && netErr.Timeout() { + return true + } + + // 如果没有错误,说明有数据可读,连接正常 + // 但是需要将读取的数据放回去(这在实际应用中比较困难) + if err == nil { + return true + } + + // 其他错误表示连接有问题 + return false } func (cf *ConnectionFactory) Close(conn net.Conn) error { @@ -127,8 +153,9 @@ func (s *Server) Start(configPath string) error { s.logger.WithField("rps", cfg.OptimizedServer.RateLimit.RequestsPerSecond).Info("Rate limiting enabled") } - // 初始化连接池 + // 初始化连接池(注意:SOCKS5代理的连接池使用受限) if cfg.OptimizedServer.ConnectionPool.Enabled { + s.logger.Warn("Connection pool for SOCKS5 proxy has limited effectiveness due to dynamic target addresses") poolConfig := pool.Config{ MaxSize: cfg.OptimizedServer.ConnectionPool.MaxSize, MaxLifetime: cfg.OptimizedServer.ConnectionPool.MaxLifetime, @@ -141,9 +168,10 @@ func (s *Server) Start(configPath string) error { } s.connectionPool, err = pool.NewConnectionPool(poolConfig, factory, s.logger) if err != nil { - s.logger.WithError(err).Warn("Failed to create connection pool") + s.logger.WithError(err).Warn("Failed to create connection pool, continuing without connection pooling") + s.connectionPool = nil // 确保连接池为nil,避免后续使用 } else { - s.logger.WithField("max_size", cfg.OptimizedServer.ConnectionPool.MaxSize).Info("Connection pool enabled (no pre-connections for SOCKS5)") + s.logger.WithField("max_size", cfg.OptimizedServer.ConnectionPool.MaxSize).Info("Connection pool initialized (limited effectiveness for SOCKS5)") } } diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100755 index 0000000..413b6b7 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,298 @@ +#!/bin/bash + +# 多平台构建脚本 +# 用法: ./scripts/build.sh [版本号] [平台] + +set -e + +# 默认值 +VERSION=${1:-"v1.1.0"} +PLATFORM=${2:-"all"} + +# 配置 +APP_NAME="wormhole-server" +BUILD_TIME=$(date -u '+%Y-%m-%d_%H:%M:%S') +GIT_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown") + +# 颜色输出 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# 支持的平台列表 +SUPPORTED_PLATFORMS=( + "linux-amd64:linux:amd64:" + "linux-arm64:linux:arm64:" + "linux-386:linux:386:" + "linux-arm:linux:arm:" + "darwin-amd64:darwin:amd64:" + "darwin-arm64:darwin:arm64:" + "windows-amd64:windows:amd64:.exe" + "windows-386:windows:386:.exe" + "windows-arm64:windows:arm64:.exe" + "freebsd-amd64:freebsd:amd64:" + "freebsd-arm64:freebsd:arm64:" +) + +# 日志函数 +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warn() { + echo -e "${YELLOW}[WARN]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# 获取平台信息 +get_platform_info() { + local platform=$1 + for entry in "${SUPPORTED_PLATFORMS[@]}"; do + IFS=':' read -ra parts <<< "$entry" + if [[ "${parts[0]}" == "$platform" ]]; then + echo "${parts[1]} ${parts[2]} ${parts[3]}" + return 0 + fi + done + return 1 +} + +# 显示帮助信息 +show_help() { + echo "多平台构建脚本 - Wormhole Server" + echo "" + echo "用法:" + echo " $0 [版本号] [平台]" + echo "" + echo "参数:" + echo " 版本号 构建版本 (默认: v1.1.0)" + echo " 平台 目标平台 (默认: all)" + echo "" + echo "支持的平台:" + for entry in "${SUPPORTED_PLATFORMS[@]}"; do + IFS=':' read -ra parts <<< "$entry" + echo " ${parts[0]} - ${parts[1]} ${parts[2]}" + done + echo " all - 构建所有平台" + echo "" + echo "示例:" + echo " $0 # 构建所有平台,版本 v1.1.0" + echo " $0 v1.2.0 # 构建所有平台,版本 v1.2.0" + echo " $0 v1.2.0 linux-amd64 # 构建 Linux AMD64 版本" + echo " $0 v1.2.0 darwin-arm64 # 构建 macOS ARM64 版本" +} + +# 检查依赖 +check_dependencies() { + log_info "检查构建依赖..." + + if ! command -v go &> /dev/null; then + log_error "Go 未安装或不在 PATH 中" + exit 1 + fi + + GO_VERSION=$(go version | cut -d' ' -f3) + log_info "Go 版本: $GO_VERSION" + + if ! command -v git &> /dev/null; then + log_warn "Git 未安装,将使用默认提交哈希" + fi +} + +# 构建单个平台 +build_platform() { + local platform=$1 + + local platform_info=$(get_platform_info "$platform") + if [[ $? -ne 0 ]]; then + log_error "不支持的平台: $platform" + return 1 + fi + + IFS=' ' read -ra parts <<< "$platform_info" + local goos=${parts[0]} + local goarch=${parts[1]} + local ext=${parts[2]:-""} + + local binary_name="${APP_NAME}-${VERSION}-${platform}${ext}" + local output_path="dist/${binary_name}" + + log_info "构建 ${platform} (${goos}/${goarch})..." + + # 创建输出目录 + mkdir -p dist + + # 设置环境变量并构建 + GOOS=$goos GOARCH=$goarch go build \ + -ldflags "-X main.version=${VERSION} -X main.buildTime=${BUILD_TIME} -X main.gitCommit=${GIT_COMMIT} -s -w" \ + -o "$output_path" \ + cmd/wormhole-server/main.go + + if [[ $? -eq 0 ]]; then + local size=$(du -h "$output_path" | cut -f1) + log_success "构建完成: $output_path ($size)" + return 0 + else + log_error "构建失败: $platform" + return 1 + fi +} + +# 构建所有平台 +build_all() { + log_info "开始构建所有平台..." + + local success_count=0 + local total_count=${#SUPPORTED_PLATFORMS[@]} + + for entry in "${SUPPORTED_PLATFORMS[@]}"; do + IFS=':' read -ra parts <<< "$entry" + local platform=${parts[0]} + if build_platform "$platform"; then + ((success_count++)) + fi + echo "" + done + + log_info "构建统计: $success_count/$total_count 成功" + + if [[ $success_count -eq $total_count ]]; then + log_success "所有平台构建成功!" + return 0 + else + log_warn "部分平台构建失败" + return 1 + fi +} + +# 创建发布包 +create_release_packages() { + log_info "创建发布包..." + + cd dist + + for file in ${APP_NAME}-${VERSION}-*; do + if [[ -f "$file" ]]; then + if [[ "$file" == *.exe ]]; then + # Windows 平台使用 zip + platform=$(echo "$file" | sed "s/${APP_NAME}-${VERSION}-//; s/.exe$//") + if command -v zip &> /dev/null; then + zip -q "${APP_NAME}-${VERSION}-${platform}.zip" "$file" ../configs/server.yaml ../README.md + log_success "创建包: ${APP_NAME}-${VERSION}-${platform}.zip" + else + log_warn "zip 命令未找到,跳过 Windows 包创建" + fi + else + # 其他平台使用 tar.gz + platform=$(echo "$file" | sed "s/${APP_NAME}-${VERSION}-//") + tar -czf "${APP_NAME}-${VERSION}-${platform}.tar.gz" "$file" -C .. configs/server.yaml README.md + log_success "创建包: ${APP_NAME}-${VERSION}-${platform}.tar.gz" + fi + fi + done + + # 创建校验和文件 + if ls ${APP_NAME}-${VERSION}-*.{tar.gz,zip} 1> /dev/null 2>&1; then + sha256sum ${APP_NAME}-${VERSION}-*.{tar.gz,zip} 2>/dev/null > ${APP_NAME}-${VERSION}-checksums.txt || \ + shasum -a 256 ${APP_NAME}-${VERSION}-*.{tar.gz,zip} > ${APP_NAME}-${VERSION}-checksums.txt + log_success "创建校验和文件: ${APP_NAME}-${VERSION}-checksums.txt" + fi + + cd .. +} + +# 显示构建结果 +show_results() { + log_info "构建结果:" + + if [[ -d "dist" ]]; then + echo "" + ls -lh dist/ | grep -E "(${APP_NAME}|总计|total)" + echo "" + + log_info "要运行本地版本,使用:" + if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" ]]; then + echo " .\\dist\\${APP_NAME}-${VERSION}-windows-amd64.exe -config configs\\server.yaml" + elif [[ "$OSTYPE" == "darwin"* ]]; then + if [[ $(uname -m) == "arm64" ]]; then + echo " ./dist/${APP_NAME}-${VERSION}-darwin-arm64 -config configs/server.yaml" + else + echo " ./dist/${APP_NAME}-${VERSION}-darwin-amd64 -config configs/server.yaml" + fi + else + echo " ./dist/${APP_NAME}-${VERSION}-linux-amd64 -config configs/server.yaml" + fi + fi +} + +# 主函数 +main() { + echo "==============================================" + echo " Wormhole Server 多平台构建脚本" + echo "==============================================" + echo "" + + # 处理帮助参数 + if [[ "$1" == "-h" || "$1" == "--help" ]]; then + show_help + exit 0 + fi + + log_info "构建版本: $VERSION" + log_info "目标平台: $PLATFORM" + log_info "构建时间: $BUILD_TIME" + log_info "Git 提交: $GIT_COMMIT" + echo "" + + # 检查依赖 + check_dependencies + echo "" + + # 下载依赖 + log_info "下载 Go 模块依赖..." + go mod download + go mod tidy + echo "" + + # 执行构建 + local build_success=false + + if [[ "$PLATFORM" == "all" ]]; then + if build_all; then + build_success=true + fi + else + if build_platform "$PLATFORM"; then + build_success=true + fi + fi + + # 创建发布包 (仅在构建成功时) + if [[ "$build_success" == true && "$PLATFORM" == "all" ]]; then + echo "" + create_release_packages + fi + + echo "" + show_results + + if [[ "$build_success" == true ]]; then + log_success "构建完成!" + exit 0 + else + log_error "构建失败!" + exit 1 + fi +} + +# 运行主函数 +main "$@" \ No newline at end of file diff --git a/scripts/setup-docker-proxy.sh b/scripts/setup-docker-proxy.sh new file mode 100755 index 0000000..63dee46 --- /dev/null +++ b/scripts/setup-docker-proxy.sh @@ -0,0 +1,248 @@ +#!/bin/bash + +# Docker SOCKS5 代理配置脚本 +# 用法: ./scripts/setup-docker-proxy.sh [SOCKS5地址] [用户名] [密码] + +set -e + +# 默认配置 +SOCKS5_HOST=${1:-"127.0.0.1"} +SOCKS5_PORT=${2:-"1080"} +USERNAME=${3:-"admin"} +PASSWORD=${4:-"secure123"} + +# 颜色输出 +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +log_info() { + echo -e "${BLUE}[INFO]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[SUCCESS]${NC} $1" +} + +log_warn() { + echo -e "${YELLOW}[WARN]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +# 检查操作系统 +detect_os() { + if [[ "$OSTYPE" == "darwin"* ]]; then + echo "macos" + elif [[ "$OSTYPE" == "linux-gnu"* ]]; then + echo "linux" + else + echo "unknown" + fi +} + +# 配置Docker Desktop (macOS/Windows) +configure_docker_desktop() { + log_info "配置Docker Desktop代理设置..." + + # Docker Desktop配置文件路径 + if [[ "$(detect_os)" == "macos" ]]; then + DOCKER_CONFIG_DIR="$HOME/.docker" + else + DOCKER_CONFIG_DIR="$HOME/.docker" + fi + + mkdir -p "$DOCKER_CONFIG_DIR" + + # 创建daemon.json配置 + cat > "$DOCKER_CONFIG_DIR/daemon.json" << EOF +{ + "proxies": { + "default": { + "httpProxy": "socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT}", + "httpsProxy": "socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT}", + "noProxy": "localhost,127.0.0.1,*.local" + } + }, + "registry-mirrors": [ + "https://docker.mirrors.ustc.edu.cn", + "https://hub-mirror.c.163.com" + ] +} +EOF + + log_success "Docker daemon.json 配置已创建: $DOCKER_CONFIG_DIR/daemon.json" +} + +# 配置Docker客户端 +configure_docker_client() { + log_info "配置Docker客户端代理设置..." + + DOCKER_CONFIG_DIR="$HOME/.docker" + mkdir -p "$DOCKER_CONFIG_DIR" + + # 创建config.json配置 + cat > "$DOCKER_CONFIG_DIR/config.json" << EOF +{ + "proxies": { + "default": { + "httpProxy": "socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT}", + "httpsProxy": "socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT}", + "noProxy": "localhost,127.0.0.1,*.local" + } + } +} +EOF + + log_success "Docker 客户端配置已创建: $DOCKER_CONFIG_DIR/config.json" +} + +# 配置systemd服务 (Linux) +configure_docker_systemd() { + log_info "配置Docker systemd服务代理..." + + DOCKER_SERVICE_DIR="/etc/systemd/system/docker.service.d" + + if [[ ! -d "$DOCKER_SERVICE_DIR" ]]; then + log_info "创建Docker服务目录: $DOCKER_SERVICE_DIR" + sudo mkdir -p "$DOCKER_SERVICE_DIR" + fi + + # 创建代理配置文件 + sudo tee "$DOCKER_SERVICE_DIR/proxy.conf" > /dev/null << EOF +[Service] +Environment="HTTP_PROXY=socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT}" +Environment="HTTPS_PROXY=socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT}" +Environment="NO_PROXY=localhost,127.0.0.1,*.local" +EOF + + log_success "Docker systemd 代理配置已创建" + + # 重新加载配置 + log_info "重新加载systemd配置..." + sudo systemctl daemon-reload + sudo systemctl restart docker + + log_success "Docker服务已重启" +} + +# 设置环境变量 +setup_env_vars() { + log_info "设置环境变量..." + + cat << EOF + +# 添加以下环境变量到您的 ~/.bashrc 或 ~/.zshrc: +export HTTP_PROXY=socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT} +export HTTPS_PROXY=socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT} +export NO_PROXY=localhost,127.0.0.1,*.local + +# 或者临时设置 (当前shell有效): +EOF + + echo "export HTTP_PROXY=socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT}" + echo "export HTTPS_PROXY=socks5://${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT}" + echo "export NO_PROXY=localhost,127.0.0.1,*.local" +} + +# 测试连接 +test_connection() { + log_info "测试SOCKS5连接..." + + # 测试SOCKS5代理是否可用 + if command -v curl &> /dev/null; then + if curl --socks5 "${USERNAME}:${PASSWORD}@${SOCKS5_HOST}:${SOCKS5_PORT}" \ + --connect-timeout 10 \ + -s https://registry-1.docker.io/v2/ > /dev/null; then + log_success "SOCKS5代理连接测试成功" + else + log_error "SOCKS5代理连接测试失败" + return 1 + fi + else + log_warn "curl未安装,跳过连接测试" + fi +} + +# 显示帮助信息 +show_help() { + echo "Docker SOCKS5 代理配置脚本" + echo "" + echo "用法:" + echo " $0 [SOCKS5地址] [端口] [用户名] [密码]" + echo "" + echo "参数:" + echo " SOCKS5地址 SOCKS5服务器地址 (默认: 127.0.0.1)" + echo " 端口 SOCKS5服务器端口 (默认: 1080)" + echo " 用户名 认证用户名 (默认: admin)" + echo " 密码 认证密码 (默认: secure123)" + echo "" + echo "示例:" + echo " $0 # 使用默认配置" + echo " $0 192.168.1.100 1080 user pass # 自定义配置" +} + +# 主函数 +main() { + echo "==============================================" + echo " Docker SOCKS5 代理配置脚本" + echo "==============================================" + echo "" + + if [[ "$1" == "-h" || "$1" == "--help" ]]; then + show_help + exit 0 + fi + + log_info "SOCKS5服务器: ${SOCKS5_HOST}:${SOCKS5_PORT}" + log_info "认证信息: ${USERNAME}:${PASSWORD}" + echo "" + + # 测试连接 + if ! test_connection; then + log_error "请确保SOCKS5服务器正在运行并且配置正确" + exit 1 + fi + + # 检测操作系统并配置 + OS=$(detect_os) + case $OS in + "macos") + log_info "检测到macOS系统" + configure_docker_desktop + configure_docker_client + ;; + "linux") + log_info "检测到Linux系统" + configure_docker_client + if systemctl is-active --quiet docker; then + configure_docker_systemd + else + log_warn "Docker服务未运行,跳过systemd配置" + fi + ;; + *) + log_warn "未知操作系统,仅配置客户端" + configure_docker_client + ;; + esac + + echo "" + setup_env_vars + echo "" + + log_success "Docker代理配置完成!" + log_info "请重启Docker Desktop或执行 'sudo systemctl restart docker' 使配置生效" + + echo "" + echo "测试命令:" + echo " docker pull hello-world" + echo " docker run hello-world" +} + +# 运行主函数 +main "$@" \ No newline at end of file