From 9eff7aabf4a2fa07a36e441c5948142fa7dcff2a Mon Sep 17 00:00:00 2001 From: tsosunchia <59512455+tsosunchia@users.noreply.github.com> Date: Thu, 5 Mar 2026 22:05:38 +0800 Subject: [PATCH] feat: introduce build variants for NextTrace with flavor options - Added three build flavors: `nexttrace` (full), `nexttrace-tiny`, and `ntr` (MTR-focused). - Updated README.md and README_zh_CN.md to reflect new build variants and their features. - Implemented manual build instructions for each flavor. - Enhanced command-line argument parsing to accommodate flavor-specific options. - Disabled WebUI and Globalping features in `nexttrace-tiny` and `ntr` flavors. - Created separate files for handling Globalping and WebUI functionality based on build flavor. - Added error handling for unavailable features in non-full builds. --- .cross_compile.sh | 118 +++++++++++++++------ .github/workflows/build.yml | 152 +++++++++++++++++---------- README.md | 73 +++++++++++++ README_zh_CN.md | 180 ++++++++++++++++++++++---------- cmd/cmd.go | 202 +++++++++++++++++++++--------------- cmd/deploy_disabled.go | 9 ++ cmd/deploy_full.go | 11 ++ cmd/flavor_full.go | 11 ++ cmd/flavor_ntr.go | 11 ++ cmd/flavor_tiny.go | 11 ++ cmd/globalping_disabled.go | 15 +++ cmd/globalping_full.go | 74 +++++++++++++ trace/globalping.go | 22 +--- trace/globalping_types.go | 24 +++++ 14 files changed, 672 insertions(+), 241 deletions(-) create mode 100644 cmd/deploy_disabled.go create mode 100644 cmd/deploy_full.go create mode 100644 cmd/flavor_full.go create mode 100644 cmd/flavor_ntr.go create mode 100644 cmd/flavor_tiny.go create mode 100644 cmd/globalping_disabled.go create mode 100644 cmd/globalping_full.go create mode 100644 trace/globalping_types.go diff --git a/.cross_compile.sh b/.cross_compile.sh index 2b84f2b..df758d7 100644 --- a/.cross_compile.sh +++ b/.cross_compile.sh @@ -3,8 +3,35 @@ set -Eeuo pipefail # -------- Config -------- -DIST_PREFIX="nexttrace" -DEBUG_MODE="${1:-}" # 支持 ./script.sh debug +# Usage: .cross_compile.sh [full|tiny|ntr|all] [debug] +# full — build nexttrace (Full, includes WebUI + Globalping + MTR) +# tiny — build nexttrace-tiny (no WebUI, no Globalping, no MTR) +# ntr — build ntr (MTR-only, default MTR mode) +# all — build all three flavors (default) +# debug — enable debug symbols (can combine: .cross_compile.sh all debug) + +FLAVOR_ARG="${1:-all}" +DEBUG_MODE="${2:-}" + +# Allow "debug" as first arg for backward compat +if [[ "${FLAVOR_ARG}" == "debug" ]]; then + FLAVOR_ARG="all" + DEBUG_MODE="debug" +fi + +# Define flavor specs: "bin_name:build_tags" +declare -a FLAVOR_SPECS +case "${FLAVOR_ARG}" in + full) FLAVOR_SPECS=("nexttrace:") ;; + tiny) FLAVOR_SPECS=("nexttrace-tiny:flavor_tiny") ;; + ntr) FLAVOR_SPECS=("ntr:flavor_ntr") ;; + all) FLAVOR_SPECS=("nexttrace:" "nexttrace-tiny:flavor_tiny" "ntr:flavor_ntr") ;; + *) + echo "Usage: $0 [full|tiny|ntr|all] [debug]" >&2 + exit 1 + ;; +esac + TARGET_DIR="dist" PLATFORMS="linux/386 linux/amd64 linux/arm64 linux/mips linux/mips64 linux/mipsle linux/mips64le linux/loong64 windows/amd64 windows/arm64 openbsd/amd64 openbsd/arm64 freebsd/amd64 freebsd/arm64" UPX_BIN="${UPX_BIN:-$(command -v upx 2>/dev/null || true)}" @@ -28,6 +55,32 @@ if [[ "${DEBUG_MODE}" == "debug" ]]; then GO_BUILD_FLAGS=(-trimpath -gcflags "all=-N -l") fi +# build_one BIN TAGS GOOS GOARCH [EXTRA_ENV...] +build_one() { + local bin="$1" tags="$2" goos="$3" goarch="$4" + shift 4 + local target="${TARGET_DIR}/${bin}_${goos}_${goarch}" + # Apply extra env vars (e.g. GOARM=7 suffix) + for ev in "$@"; do + local key="${ev%%=*}" val="${ev#*=}" + if [[ "${key}" == "GOARM" ]]; then + target="${target}v${val}" + elif [[ "${key}" == "GOMIPS" && "${val}" == "softfloat" ]]; then + target="${target}_softfloat" + fi + done + if [[ "${goos}" == "windows" ]]; then + target="${target}.exe" + fi + + local tags_flag="" + if [[ -n "${tags}" ]]; then tags_flag="-tags ${tags}"; fi + + echo "build => ${target} (tags: ${tags:-none})" + env "$@" go build "${GO_BUILD_FLAGS[@]}" ${tags_flag} -o "${target}" -ldflags "${LD_BASE}" + compress_with_upx "${target}" "${goos}" "${goarch}" "" "quiet" +} + compress_with_upx() { local binary="${1:-}" local target_os="${2:-}" @@ -69,6 +122,8 @@ else echo "info: using upx at ${UPX_BIN} with flags ${UPX_FLAGS}" >&2 fi +echo "info: building flavor(s): ${FLAVOR_ARG}" >&2 + # -------- Prepare out dir -------- rm -rf -- "${TARGET_DIR}" mkdir -p -- "${TARGET_DIR}" @@ -80,21 +135,19 @@ for pl in ${PLATFORMS}; do GOARCH="${pl#*/}" export GOOS GOARCH - TARGET="${TARGET_DIR}/${DIST_PREFIX}_${GOOS}_${GOARCH}" - if [[ "${GOOS}" == "windows" ]]; then - TARGET="${TARGET}.exe" - fi - - echo "build => ${TARGET}" - go build "${GO_BUILD_FLAGS[@]}" -o "${TARGET}" -ldflags "${LD_BASE}" - compress_with_upx "${TARGET}" "${GOOS}" "${GOARCH}" + for SPEC in "${FLAVOR_SPECS[@]}"; do + BIN="${SPEC%%:*}" + TAGS="${SPEC#*:}" + build_one "${BIN}" "${TAGS}" "${GOOS}" "${GOARCH}" + done # Extra soft-float variants for linux/mips and linux/mipsle if [[ "${GOOS}" == "linux" && ( "${GOARCH}" == "mips" || "${GOARCH}" == "mipsle" ) ]]; then - TARGET_SOFT="${TARGET_DIR}/${DIST_PREFIX}_${GOOS}_${GOARCH}_softfloat" - echo "build => ${TARGET_SOFT} (GOMIPS=softfloat)" - GOMIPS=softfloat go build "${GO_BUILD_FLAGS[@]}" -o "${TARGET_SOFT}" -ldflags "${LD_BASE}" - compress_with_upx "${TARGET_SOFT}" "${GOOS}" "${GOARCH}" + for SPEC in "${FLAVOR_SPECS[@]}"; do + BIN="${SPEC%%:*}" + TAGS="${SPEC#*:}" + build_one "${BIN}" "${TAGS}" "${GOOS}" "${GOARCH}" "GOMIPS=softfloat" + done fi done @@ -103,10 +156,11 @@ export CGO_ENABLED=0 export GOOS='linux' export GOARCH='arm' export GOARM='7' -TARGET="${TARGET_DIR}/${DIST_PREFIX}_${GOOS}_${GOARCH}v7" -echo "build => ${TARGET}" -go build "${GO_BUILD_FLAGS[@]}" -o "${TARGET}" -ldflags "${LD_BASE}" -compress_with_upx "${TARGET}" "${GOOS}" "${GOARCH}" "${GOARM}" +for SPEC in "${FLAVOR_SPECS[@]}"; do + BIN="${SPEC%%:*}" + TAGS="${SPEC#*:}" + build_one "${BIN}" "${TAGS}" "${GOOS}" "${GOARCH}" "GOARM=7" +done # -------- Darwin targets with CGO + SDK libpcap -------- if [[ "$(uname)" == "Darwin" ]]; then @@ -132,22 +186,26 @@ if [[ "$(uname)" == "Darwin" ]]; then export CGO_CFLAGS="-isysroot ${SDKROOT} ${ARCH_FLAG} -mmacosx-version-min=11.0" export CGO_LDFLAGS="-isysroot ${SDKROOT} ${ARCH_FLAG} -mmacosx-version-min=11.0" - TARGET="${TARGET_DIR}/${DIST_PREFIX}_${GOOS}_${GOARCH}" - echo "build => ${TARGET}" - go build "${GO_BUILD_FLAGS[@]}" -o "${TARGET}" -ldflags "${LD_BASE}" - compress_with_upx "${TARGET}" "${GOOS}" "${GOARCH}" + for SPEC in "${FLAVOR_SPECS[@]}"; do + BIN="${SPEC%%:*}" + TAGS="${SPEC#*:}" + build_one "${BIN}" "${TAGS}" "${GOOS}" "${GOARCH}" + done done # 合并 Universal 2(存在 lipo 才合并) if command -v lipo >/dev/null 2>&1; then - if [[ -f "${TARGET_DIR}/${DIST_PREFIX}_darwin_amd64" && -f "${TARGET_DIR}/${DIST_PREFIX}_darwin_arm64" ]]; then - lipo -create -output "${TARGET_DIR}/${DIST_PREFIX}_darwin_universal" \ - "${TARGET_DIR}/${DIST_PREFIX}_darwin_amd64" \ - "${TARGET_DIR}/${DIST_PREFIX}_darwin_arm64" - echo "build => ${TARGET_DIR}/${DIST_PREFIX}_darwin_universal" - else - echo "warn: missing one of darwin slices; skip universal lipo." >&2 - fi + for SPEC in "${FLAVOR_SPECS[@]}"; do + BIN="${SPEC%%:*}" + if [[ -f "${TARGET_DIR}/${BIN}_darwin_amd64" && -f "${TARGET_DIR}/${BIN}_darwin_arm64" ]]; then + lipo -create -output "${TARGET_DIR}/${BIN}_darwin_universal" \ + "${TARGET_DIR}/${BIN}_darwin_amd64" \ + "${TARGET_DIR}/${BIN}_darwin_arm64" + echo "build => ${TARGET_DIR}/${BIN}_darwin_universal" + else + echo "warn: missing one of darwin slices for ${BIN}; skip universal lipo." >&2 + fi + done else echo "warn: lipo not found; skip universal binary." >&2 fi diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b333fdb..2056a4a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -106,19 +106,25 @@ jobs: ARM_SUFFIX="" if [ -n "${GOARM:-}" ]; then ARM_SUFFIX="v${GOARM}"; fi - NAME="nexttrace_${GOOS}_${GOARCH}${ARM_SUFFIX}" - if [ "${GOOS}" = "windows" ]; then NAME="${NAME}.exe"; fi - if [ "${GOMIPS:-}" = "softfloat" ]; then NAME="${NAME}_softfloat"; fi + PLATFORM="${GOOS}_${GOARCH}${ARM_SUFFIX}" + EXT="" + if [ "${GOOS}" = "windows" ]; then EXT=".exe"; fi + SOFT="" + if [ "${GOMIPS:-}" = "softfloat" ]; then SOFT="_softfloat"; fi if [ "$GOOS" = "android" ]; then ANDROID_API=21 TOOLCHAIN_BIN="${{ steps.setup-ndk.outputs.ndk-path }}/toolchains/llvm/prebuilt/linux-x86_64/bin" export CC="$TOOLCHAIN_BIN/aarch64-linux-android${ANDROID_API}-clang" echo "CC=${CC}" >> "$GITHUB_ENV" fi + echo "BUILD_VERSION=${BUILD_VERSION}" >> "$GITHUB_ENV" echo "BUILD_DATE=${BUILD_DATE}" >> "$GITHUB_ENV" echo "COMMIT_SHA1=${COMMIT_SHA1}" >> "$GITHUB_ENV" - echo "ASSET_NAME=${NAME}" >> "$GITHUB_ENV" + echo "ARM_SUFFIX=${ARM_SUFFIX}" >> "$GITHUB_ENV" + echo "PLATFORM=${PLATFORM}" >> "$GITHUB_ENV" + echo "EXT=${EXT}" >> "$GITHUB_ENV" + echo "SOFT=${SOFT}" >> "$GITHUB_ENV" - name: Get project dependencies run: go mod download @@ -135,33 +141,46 @@ jobs: sudo apt-get update sudo apt-get install -y upx - - name: Build + - name: Build all flavors run: | mkdir -p dist - go build -trimpath -o "dist/${ASSET_NAME}" \ - -ldflags "-X github.com/nxtrace/NTrace-core/config.Version=${BUILD_VERSION} \ - -X github.com/nxtrace/NTrace-core/config.BuildDate=${BUILD_DATE} \ - -X github.com/nxtrace/NTrace-core/config.CommitID=${COMMIT_SHA1} \ - -w -s" - if command -v upx >/dev/null 2>&1; then - case "${GOOS}-${GOARCH}-${GOARM:-}" in - linux-amd64-*) upx -9 "dist/${ASSET_NAME}" ;; - linux-386-*) upx -9 "dist/${ASSET_NAME}" ;; - linux-arm64-*) upx -9 "dist/${ASSET_NAME}" ;; - linux-arm-7) upx -9 "dist/${ASSET_NAME}" ;; - *) - echo "skip upx for ${GOOS}/${GOARCH}${GOARM:+/v${GOARM}}" - ;; - esac - else - echo "upx not available; skipping compression for ${GOOS}/${GOARCH}${GOARM:+/v${GOARM}}" - fi + LD_BASE="-X github.com/nxtrace/NTrace-core/config.Version=${BUILD_VERSION} \ + -X github.com/nxtrace/NTrace-core/config.BuildDate=${BUILD_DATE} \ + -X github.com/nxtrace/NTrace-core/config.CommitID=${COMMIT_SHA1} \ + -w -s" + for SPEC in "nexttrace:" "nexttrace-tiny:flavor_tiny" "ntr:flavor_ntr"; do + BIN="${SPEC%%:*}" + TAGS="${SPEC#*:}" + NAME="${BIN}_${PLATFORM}${EXT}${SOFT}" + TAGS_FLAG="" + if [ -n "$TAGS" ]; then TAGS_FLAG="-tags $TAGS"; fi + echo "build => dist/${NAME} (tags: ${TAGS:-none})" + go build -trimpath $TAGS_FLAG -o "dist/${NAME}" -ldflags "$LD_BASE" + if command -v upx >/dev/null 2>&1; then + case "${GOOS}-${GOARCH}-${GOARM:-}" in + linux-amd64-*|linux-386-*|linux-arm64-*|linux-arm-7) upx -9 "dist/${NAME}" ;; + *) ;; + esac + fi + done - - name: Upload artifact + - name: Verify tiny/ntr decoupling + run: | + set -Eeuo pipefail + for BIN in "nexttrace-tiny" "ntr"; do + FNAME="${BIN}_${PLATFORM}${EXT}${SOFT}" + if go version -m "dist/${FNAME}" 2>/dev/null | grep -qE 'github\.com/gin-gonic/gin|github\.com/jsdelivr/globalping-cli'; then + echo "FAIL: ${FNAME} contains gin or globalping-cli dependency" + exit 1 + fi + done + echo "Decoupling check passed" + + - name: Upload artifacts uses: actions/upload-artifact@v7 with: - name: ${{ env.ASSET_NAME }} - path: dist/${{ env.ASSET_NAME }} + name: build-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.goarm && format('-v{0}', matrix.goarm) || '' }}${{ matrix.gomips && format('-{0}', matrix.gomips) || '' }} + path: dist/ if-no-files-found: error build-darwin: @@ -217,32 +236,50 @@ jobs: BUILD_VERSION="$(git describe --tags --always 2>/dev/null || echo dev)" BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" COMMIT_SHA1="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)" - NAME="nexttrace_${GOOS}_${GOARCH}" echo "BUILD_VERSION=${BUILD_VERSION}" >> "$GITHUB_ENV" echo "BUILD_DATE=${BUILD_DATE}" >> "$GITHUB_ENV" echo "COMMIT_SHA1=${COMMIT_SHA1}" >> "$GITHUB_ENV" - echo "ASSET_NAME=${NAME}" >> "$GITHUB_ENV" - name: Get project dependencies run: go mod download - - name: Build (Darwin, CGO+libpcap via SDK) + - name: Build all flavors (Darwin, CGO+libpcap via SDK) run: | mkdir -p dist - go build -trimpath -o "dist/${ASSET_NAME}" \ - -ldflags "-X github.com/nxtrace/NTrace-core/config.Version=${BUILD_VERSION} \ - -X github.com/nxtrace/NTrace-core/config.BuildDate=${BUILD_DATE} \ - -X github.com/nxtrace/NTrace-core/config.CommitID=${COMMIT_SHA1} \ - -w -s" + LD_BASE="-X github.com/nxtrace/NTrace-core/config.Version=${BUILD_VERSION} \ + -X github.com/nxtrace/NTrace-core/config.BuildDate=${BUILD_DATE} \ + -X github.com/nxtrace/NTrace-core/config.CommitID=${COMMIT_SHA1} \ + -w -s" + for SPEC in "nexttrace:" "nexttrace-tiny:flavor_tiny" "ntr:flavor_ntr"; do + BIN="${SPEC%%:*}" + TAGS="${SPEC#*:}" + NAME="${BIN}_${GOOS}_${GOARCH}" + TAGS_FLAG="" + if [ -n "$TAGS" ]; then TAGS_FLAG="-tags $TAGS"; fi + echo "build => dist/${NAME} (tags: ${TAGS:-none})" + go build -trimpath $TAGS_FLAG -o "dist/${NAME}" -ldflags "$LD_BASE" + done - - name: Upload artifact + - name: Verify tiny/ntr decoupling + run: | + set -Eeuo pipefail + for BIN in "nexttrace-tiny" "ntr"; do + FNAME="${BIN}_${GOOS}_${GOARCH}" + if go version -m "dist/${FNAME}" 2>/dev/null | grep -qE 'github\.com/gin-gonic/gin|github\.com/jsdelivr/globalping-cli'; then + echo "FAIL: ${FNAME} contains gin or globalping-cli dependency" + exit 1 + fi + done + echo "Decoupling check passed" + + - name: Upload artifacts uses: actions/upload-artifact@v7 with: - name: ${{ env.ASSET_NAME }} - path: dist/${{ env.ASSET_NAME }} + name: build-darwin-${{ matrix.goarch }} + path: dist/ if-no-files-found: error - # NEW: 构建 Universal,并上传为 Artifact(不依赖 tag) + # Build Universal binaries for all flavors darwin-universal: runs-on: macos-latest needs: [ build-darwin ] @@ -250,33 +287,38 @@ jobs: - name: Download darwin slices (flatten) uses: actions/download-artifact@v8 with: - pattern: nexttrace_darwin_* + pattern: build-darwin-* merge-multiple: true path: dist - - name: Make macOS Universal (amd64+arm64) + - name: Make macOS Universal (amd64+arm64) for all flavors run: | set -Eeuo pipefail - AMD64="dist/nexttrace_darwin_amd64" - ARM64="dist/nexttrace_darwin_arm64" - if [ -f "$AMD64" ] && [ -f "$ARM64" ]; then - lipo -create -output dist/nexttrace_darwin_universal "$AMD64" "$ARM64" - file dist/nexttrace_darwin_universal || true - echo "✅ Built: dist/nexttrace_darwin_universal" - else - echo "❌ Missing darwin slices; cannot build universal." >&2 - exit 1 - fi + for BIN in nexttrace nexttrace-tiny ntr; do + AMD64="dist/${BIN}_darwin_amd64" + ARM64="dist/${BIN}_darwin_arm64" + if [ -f "$AMD64" ] && [ -f "$ARM64" ]; then + lipo -create -output "dist/${BIN}_darwin_universal" "$AMD64" "$ARM64" + file "dist/${BIN}_darwin_universal" || true + echo "Built: dist/${BIN}_darwin_universal" + else + echo "Missing darwin slices for ${BIN}; cannot build universal." >&2 + exit 1 + fi + done ls -l dist - - name: Upload universal as artifact + - name: Upload universal artifacts uses: actions/upload-artifact@v7 with: - name: nexttrace_darwin_universal - path: dist/nexttrace_darwin_universal + name: build-darwin-universal + path: | + dist/nexttrace_darwin_universal + dist/nexttrace-tiny_darwin_universal + dist/ntr_darwin_universal if-no-files-found: error - # 发布时仅下载所有 Artifact(包含 universal),直接发布 + # Download all build artifacts and publish to a single release release: runs-on: ubuntu-latest needs: [ build, build-darwin, darwin-universal ] @@ -285,7 +327,7 @@ jobs: - name: Download all artifacts (flatten) uses: actions/download-artifact@v8 with: - pattern: nexttrace_* + pattern: build-* merge-multiple: true path: dist_release diff --git a/README.md b/README.md index b613a50..7476c90 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,79 @@ Please note, the repositories for all of the above installation methods are main - `Release` provides compiled binary executables for many systems and different architectures. If none are available, you can compile it yourself. - Some essential dependencies of this project are not fully implemented on `Windows` by `Golang`, so currently, `NextTrace` is in an experimental support phase on the `Windows` platform. +### Build Variants + +Starting from this release, NextTrace is published in **three flavors** under the same tag. Choose the one that best fits your use case: + +| Feature | `nexttrace` (Full) | `nexttrace-tiny` | `ntr` | +| --------------------- | :----------------: | :--------------: | :----------: | +| Normal traceroute | ✅ | ✅ | — | +| MTR TUI | ✅ | — | ✅ (default) | +| MTR report (`-r`) | ✅ | — | ✅ | +| MTR wide (`-w`) | ✅ | — | ✅ | +| MTR raw (`--raw`) | ✅ | — | ✅ | +| Globalping (`--from`) | ✅ | — | — | +| WebUI (`--deploy`) | ✅ | — | — | +| Fast Trace (`-F`) | ✅ | ✅ | — | +| Default mode | traceroute | traceroute | MTR TUI | +| Binary name | `nexttrace` | `nexttrace-tiny` | `ntr` | + +> **Note:** Package managers (Homebrew, AUR, Scoop, etc.) currently install the **Full** (`nexttrace`) version only. + +### Feature Matrix + +- **`nexttrace`** — Full-featured build. Includes everything: traceroute, MTR, Globalping, and WebUI. +- **`nexttrace-tiny`** — Lightweight build. Normal traceroute only, no MTR / Globalping / WebUI. Suitable for embedded or minimal environments. +- **`ntr`** — MTR-focused build. Runs MTR TUI by default. No Globalping / WebUI; no normal traceroute mode. + +### Manual Build + +Build from source with Go 1.22+ installed: + +```bash +# Full (all features) +go build -trimpath -o dist/nexttrace -ldflags "-w -s" . + +# Tiny (no MTR, no Globalping, no WebUI) +go build -tags flavor_tiny -trimpath -o dist/nexttrace-tiny -ldflags "-w -s" . + +# NTR (MTR-only) +go build -tags flavor_ntr -trimpath -o dist/ntr -ldflags "-w -s" . +``` + +Cross-compile example: + +```bash +# Linux arm64, Tiny flavor +GOOS=linux GOARCH=arm64 CGO_ENABLED=0 \ + go build -tags flavor_tiny -trimpath -o dist/nexttrace-tiny_linux_arm64 -ldflags "-w -s" . +``` + +The `tiny` and `ntr` flavors use **compile-time build tags** to exclude modules — this is not a runtime switch. You can verify with `go version -m ` that `gin` and `globalping-cli` are absent from `nexttrace-tiny` and `ntr`. + +The `.cross_compile.sh` script supports building flavors: + +```bash +./.cross_compile.sh all # Build all three flavors for all platforms +./.cross_compile.sh full # Build only nexttrace (Full) +./.cross_compile.sh tiny # Build only nexttrace-tiny +./.cross_compile.sh ntr # Build only ntr +``` + +### Release Assets Naming + +Release binaries follow this naming convention: + +``` +{binary}_{os}_{arch}[v{arm}][.exe][_softfloat] +``` + +Examples: + +- `nexttrace_linux_amd64`, `nexttrace-tiny_linux_amd64`, `ntr_linux_amd64` +- `nexttrace_darwin_universal`, `nexttrace-tiny_darwin_universal`, `ntr_darwin_universal` +- `nexttrace_windows_amd64.exe`, `ntr_windows_amd64.exe` + ### Get Started `NextTrace` uses the `ICMP` protocol to perform TraceRoute requests by default, which supports both `IPv4` and `IPv6` diff --git a/README_zh_CN.md b/README_zh_CN.md index ecfb328..cf4d3bf 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -8,10 +8,9 @@
NextTrace
-

一款追求轻量化的开源可视化路由跟踪工具。

---------------------------------------- +---
主页:www.nxtrace.org
@@ -43,8 +42,6 @@ - - 我们非常感谢 [DMIT](https://dmit.io)、 [Misaka](https://misaka.io) 和 [SnapStack](https://portal.saltyfish.io) 提供了支持本项目所需的网络基础设施。 ## How To Use @@ -62,14 +59,13 @@ Document Language: [English](README.md) | 简体中文 ### Automated Install -* Linux - * 一键安装脚本 +- Linux + - 一键安装脚本 ```shell curl -sL https://nxtrace.org/nt | bash ``` - - * 从 nxtrace的APT源安装 - * 支持 AMD64/ARM64 架构 + - 从 nxtrace的APT源安装 + - 支持 AMD64/ARM64 架构 ```shell curl -fsSL https://github.com/nxtrace/nexttrace-debs/releases/latest/download/nexttrace-archive-keyring.gpg | sudo tee /etc/apt/keyrings/nexttrace.gpg >/dev/null echo "Types: deb @@ -79,81 +75,155 @@ Document Language: [English](README.md) | 简体中文 sudo apt update sudo apt install nexttrace ``` - * APT源由 wcbing, nxtrace 维护 + - APT源由 wcbing, nxtrace 维护 - * Arch Linux AUR 安装命令 - * 直接下载bin包(仅支持amd64) + - Arch Linux AUR 安装命令 + - 直接下载bin包(仅支持amd64) ```shell yay -S nexttrace-bin ``` - * 从源码构建(仅支持amd64) + - 从源码构建(仅支持amd64) ```shell yay -S nexttrace ``` - * AUR 的构建分别由 ouuan, huyz 维护 + - AUR 的构建分别由 ouuan, huyz 维护 - * Linuxbrew 安装命令 + - Linuxbrew 安装命令 - 同macOS Homebrew安装方法(homebrew-core版仅支持amd64) + 同macOS Homebrew安装方法(homebrew-core版仅支持amd64) + + - deepin 安装命令 - * deepin 安装命令 ```shell apt install nexttrace ``` - * [x-cmd](https://cn.x-cmd.com/pkg/nexttrace) 安装命令 + - [x-cmd](https://cn.x-cmd.com/pkg/nexttrace) 安装命令 + ```shell x env use nexttrace ``` - * Termux 安装命令 + - Termux 安装命令 ```shell pkg install root-repo pkg install nexttrace ``` - - * ImmortalWrt 安装命令 + - ImmortalWrt 安装命令 ```shell opkg install nexttrace ``` - - -* macOS - * macOS Homebrew 安装命令 - * homebrew-core版 + +- macOS + - macOS Homebrew 安装命令 + - homebrew-core版 ```shell brew install nexttrace ``` - * 本仓库ACTIONS自动构建版(更新更快) + - 本仓库ACTIONS自动构建版(更新更快) ```shell brew tap nxtrace/nexttrace && brew install nxtrace/nexttrace/nexttrace ``` - * homebrew-core 构建由 chenrui333 维护,请注意该版本更新可能会落后仓库Action自动构建版本 + - homebrew-core 构建由 chenrui333 维护,请注意该版本更新可能会落后仓库Action自动构建版本 -* Windows - * Windows WinGet 安装命令 - * WinGet 版 +- Windows + - Windows WinGet 安装命令 + - WinGet 版 ```powershell winget install nexttrace ``` - * WinGet 构建由 Dragon1573 维护 + - WinGet 构建由 Dragon1573 维护 - * Windows Scoop 安装命令 - * scoop-extras 版 + - Windows Scoop 安装命令 + - scoop-extras 版 ```powershell scoop bucket add extras && scoop install extras/nexttrace ``` - * scoop-extra 由 soenggam 维护 + + - scoop-extra 由 soenggam 维护 请注意,以上多种安装方式的仓库均由开源爱好者自行维护,不保证可用性和及时更新,如遇到问题请联系仓库维护者解决,或使用本项目官方编译提供的二进制包。 ### Manual Install -* 下载预编译的可执行程序 - - 对于以上方法没有涵盖的用户,请直接前往 [Release](https://www.nxtrace.org/downloads) 下载编译后的二进制可执行文件。 - * `Release`里面为很多系统以及不同架构提供了编译好的二进制可执行文件,如果没有可以自行编译。 - * 一些本项目的必要依赖在`Windows`上`Golang`底层实现不完全,所以目前`NextTrace`在`Windows`平台出于实验性支持阶段。 +- 下载预编译的可执行程序 + + 对于以上方法没有涵盖的用户,请直接前往 [Release](https://www.nxtrace.org/downloads) 下载编译后的二进制可执行文件。 + - `Release`里面为很多系统以及不同架构提供了编译好的二进制可执行文件,如果没有可以自行编译。 + - 一些本项目的必要依赖在`Windows`上`Golang`底层实现不完全,所以目前`NextTrace`在`Windows`平台出于实验性支持阶段。 + +### 版本说明 + +从本版本开始,NextTrace 在同一 release tag 下发布 **三种构建版本**,按需选用: + +| 功能 | `nexttrace`(完整版) | `nexttrace-tiny` | `ntr` | +| ----------------------- | :-------------------: | :--------------: | :--------: | +| 常规 traceroute | ✅ | ✅ | — | +| MTR TUI | ✅ | — | ✅(默认) | +| MTR 报告(`-r`) | ✅ | — | ✅ | +| MTR 宽报告(`-w`) | ✅ | — | ✅ | +| MTR 原始输出(`--raw`) | ✅ | — | ✅ | +| Globalping(`--from`) | ✅ | — | — | +| WebUI(`--deploy`) | ✅ | — | — | +| 快速跟踪(`-F`) | ✅ | ✅ | — | +| 默认运行模式 | traceroute | traceroute | MTR TUI | +| 二进制名 | `nexttrace` | `nexttrace-tiny` | `ntr` | + +> **注意:** 包管理器(Homebrew、AUR、Scoop 等)目前仅安装 **完整版**(`nexttrace`)。 + +### 功能对比 + +- **`nexttrace`** — 完整版。包含所有功能:traceroute、MTR、Globalping 与 WebUI。 +- **`nexttrace-tiny`** — 精简版。仅保留常规 traceroute,不含 MTR / Globalping / WebUI。适合嵌入式或极简环境。 +- **`ntr`** — MTR 专用版。默认启动 MTR TUI。无 Globalping / WebUI,无常规 traceroute 模式。 + +### 手动编译 + +需要 Go 1.22+ 环境: + +```bash +# 完整版(所有功能) +go build -trimpath -o dist/nexttrace -ldflags "-w -s" . + +# 精简版(无 MTR、无 Globalping、无 WebUI) +go build -tags flavor_tiny -trimpath -o dist/nexttrace-tiny -ldflags "-w -s" . + +# MTR 专用版 +go build -tags flavor_ntr -trimpath -o dist/ntr -ldflags "-w -s" . +``` + +交叉编译示例: + +```bash +# Linux arm64 精简版 +GOOS=linux GOARCH=arm64 CGO_ENABLED=0 \ + go build -tags flavor_tiny -trimpath -o dist/nexttrace-tiny_linux_arm64 -ldflags "-w -s" . +``` + +`tiny` 和 `ntr` 版本通过 **编译期 build tags** 裁剪模块——不是运行时开关。可通过 `go version -m ` 验证 `nexttrace-tiny` 和 `ntr` 中不包含 `gin` 与 `globalping-cli`。 + +`.cross_compile.sh` 脚本支持按版本构建: + +```bash +./.cross_compile.sh all # 构建全部三个版本(所有平台) +./.cross_compile.sh full # 仅构建 nexttrace(完整版) +./.cross_compile.sh tiny # 仅构建 nexttrace-tiny +./.cross_compile.sh ntr # 仅构建 ntr +``` + +### 发行资产命名规则 + +Release 二进制文件命名格式: + +``` +{二进制名}_{操作系统}_{架构}[v{arm版本}][.exe][_softfloat] +``` + +示例: + +- `nexttrace_linux_amd64`、`nexttrace-tiny_linux_amd64`、`ntr_linux_amd64` +- `nexttrace_darwin_universal`、`nexttrace-tiny_darwin_universal`、`ntr_darwin_universal` +- `nexttrace_windows_amd64.exe`、`ntr_windows_amd64.exe` ### Get Started @@ -195,12 +265,13 @@ PS: 路由可视化的绘制模块为独立模块,具体代码可在 [nxtrace/ 路由可视化功能因为需要每个 Hop 的地理位置坐标,而第三方 API 通常不提供此类信息,所以此功能目前只支持搭配 LeoMoeAPI 使用。 #### `Windows` 用户必须完成的配置步骤 + - 对于普通用户模式: 只能使用 **ICMP mode**,且需防火墙配置允许`ICMP/ICMPv6`。 - ```powershell - netsh advfirewall firewall add rule name="All ICMP v4" dir=in action=allow protocol=icmpv4:any,any - netsh advfirewall firewall add rule name="All ICMP v6" dir=in action=allow protocol=icmpv6:any,any - ``` + ```powershell + netsh advfirewall firewall add rule name="All ICMP v4" dir=in action=allow protocol=icmpv4:any,any + netsh advfirewall firewall add rule name="All ICMP v6" dir=in action=allow protocol=icmpv6:any,any + ``` - 对于管理员模式: **TCP/UDP mode** 依赖 `WinDivert`。 **ICMP mode** 支持 `1=Socket` 与 `2=WinDivert`(`0=Auto`)。使用 Socket 模式时,需防火墙配置允许`ICMP/ICMPv6`。 @@ -339,7 +410,7 @@ nexttrace -t --tcp --max-hops 20 --first 3 --no-rdns 8.8.8.8 - **`q` / `Q`** — 退出(恢复终端,不留下输出) - **`p`** — 暂停探测 -- **空格** — 恢复探测 +- **空格** — 恢复探测 - **`r`** — 重置统计(计数器清零,显示模式保持不变) - **`y`** — 循环切换主机显示模式:ASN → City → Owner → Full - **`n`** — 切换主机名显示方式: @@ -599,10 +670,12 @@ NextTrace 所有的的 IP 地理位置 `API DEMO` 可以参考[这里](https://g [GitHub - sjlleo/nexttrace-backend: NextTrace BackEnd](https://github.com/sjlleo/nexttrace-backend) NextTrace `LeoMoeAPI`现已使用Proof of Work(POW)机制来防止滥用,其中NextTrace作为客户端引入了powclient库,POW CLIENT/SERVER均已开源,欢迎大家使用。(POW模块相关问题请发到对应的仓库) + - [GitHub - tsosunchia/powclient: Proof of Work CLIENT for NextTrace](https://github.com/tsosunchia/powclient) - [GitHub - tsosunchia/powserver: Proof of Work SERVER for NextTrace](https://github.com/tsosunchia/powserver) 对于中国大陆用户,可以使用 [Nya Labs](https://natfrp.com) 提供的位于大陆的POW服务器优化访问速度 + ```shell #使用方法任选其一 #1. 在环境变量中设置 @@ -635,6 +708,7 @@ nexttrace --pow-provider sakura Get it on Google Play ## Cloudflare Support + 本项目受 [Alexandria 计划](http://www.cloudflare.com/oss-credits)赞助。 Cloudflare Logo @@ -687,21 +761,21 @@ nexttrace --pow-provider sakura - 其他第三方 API 尽管集成在本项目内,但是具体的 TOS 以及 AUP,请详见第三方 API 官网。如遇到 IP 数据错误,也请直接联系他们纠错。 - - 如何获取最新commit的新鲜出炉的二进制可执行文件? - >请前往GitHub Actions中最新一次 [Build & Release](https://github.com/nxtrace/NTrace-V1/actions/workflows/build.yml) workflow. + > 请前往GitHub Actions中最新一次 [Build & Release](https://github.com/nxtrace/NTrace-V1/actions/workflows/build.yml) workflow. - 常见疑问 - + Windows 平台下,ICMP 模式须手动放行ICMP/ICMPv6防火墙 - + macOS 平台下,仅 ICMP 模式不需要提权运行 - + 在一些情况下,同时运行多个 NextTrace 实例可能会导致互相干扰结果(目前仅在 TCP 模式下有观察到) + - Windows 平台下,ICMP 模式须手动放行ICMP/ICMPv6防火墙 + - macOS 平台下,仅 ICMP 模式不需要提权运行 + - 在一些情况下,同时运行多个 NextTrace 实例可能会导致互相干扰结果(目前仅在 TCP 模式下有观察到) ## IP 数据以及精准度说明 对于IP相关信息的纠错反馈,我们目前开放了两个渠道: ->- 本项目的GITHUB ISSUES区中的[IP 错误报告汇总帖](https://github.com/orgs/nxtrace/discussions/222) ->- 本项目的纠错专用邮箱: `correct#nxtrace.org` (请注意此邮箱仅供IP相关信息纠错专用,其他反馈请发送ISSUE) + +> - 本项目的GITHUB ISSUES区中的[IP 错误报告汇总帖](https://github.com/orgs/nxtrace/discussions/222) +> - 本项目的纠错专用邮箱: `correct#nxtrace.org` (请注意此邮箱仅供IP相关信息纠错专用,其他反馈请发送ISSUE) NextTrace 有多个数据源可以选择,目前默认使用的 LeoMoeAPI 为我们项目维护的数据源。 @@ -728,6 +802,7 @@ LeoMoeAPI 已经尽力校准了比较常见的骨干网路由,这部分在测 ### GeoFeed 对于 geofeed.csv 来说,格式如下: + ``` IP_CDIR,LtdCode,ISO3166-2,CityName,ASN,IPWhois ``` @@ -747,6 +822,7 @@ IP_CDIR,LtdCode,ISO3166-2,CityName,ASN,IPWhois ### PTR 对于 ptr.csv 来说,格式如下: + ``` IATA_CODE,LtdCode,RegionName,CityName ``` diff --git a/cmd/cmd.go b/cmd/cmd.go index 0210a99..b58d977 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -23,7 +23,6 @@ import ( "github.com/nxtrace/NTrace-core/ipgeo" "github.com/nxtrace/NTrace-core/printer" "github.com/nxtrace/NTrace-core/reporter" - "github.com/nxtrace/NTrace-core/server" "github.com/nxtrace/NTrace-core/trace" "github.com/nxtrace/NTrace-core/tracelog" "github.com/nxtrace/NTrace-core/tracemap" @@ -31,6 +30,10 @@ import ( "github.com/nxtrace/NTrace-core/wshandle" ) +func ptrBool(v bool) *bool { return &v } +func ptrStr(v string) *string { return &v } +func ptrInt(v int) *int { return &v } + type listenInfo struct { Binding string Access string @@ -246,7 +249,7 @@ func fixPositionalAlignment(usage string) string { } func Execute() { - parser := argparse.NewParser("nexttrace", "An open source visual route tracking CLI tool") + parser := argparse.NewParser(appBinName, "An open source visual route tracking CLI tool") // Override HelpFunc so positional arg names are sanitized in --help output parser.HelpFunc = func(c *argparse.Command, msg interface{}) string { return sanitizeUsagePositionalArgs(c.Usage(msg)) @@ -257,10 +260,20 @@ func Execute() { ipv6Only := parser.Flag("6", "ipv6", &argparse.Options{Help: "Use IPv6 only"}) tcp := parser.Flag("T", "tcp", &argparse.Options{Help: "Use TCP SYN for tracerouting (default dest-port is 80)"}) udp := parser.Flag("U", "udp", &argparse.Options{Help: "Use UDP SYN for tracerouting (default dest-port is 33494)"}) - fast_trace := parser.Flag("F", "fast-trace", &argparse.Options{Help: "One-Key Fast Trace to China ISPs"}) + // ── Fast-trace: hidden in ntr (always conflicts with default MTR mode) ── + var fast_trace *bool + if !defaultMTR { + fast_trace = parser.Flag("F", "fast-trace", &argparse.Options{Help: "One-Key Fast Trace to China ISPs"}) + } else { + fast_trace = ptrBool(false) + } port := parser.Int("p", "port", &argparse.Options{Help: "Set the destination port to use. With default of 80 for \"tcp\", 33494 for \"udp\""}) icmpMode := parser.Int("", "icmp-mode", &argparse.Options{Help: "Windows ONLY: Choose the method to listen for ICMP packets (1=Socket, 2=WinDivert; 0=Auto)"}) - numMeasurements := parser.Int("q", "queries", &argparse.Options{Default: 3, Help: "Set the number of latency samples to display for each hop"}) + queriesHelp := "Set the number of latency samples to display for each hop" + if defaultMTR { + queriesHelp = "Set the max number of probes per hop in MTR mode (0 = unlimited for TUI; default 10 for --report)" + } + numMeasurements := parser.Int("q", "queries", &argparse.Options{Default: 3, Help: queriesHelp}) maxAttempts := parser.Int("", "max-attempts", &argparse.Options{Help: "Set the maximum number of probe packets per hop (instead of a fixed auto value)"}) parallelRequests := parser.Int("", "parallel-requests", &argparse.Options{Default: 18, Help: "Set ParallelRequests number. It should be 1 when there is a multi-routing"}) maxHops := parser.Int("m", "max-hops", &argparse.Options{Default: 30, Help: "Set the max number of hops (max TTL to be reached)"}) @@ -270,25 +283,73 @@ func Execute() { Help: "Choose PoW Provider [api.nxtrace.org, sakura] For China mainland users, please use sakura"}) norDNS := parser.Flag("n", "no-rdns", &argparse.Options{Help: "Do not resolve IP addresses to their domain names"}) alwaysrDNS := parser.Flag("a", "always-rdns", &argparse.Options{Help: "Always resolve IP addresses to their domain names"}) - routePath := parser.Flag("P", "route-path", &argparse.Options{Help: "Print traceroute hop path by ASN and location"}) + // ── Traceroute-only output flags (hidden in ntr — always conflict with default MTR mode) ── + var routePath, output, tablePrint, jsonPrint, classicPrint *bool + if !defaultMTR { + routePath = parser.Flag("P", "route-path", &argparse.Options{Help: "Print traceroute hop path by ASN and location"}) + output = parser.Flag("o", "output", &argparse.Options{Help: "Write trace result to file (RealTimePrinter ONLY)"}) + tablePrint = parser.Flag("", "table", &argparse.Options{Help: "Output trace results as a final summary table (traceroute report mode)"}) + jsonPrint = parser.Flag("j", "json", &argparse.Options{Help: "Output trace results as JSON"}) + classicPrint = parser.Flag("c", "classic", &argparse.Options{Help: "Classic Output trace results like BestTrace"}) + } else { + routePath = ptrBool(false) + output = ptrBool(false) + tablePrint = ptrBool(false) + jsonPrint = ptrBool(false) + classicPrint = ptrBool(false) + } dn42 := parser.Flag("", "dn42", &argparse.Options{Help: "DN42 Mode"}) - output := parser.Flag("o", "output", &argparse.Options{Help: "Write trace result to file (RealTimePrinter ONLY)"}) - tablePrint := parser.Flag("", "table", &argparse.Options{Help: "Output trace results as a final summary table (traceroute report mode)"}) - rawPrint := parser.Flag("", "raw", &argparse.Options{Help: "Machine-friendly output. With MTR (--mtr/-r/-w), enables streaming raw event mode"}) - jsonPrint := parser.Flag("j", "json", &argparse.Options{Help: "Output trace results as JSON"}) - classicPrint := parser.Flag("c", "classic", &argparse.Options{Help: "Classic Output trace results like BestTrace"}) + rawHelp := "Machine-friendly output" + if enableMTR { + rawHelp += ". With MTR (--mtr/-r/-w), enables streaming raw event mode" + } + rawPrint := parser.Flag("", "raw", &argparse.Options{Help: rawHelp}) beginHop := parser.Int("f", "first", &argparse.Options{Default: 1, Help: "Start from the first_ttl hop (instead of 1)"}) - disableMaptrace := parser.Flag("M", "map", &argparse.Options{Help: "Disable Print Trace Map"}) + // ── Map: hidden in ntr (MTR mode never prints a trace map) ── + var disableMaptrace *bool + if !defaultMTR { + disableMaptrace = parser.Flag("M", "map", &argparse.Options{Help: "Disable Print Trace Map"}) + } else { + disableMaptrace = ptrBool(true) // map is always suppressed in ntr + } disableMPLS := parser.Flag("e", "disable-mpls", &argparse.Options{Help: "Disable MPLS"}) ver := parser.Flag("V", "version", &argparse.Options{Help: "Print version info and exit"}) srcAddr := parser.String("s", "source", &argparse.Options{Help: "Use source address src_addr for outgoing packets"}) srcPort := parser.Int("", "source-port", &argparse.Options{Help: "Use source port src_port for outgoing packets"}) srcDev := parser.String("D", "dev", &argparse.Options{Help: "Use the following Network Devices as the source address in outgoing packets"}) - deployListen := parser.String("", "listen", &argparse.Options{Help: "Set listen address for web console (e.g. 127.0.0.1:30080)"}) - deploy := parser.Flag("", "deploy", &argparse.Options{Help: "Start the Gin powered web console"}) + + // ── WebUI flags (full only) ── + var deployListen *string + var deploy *bool + if enableWebUI { + deployListen = parser.String("", "listen", &argparse.Options{Help: "Set listen address for web console (e.g. 127.0.0.1:30080)"}) + deploy = parser.Flag("", "deploy", &argparse.Options{Help: "Start the Gin powered web console"}) + } else { + deployListen = ptrStr("") + deploy = ptrBool(false) + } + //router := parser.Flag("R", "route", &argparse.Options{Help: "Show Routing Table [Provided By BGP.Tools]"}) - packetInterval := parser.Int("z", "send-time", &argparse.Options{Default: defaultPacketIntervalMs, Help: "Set how many [milliseconds] between sending each packet. Default: 50ms. Ignored in MTR mode"}) - ttlInterval := parser.Int("i", "ttl-time", &argparse.Options{Default: defaultTracerouteTTLIntervalMs, Help: "Interval [ms] between TTL groups in normal traceroute (default: 300ms). In MTR mode (--mtr/-r/-w, including --raw), sets per-hop probe interval: how long between successive probes to the same hop (default: 1000ms when omitted)"}) + // ── Send-time: hidden in ntr (always ignored in MTR mode) ── + var packetInterval *int + if !defaultMTR { + sendTimeHelp := "Set how many [milliseconds] between sending each packet. Default: 50ms" + if enableMTR { + sendTimeHelp += ". Ignored in MTR mode" + } + packetInterval = parser.Int("z", "send-time", &argparse.Options{Default: defaultPacketIntervalMs, Help: sendTimeHelp}) + } else { + packetInterval = ptrInt(defaultPacketIntervalMs) + } + var ttlIntervalHelp string + if !enableMTR { + ttlIntervalHelp = "Set the interval [ms] between TTL groups for traceroute (default: 300ms)" + } else if defaultMTR { + ttlIntervalHelp = "Set the per-hop probe interval [ms] in MTR mode (default: 1000ms when omitted)" + } else { + ttlIntervalHelp = "Interval [ms] between TTL groups in normal traceroute (default: 300ms). In MTR mode (--mtr/-r/-w, including --raw), sets per-hop probe interval: how long between successive probes to the same hop (default: 1000ms when omitted)" + } + ttlInterval := parser.Int("i", "ttl-time", &argparse.Options{Default: defaultTracerouteTTLIntervalMs, Help: ttlIntervalHelp}) timeout := parser.Int("", "timeout", &argparse.Options{Default: 1000, Help: "The number of [milliseconds] to keep probe sockets open before giving up on the connection"}) packetSize := parser.Int("", "psize", &argparse.Options{Default: 52, Help: "Set the payload size"}) dot := parser.Selector("", "dot-server", []string{"dnssb", "aliyun", "dnspod", "google", "cloudflare"}, &argparse.Options{ @@ -296,13 +357,44 @@ func Execute() { lang := parser.Selector("g", "language", []string{"en", "cn"}, &argparse.Options{Default: "cn", Help: "Choose the language for displaying [en, cn]"}) noColor := parser.Flag("C", "no-color", &argparse.Options{Help: "Disable Colorful Output"}) - from := parser.String("", "from", &argparse.Options{Help: "Run traceroute via Globalping (https://globalping.io/network) from a specified location. The location field accepts continents, countries, regions, cities, ASNs, ISPs, or cloud regions."}) - mtrMode := parser.Flag("t", "mtr", &argparse.Options{Help: "Enable MTR (My Traceroute) continuous probing mode"}) - reportMode := parser.Flag("r", "report", &argparse.Options{Help: "MTR report mode (non-interactive, implies --mtr); can trigger MTR without --mtr"}) - wideMode := parser.Flag("w", "wide", &argparse.Options{Help: "MTR wide report mode (implies --mtr --report); alone equals --mtr --report --wide"}) - showIPs := parser.Flag("", "show-ips", &argparse.Options{Help: "MTR only: display both PTR hostnames and numeric IPs (PTR first, IP in parentheses)"}) - ipInfoMode := parser.Int("y", "ipinfo", &argparse.Options{Default: 0, Help: "Set initial MTR TUI host info mode (0-4). TUI only; ignored in --report/--raw. 0:IP/PTR 1:ASN 2:City 3:Owner 4:Full"}) - file := parser.String("", "file", &argparse.Options{Help: "Read IP Address or domain name from file"}) + + // ── Globalping flag (full only) ── + var from *string + if enableGlobalping { + from = parser.String("", "from", &argparse.Options{Help: "Run traceroute via Globalping (https://globalping.io/network) from a specified location. The location field accepts continents, countries, regions, cities, ASNs, ISPs, or cloud regions."}) + } else { + from = ptrStr("") + } + + // ── MTR flags (full & ntr only) ── + var mtrMode, reportMode, wideMode, showIPs *bool + var ipInfoMode *int + if enableMTR { + // ── -t/--mtr: hidden in ntr (always active by default) ── + if !defaultMTR { + mtrMode = parser.Flag("t", "mtr", &argparse.Options{Help: "Enable MTR (My Traceroute) continuous probing mode"}) + } else { + mtrMode = ptrBool(true) + } + reportMode = parser.Flag("r", "report", &argparse.Options{Help: "MTR report mode (non-interactive, implies --mtr); can trigger MTR without --mtr"}) + wideMode = parser.Flag("w", "wide", &argparse.Options{Help: "MTR wide report mode (implies --mtr --report); alone equals --mtr --report --wide"}) + showIPs = parser.Flag("", "show-ips", &argparse.Options{Help: "MTR only: display both PTR hostnames and numeric IPs (PTR first, IP in parentheses)"}) + ipInfoMode = parser.Int("y", "ipinfo", &argparse.Options{Default: 0, Help: "Set initial MTR TUI host info mode (0-4). TUI only; ignored in --report/--raw. 0:IP/PTR 1:ASN 2:City 3:Owner 4:Full"}) + } else { + mtrMode = ptrBool(false) + reportMode = ptrBool(false) + wideMode = ptrBool(false) + showIPs = ptrBool(false) + ipInfoMode = ptrInt(0) + } + + // ── File: hidden in ntr (conflicts with default MTR mode) ── + var file *string + if !defaultMTR { + file = parser.String("", "file", &argparse.Options{Help: "Read IP Address or domain name from file"}) + } else { + file = ptrStr("") + } str := parser.StringPositional(&argparse.Options{Help: "Trace target: IPv4 address (e.g. 8.8.8.8), IPv6 address (e.g. 2001:db8::1), domain name (e.g. example.com), or URL (e.g. https://example.com)"}) err := parser.Parse(os.Args) @@ -314,7 +406,7 @@ func Execute() { } // ── 统一 MTR 有效开关 ── - effectiveMTR := *mtrMode || *reportMode || *wideMode + effectiveMTR := *mtrMode || *reportMode || *wideMode || defaultMTR effectiveReport := *reportMode || *wideMode effectiveWide := *wideMode effectiveMTRRaw := effectiveMTR && *rawPrint @@ -396,7 +488,7 @@ func Execute() { } } fmt.Println("注意:Web 控制台的安全性有限,请在确保安全的前提下使用,如有必要请使用ACL等方式加强安全性") - if err := server.Run(listenAddr); err != nil { + if err := runDeploy(listenAddr); err != nil { if util.EnvDevMode { panic(err) } @@ -572,7 +664,7 @@ func Execute() { } if *from != "" { - executeGlobalpingTraceroute( + handleGlobalpingTrace( &trace.GlobalpingOptions{ Target: *str, From: *from, @@ -912,65 +1004,7 @@ func capabilitiesCheck() { } else { // 没权限啦 fmt.Println("您正在以普通用户权限运行 NextTrace,但 NextTrace 未被赋予监听网络套接字的ICMP消息包、修改IP头信息(TTL)等路由跟踪所需的权限") - fmt.Println("请使用管理员用户执行 `sudo setcap cap_net_raw,cap_net_admin+eip ${your_nexttrace_path}/nexttrace` 命令,赋予相关权限后再运行~") + fmt.Printf("请使用管理员用户执行 `sudo setcap cap_net_raw,cap_net_admin+eip ${your_nexttrace_path}/%s` 命令,赋予相关权限后再运行~\n", appBinName) fmt.Println("什么?为什么 ping 普通用户执行不要 root 权限?因为这些工具在管理员安装时就已经被赋予了一些必要的权限,具体请使用 `getcap /usr/bin/ping` 查看") } } - -func executeGlobalpingTraceroute(opts *trace.GlobalpingOptions, config *trace.Config) { - res, measurement, err := trace.GlobalpingTraceroute(opts, config) - if err != nil { - fmt.Println(err) - return - } - - if !opts.DisableMaptrace && - (util.StringInSlice(strings.ToUpper(opts.DataOrigin), []string{"LEOMOEAPI", "IPINFO", "IP-API.COM", "IPAPI.COM"})) { - r, err := json.Marshal(res) - if err != nil { - fmt.Println(err) - return - } - url, err := tracemap.GetMapUrl(string(r)) - if err != nil { - fmt.Println(err) - return - } - res.TraceMapUrl = url - } - - if opts.JSONPrint { - r, err := json.Marshal(res) - if err != nil { - fmt.Println(err) - return - } - fmt.Println(string(r)) - return - } - - if measurement == nil || len(measurement.Results) == 0 { - fmt.Println("Globalping 未返回可用的探测结果,已跳过输出。") - return - } - - fmt.Fprintln(color.Output, color.New(color.FgGreen, color.Bold).Sprintf("> %s", trace.GlobalpingFormatLocation(&measurement.Results[0]))) - - if opts.TablePrint { - printer.TracerouteTablePrinter(res) - } else { - for i := range res.Hops { - if opts.ClassicPrint { - printer.ClassicPrinter(res, i) - } else if opts.RawPrint { - printer.EasyPrinter(res, i) - } else { - printer.RealtimePrinter(res, i) - } - } - } - - if res.TraceMapUrl != "" { - tracemap.PrintMapUrl(res.TraceMapUrl) - } -} diff --git a/cmd/deploy_disabled.go b/cmd/deploy_disabled.go new file mode 100644 index 0000000..6c58985 --- /dev/null +++ b/cmd/deploy_disabled.go @@ -0,0 +1,9 @@ +//go:build flavor_tiny || flavor_ntr + +package cmd + +import "fmt" + +func runDeploy(_ string) error { + return fmt.Errorf("WebUI (--deploy) is not available in %s; please use the full nexttrace build", appBinName) +} diff --git a/cmd/deploy_full.go b/cmd/deploy_full.go new file mode 100644 index 0000000..9930db9 --- /dev/null +++ b/cmd/deploy_full.go @@ -0,0 +1,11 @@ +//go:build !flavor_tiny && !flavor_ntr + +package cmd + +import ( + "github.com/nxtrace/NTrace-core/server" +) + +func runDeploy(listenAddr string) error { + return server.Run(listenAddr) +} diff --git a/cmd/flavor_full.go b/cmd/flavor_full.go new file mode 100644 index 0000000..2207d27 --- /dev/null +++ b/cmd/flavor_full.go @@ -0,0 +1,11 @@ +//go:build !flavor_tiny && !flavor_ntr + +package cmd + +const ( + appBinName = "nexttrace" + enableWebUI = true + enableGlobalping = true + enableMTR = true + defaultMTR = false +) diff --git a/cmd/flavor_ntr.go b/cmd/flavor_ntr.go new file mode 100644 index 0000000..50b48e4 --- /dev/null +++ b/cmd/flavor_ntr.go @@ -0,0 +1,11 @@ +//go:build flavor_ntr + +package cmd + +const ( + appBinName = "ntr" + enableWebUI = false + enableGlobalping = false + enableMTR = true + defaultMTR = true +) diff --git a/cmd/flavor_tiny.go b/cmd/flavor_tiny.go new file mode 100644 index 0000000..106f169 --- /dev/null +++ b/cmd/flavor_tiny.go @@ -0,0 +1,11 @@ +//go:build flavor_tiny + +package cmd + +const ( + appBinName = "nexttrace-tiny" + enableWebUI = false + enableGlobalping = false + enableMTR = false + defaultMTR = false +) diff --git a/cmd/globalping_disabled.go b/cmd/globalping_disabled.go new file mode 100644 index 0000000..7a3a205 --- /dev/null +++ b/cmd/globalping_disabled.go @@ -0,0 +1,15 @@ +//go:build flavor_tiny || flavor_ntr + +package cmd + +import ( + "fmt" + "os" + + "github.com/nxtrace/NTrace-core/trace" +) + +func handleGlobalpingTrace(_ *trace.GlobalpingOptions, _ *trace.Config) { + fmt.Fprintf(os.Stderr, "--from (Globalping) is not available in %s; please use the full nexttrace build\n", appBinName) + os.Exit(1) +} diff --git a/cmd/globalping_full.go b/cmd/globalping_full.go new file mode 100644 index 0000000..f2eabef --- /dev/null +++ b/cmd/globalping_full.go @@ -0,0 +1,74 @@ +//go:build !flavor_tiny && !flavor_ntr + +package cmd + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/fatih/color" + + "github.com/nxtrace/NTrace-core/printer" + "github.com/nxtrace/NTrace-core/trace" + "github.com/nxtrace/NTrace-core/tracemap" + "github.com/nxtrace/NTrace-core/util" +) + +func handleGlobalpingTrace(opts *trace.GlobalpingOptions, config *trace.Config) { + res, measurement, err := trace.GlobalpingTraceroute(opts, config) + if err != nil { + fmt.Println(err) + return + } + + if !opts.DisableMaptrace && + (util.StringInSlice(strings.ToUpper(opts.DataOrigin), []string{"LEOMOEAPI", "IPINFO", "IP-API.COM", "IPAPI.COM"})) { + r, err := json.Marshal(res) + if err != nil { + fmt.Println(err) + return + } + url, err := tracemap.GetMapUrl(string(r)) + if err != nil { + fmt.Println(err) + return + } + res.TraceMapUrl = url + } + + if opts.JSONPrint { + r, err := json.Marshal(res) + if err != nil { + fmt.Println(err) + return + } + fmt.Println(string(r)) + return + } + + if measurement == nil || len(measurement.Results) == 0 { + fmt.Println("Globalping 未返回可用的探测结果,已跳过输出。") + return + } + + fmt.Fprintln(color.Output, color.New(color.FgGreen, color.Bold).Sprintf("> %s", trace.GlobalpingFormatLocation(&measurement.Results[0]))) + + if opts.TablePrint { + printer.TracerouteTablePrinter(res) + } else { + for i := range res.Hops { + if opts.ClassicPrint { + printer.ClassicPrinter(res, i) + } else if opts.RawPrint { + printer.EasyPrinter(res, i) + } else { + printer.RealtimePrinter(res, i) + } + } + } + + if res.TraceMapUrl != "" { + tracemap.PrintMapUrl(res.TraceMapUrl) + } +} diff --git a/trace/globalping.go b/trace/globalping.go index 2bf0947..1250817 100644 --- a/trace/globalping.go +++ b/trace/globalping.go @@ -1,3 +1,5 @@ +//go:build !flavor_tiny && !flavor_ntr + package trace import ( @@ -13,26 +15,6 @@ import ( "github.com/nxtrace/NTrace-core/util" ) -type GlobalpingOptions struct { - Target string - From string - IPv4 bool - IPv6 bool - TCP bool - UDP bool - Port int - Packets int - MaxHops int - - DisableMaptrace bool - DataOrigin string - - TablePrint bool - ClassicPrint bool - RawPrint bool - JSONPrint bool -} - func GlobalpingTraceroute(opts *GlobalpingOptions, config *Config) (*Result, *globalping.Measurement, error) { c := globalping.Config{ UserAgent: "NextTrace/" + _config.Version, diff --git a/trace/globalping_types.go b/trace/globalping_types.go new file mode 100644 index 0000000..b49432e --- /dev/null +++ b/trace/globalping_types.go @@ -0,0 +1,24 @@ +package trace + +// GlobalpingOptions configures a Globalping-based traceroute request. +// Defined in an untagged file so all build flavors can reference the type +// without pulling in the globalping-cli dependency. +type GlobalpingOptions struct { + Target string + From string + IPv4 bool + IPv6 bool + TCP bool + UDP bool + Port int + Packets int + MaxHops int + + DisableMaptrace bool + DataOrigin string + + TablePrint bool + ClassicPrint bool + RawPrint bool + JSONPrint bool +}