Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 21 additions & 64 deletions .github/upstream-waivers.txt

Large diffs are not rendered by default.

31 changes: 1 addition & 30 deletions .github/workflows/run-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,34 +51,6 @@ jobs:
- name: Replay the image build's Xray patch guards
run: make test_xray_guards XRAY_GUARD_SRC="$RUNNER_TEMP/xray-guard-src"

- name: Build the pinned sing-box the image ships
run: make build_singbox SINGBOX_SRC="$RUNNER_TEMP/sing-box-src" SINGBOX_OUTPUT="$RUNNER_TEMP/sing-box"

- name: Run the live sing-box tests against the pinned build
env:
REQUIRED_TESTS: >-
TestLiveSmoke_SingBoxProcessStartsAndReportsStats
TestAnEmptyHysteria2PasswordIsNeverAccepted
TestSharedHysteria2PasswordBillsTheSameUserEveryTime
TestASingBoxRestartKeepsTheUnreadTraffic
TestAUserSyncWhoseHotReloadFailsRestartsAndKeepsTheUnreadTraffic
TestTrafficCountedWhileASingBoxRestartWaitsForItsLockIsBilled
TestASingBoxFullSyncThatAddsAUserKeepsTheCoreAndTheUnreadTraffic
TestAUserAddedToARunningSingBoxIsBilled
TestTheRunningCoreHoldsItsClashSecretPrivately
run: |
set -o pipefail
log="$RUNNER_TEMP/singbox-live.log"
read -r -a required <<< "${REQUIRED_TESTS}"
pattern="^($(IFS='|'; echo "${required[*]}"))\$"
SINGBOX_SMOKE_BINARY="$RUNNER_TEMP/sing-box" XRAY_EXECUTABLE_PATH=/usr/local/bin/xray CGO_ENABLED=1 go test -race -count=1 -timeout 10m -v -run "${pattern}" ./backend/singbox/ 2>&1 | tee "$log"
for name in "${required[@]}"; do
if ! grep -Eq "^--- PASS: ${name} \(" "$log"; then
echo "::error title=Required sing-box test did not pass::${name}"
exit 1
fi
done

- name: install wg
run: make install_wg

Expand Down Expand Up @@ -116,8 +88,7 @@ jobs:

- name: Run the controller and backend tests under the race detector
run: |
TEST_INTEGRATION=true CGO_ENABLED=1 SINGBOX_EXECUTABLE_PATH="$RUNNER_TEMP/sing-box" \
go test -race -timeout 20m -v -p 1 ./controller/...
TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./controller/...
TEST_INTEGRATION=true CGO_ENABLED=1 go test -race -timeout 20m -v -p 1 ./backend/...

- name: Check Xray process status races
Expand Down
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,3 @@ certs/
generated/
pasarguard-node*
/main
sing-box-src/
40 changes: 2 additions & 38 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,41 +15,6 @@ RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} make NAME=main build

# --- sing-box (Hysteria2) builder ---
# Built from source rather than using the official prebuilt sing-box release binary:
# official releases are not compiled with the "with_v2ray_api" tag, which this node's
# backend/singbox stats client (v2ray-api gRPC, see backend/singbox and config.go's
# SINGBOX_EXECUTABLE_PATH) requires to report per-user traffic. Version and tag set are
# pinned to match what was built and traffic-tested (incl. Salamander-obfuscated
# Hysteria2 against real QUIC-blocking ISPs) for this fork.
FROM --platform=$BUILDPLATFORM golang:1.27.4-alpine@sha256:0a5f7fe796599ff487605987432e7619ae45beeb2fba4c2ce0b907879932aebf AS singbox-builder

ARG TARGETOS
ARG TARGETARCH
ARG SINGBOX_VERSION=v1.13.21
ARG SINGBOX_TAGS=with_quic,with_utls,with_clash_api,with_v2ray_api,http2legacy
# Our fork of sing-box v1.13.14: adds a clash_api PUT /hysteria2/users endpoint so
# Hysteria2 user changes apply live, without restarting the core (no dropped sessions).
ARG SINGBOX_REPO=https://github.com/Free-Guy-IR/sing-box.git
ARG SINGBOX_BRANCH=main
ARG SINGBOX_COMMIT=f92b2cdb67bcb5e14b3b404f6fc5e43286c2688d

RUN apk update && apk add --no-cache git

COPY scripts/singbox_http2_guard.sh /singbox_http2_guard.sh

WORKDIR /singbox-src
RUN git init -q . \
&& git remote add origin ${SINGBOX_REPO} \
&& git fetch -q --depth 1 origin ${SINGBOX_COMMIT} \
&& git checkout -q FETCH_HEAD \
&& test "$(git rev-parse HEAD)" = "${SINGBOX_COMMIT}"
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} sh /singbox_http2_guard.sh "${SINGBOX_TAGS}"
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath \
-tags "${SINGBOX_TAGS}" \
-ldflags "-X 'github.com/sagernet/sing-box/constant.Version=${SINGBOX_VERSION}' -s -w -buildid=" \
-o /out/sing-box ./cmd/sing-box

# --- xray builder ---
# Built from source rather than using the prebuilt release binary installed by
# make install_xray: Xray's commander starts its gRPC server with no options, so it
Expand All @@ -58,8 +23,8 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath \
# that server the same 64 MiB this node already allows elsewhere. The build applies the
# patch and then greps for the result, so a patch that stops applying fails the build
# instead of silently shipping an unpatched core. The source is pinned to a commit and
# the checkout is asserted against it, the same way the sing-box stage does, because a
# git tag can be moved and a tag alone would not tell us we built what we reviewed.
# the checkout is asserted against it, because a git tag can be moved and a tag alone
# would not tell us we built what we reviewed.
FROM --platform=$BUILDPLATFORM golang:1.27.4-alpine@sha256:0a5f7fe796599ff487605987432e7619ae45beeb2fba4c2ce0b907879932aebf AS xray-builder

ARG TARGETOS
Expand Down Expand Up @@ -356,7 +321,6 @@ COPY --from=builder /src/main /app/main
COPY --from=xray-builder /out/xray /usr/local/bin/xray
COPY --from=geo-assets /geo/geoip.dat /usr/local/share/xray/geoip.dat
COPY --from=geo-assets /geo/geosite.dat /usr/local/share/xray/geosite.dat
COPY --from=singbox-builder /out/sing-box /usr/local/bin/sing-box
COPY --from=filter-assets /assets/pgfilter.dat /usr/local/share/xray/pgfilter.dat
COPY --from=filter-assets /assets/pgfilter_index.json /usr/local/share/xray/pgfilter_index.json

Expand Down
24 changes: 1 addition & 23 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ ifeq ($(shell echo "$(GOARCH)" | grep -Eq "(mips|mipsle)" && echo true),true)
ADDITION = GOMIPS=softfloat go build -o $(NAME)_softfloat -trimpath -ldflags "$(LDFLAGS)" -v $(MAIN)
endif

.PHONY: clean build build_xray build_singbox test_singbox_http2_guard test_xray_guards test_xray_patches test test-race-wireguard test-integration test-integration-full test-integration-wireguard test-drift \
.PHONY: clean build build_xray test_xray_guards test_xray_patches test test-race-wireguard test-integration test-integration-full test-integration-wireguard test-drift \
install_geofiles check_geofiles update_geofiles_pin

build:
Expand Down Expand Up @@ -239,28 +239,6 @@ build_xray:
cd "$(XRAY_SRC)" && echo "xray $(XRAY_COMMIT) needs go $$(sed -n 's/^go //p' go.mod); building with $$(GOTOOLCHAIN=local go version)"
cd "$(XRAY_SRC)" && GOTOOLCHAIN=local CGO_ENABLED=0 go build -trimpath -ldflags "$(XRAY_LDFLAGS)" -o "$(XRAY_OUTPUT)" ./main

SINGBOX_REPO ?= $(shell sed -n 's/^ARG SINGBOX_REPO=//p' Dockerfile)
SINGBOX_COMMIT ?= $(shell sed -n 's/^ARG SINGBOX_COMMIT=//p' Dockerfile)
SINGBOX_VERSION ?= $(shell sed -n 's/^ARG SINGBOX_VERSION=//p' Dockerfile)
SINGBOX_TAGS ?= $(shell sed -n 's/^ARG SINGBOX_TAGS=//p' Dockerfile)
SINGBOX_SRC ?= $(CURDIR)/sing-box-src
SINGBOX_OUTPUT ?= $(SINGBOX_SRC)/sing-box

build_singbox: test_singbox_http2_guard
test -n "$(SINGBOX_REPO)" && test -n "$(SINGBOX_COMMIT)" && test -n "$(SINGBOX_VERSION)" && test -n "$(SINGBOX_TAGS)" && test -n "$(SINGBOX_SRC)"
rm -rf "$(SINGBOX_SRC)"
git init -q "$(SINGBOX_SRC)"
git -C "$(SINGBOX_SRC)" remote add origin $(SINGBOX_REPO)
git -C "$(SINGBOX_SRC)" fetch -q --depth 1 origin $(SINGBOX_COMMIT)
git -C "$(SINGBOX_SRC)" checkout -q FETCH_HEAD
test "$$(git -C "$(SINGBOX_SRC)" rev-parse HEAD)" = "$(SINGBOX_COMMIT)"
cd "$(SINGBOX_SRC)" && GOTOOLCHAIN=local CGO_ENABLED=0 sh $(CURDIR)/scripts/singbox_http2_guard.sh "$(SINGBOX_TAGS)"
cd "$(SINGBOX_SRC)" && GOTOOLCHAIN=local CGO_ENABLED=0 go build -trimpath -tags "$(SINGBOX_TAGS)" -ldflags "-X 'github.com/sagernet/sing-box/constant.Version=$(SINGBOX_VERSION)' -s -w -buildid=" -o "$(SINGBOX_OUTPUT)" ./cmd/sing-box
"$(SINGBOX_OUTPUT)" version

test_singbox_http2_guard:
bash scripts/test_singbox_http2_guard.sh

XRAY_GUARD_SRC ?= $(CURDIR)/xray-guard-src
XRAY_FREEDOM_GEOIP_DAT ?= $(wildcard $(GEOFILES_DIR)/geoip.dat)

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
</a>
</p>

> Note: This is the [Free-Guy-IR](https://github.com/Free-Guy-IR) fork of the original [PasarGuard node](https://github.com/Free-Guy-IR/node), extended with sing-box (Hysteria2), OpenVPN, and L2TP/IPsec backend support.
> Note: This is the [Free-Guy-IR](https://github.com/Free-Guy-IR) fork of the original [PasarGuard node](https://github.com/Free-Guy-IR/node), extended with OpenVPN and L2TP/IPsec backend support.

# One-Click Installation (Recommended)
The easiest way to install PasarGuard Node is using our automated installation script:
Expand All @@ -41,7 +41,7 @@ node-eu-1 edit-env

You can run any other subcommand for that same node with the same prefix (`node-eu-1 ...`).

> ⚠️ **Important:** Never reuse ports between nodes. The connection port and every core's inbound/instance ports (Xray, sing-box, OpenVPN, ...) attached to each node must be completely unique per node.
> ⚠️ **Important:** Never reuse ports between nodes. The connection port and every core's inbound/instance ports (Xray, OpenVPN, ...) attached to each node must be completely unique per node.

# Moving a Node to Another Panel

Expand Down
10 changes: 0 additions & 10 deletions backend/openvpn/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,6 @@ type PKI struct {
TLSCryptKey string `json:"tls_crypt_key"`
}

// InstanceConfig describes one OpenVPN server process ("instance"): one
// listening proto/port/tun-device combination. This is the OpenVPN analogue
// of a sing-box "inbound" or an xray inbound - user.go matches against
// InstanceConfig.Tag exactly the way singbox/xray match a user's Inbounds
// against an inbound tag.
type InstanceConfig struct {
Tag string `json:"tag"`
Protocol string `json:"protocol"`
Expand Down Expand Up @@ -87,11 +82,6 @@ const (
defaultVerb = 3
)

// NewConfig parses and validates raw OpenVPN backend config JSON (see the
// package doc comment in openvpn.go for the exact shape). Mirrors
// singbox.NewConfig's validation style: clear, specific error messages and
// fail fast on anything that would otherwise start a broken or ambiguous set
// of OpenVPN processes.
func NewConfig(raw string) (*Config, error) {
var cfg Config
if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
Expand Down
3 changes: 0 additions & 3 deletions backend/openvpn/core_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@ import (
"syscall"
)

// setProcAttributes sets Unix-specific process attributes for proper process
// group management (used by Stop()'s SIGTERM/SIGKILL escalation and by
// killProcessTree). Mirrors backend/singbox/core_unix.go.
func setProcAttributes(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Expand Down
7 changes: 0 additions & 7 deletions backend/openvpn/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ import (

// logRing is a small fixed-size circular buffer of recent log lines, used to
// give context (e.g. in an error returned to the caller) when startup fails.
// Mirrors backend/singbox/log.go's logRing exactly (kept as an independent
// copy rather than a shared import - this repo does not share internal
// helper packages between backend implementations; xray and singbox each
// carry their own near-identical process/log helpers too).
type logRing struct {
mu sync.Mutex
lines []string
Expand Down Expand Up @@ -125,9 +121,6 @@ func (p *instanceProcess) recordLog(line string) {
}
}

// isStartupFailureLog is a best-effort heuristic for detecting fatal openvpn
// startup errors from its log output, analogous to backend/singbox/log.go's
// isStartupFailureLog and backend/xray/startup_diagnostics.go's.
func isStartupFailureLog(line string) bool {
lower := strings.ToLower(line)

Expand Down
27 changes: 0 additions & 27 deletions backend/openvpn/management.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,33 +14,6 @@ import (
"time"
)

// ManagementClient talks OpenVPN's line-based management-interface protocol
// over one instance's Unix domain socket (see render.go's "management
// <path> unix" / "management-client-auth" directives). It is the only piece
// of this package with no precedent elsewhere in this codebase - every other
// backend's equivalent (xray's HandlerService, sing-box's v2ray_api) is a
// typed gRPC API; OpenVPN's management interface is a bare line-oriented text
// protocol multiplexing three kinds of traffic on one connection:
//
// 1. synchronous command/response ("status 2" -> multi-line reply ending in
// a line that is just "END", or a single "SUCCESS: ..."/"ERROR: ..."
// line);
// 2. asynchronous, unprompted "real-time" notifications, always prefixed
// with ">" (">CLIENT:CONNECT,...", ">BYTECOUNT_CLI:...", etc.) that can
// arrive interleaved with a command's response at any time; and
// 3. commands we issue in reaction to a real-time notification
// ("client-auth"/"client-deny" in response to ">CLIENT:CONNECT") that we
// must NOT wait for a reply to, since the only goroutine that could ever
// read that reply is the one currently blocked sending the command - see
// writeLine vs sendCommand below.
//
// A single background goroutine (readLoop/consume) is the sole reader of the
// connection for its whole lifetime; it reconnects (with backoff, up to a
// bounded number of attempts) if the connection drops before Close is
// called, so a transient management-socket hiccup doesn't require the whole
// openvpn process to be restarted (process.go handles the process actually
// dying separately, by tearing this client down and building a fresh one on
// the next Start - see instanceProcess.Restart).
type ManagementClient struct {
tag string
socketPath string
Expand Down
23 changes: 0 additions & 23 deletions backend/openvpn/openvpn.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,3 @@
// Package openvpn implements backend.Backend on top of N OpenVPN server
// subprocesses ("instances", see config.go), one per configured
// tag/proto/port combination - this backend's analogue of a sing-box/xray
// "inbound". See process.go's instanceProcess for the single-subprocess
// lifecycle (mirrors backend/singbox/core.go's Core, generalized to N-of
// instead of one) and management.go for the single biggest structural
// difference from every other backend in this repo: user membership is
// authenticated live over each instance's management-interface Unix socket
// against an in-memory map, instead of being baked into a config file - see
// user.go's doc comment for why this means SyncUser/SyncUsers/UpdateUsers/
// UpdateUsersAndRestart never need to restart a subprocess here, unlike
// sing-box where every one of them currently does.
//
// PKI (CA cert, server cert, server key, tls-crypt key) is generated by the
// panel and arrives pre-rendered as PEM text in Backend.config's "pki" object
// (see config.go's Config.PKI) - this package only ever consumes it as opaque
// text to inline into a rendered server config (render.go); it never
// generates or touches key material itself.
package openvpn

import (
Expand Down Expand Up @@ -278,11 +260,6 @@ func (b *Backend) Shutdown() {
log.Println("openvpn shutdown complete")
}

// superviseInstances periodically restarts any instance that isn't running
// (e.g. after a crash), with per-instance exponential backoff so a
// persistently broken instance doesn't get restart-stormed - mirrors the
// spirit of sing-box's checkHealth (backend/singbox/jobs.go), adapted for N
// independently-supervised instances instead of one.
func (b *Backend) superviseInstances(ctx context.Context) {
const (
checkInterval = 3 * time.Second
Expand Down
17 changes: 0 additions & 17 deletions backend/openvpn/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,6 @@ import (
"github.com/pasarguard/node/pkg/stats"
)

// instanceProcess owns the full lifecycle of exactly one OpenVPN server
// subprocess: config rendering, spawn, management-socket client, NAT rule,
// log capture, crash/restart bookkeeping, and graceful stop. It is the
// per-instance analogue of backend/singbox/core.go's Core, generalized to run
// N of them concurrently - one per configured instance (see Backend in
// openvpn.go).
type instanceProcess struct {
tag string
inst *InstanceConfig
Expand Down Expand Up @@ -100,10 +94,6 @@ func (p *instanceProcess) writeConfigFile() error {
if err := os.MkdirAll(p.configDir, 0o700); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
// 0600: unlike sing-box's generated config (backend/singbox/core.go's
// writeConfigFile, 0644), this file embeds the server's PEM-encoded
// private key inline (see render.go) and must not be world/group
// readable.
return os.WriteFile(p.configFilePath(), []byte(text), 0o600)
}

Expand Down Expand Up @@ -343,12 +333,6 @@ func (p *instanceProcess) handleProcessExit(cmd *exec.Cmd, err error) {
p.recordLog(message)
}

// Stop gracefully stops the process: SIGTERM (OpenVPN's clean-shutdown
// signal - it notifies connected clients and exits, unlike sing-box's Stop()
// in backend/singbox/core.go, which calls Process.Kill() (SIGKILL) directly;
// worth the extra step here since a hard-killed openvpn server leaves
// clients without a clean disconnect signal), wait with a timeout, then
// escalate to killProcessTree's SIGTERM+SIGKILL+process-group fallback.
func (p *instanceProcess) Stop() {
p.stop(false)
}
Expand Down Expand Up @@ -469,7 +453,6 @@ func (p *instanceProcess) Restart() error {
// cleanupOrphanedProcesses finds and kills openvpn processes for this
// specific instance (matched by executable path + --config path, see
// process_unix.go) that are zombies or parented by this node process.
// Mirrors backend/singbox/core.go's Core.cleanupOrphanedProcesses.
func (p *instanceProcess) cleanupOrphanedProcesses() error {
processes, err := findOpenVPNProcesses(p.executablePath, p.configFilePath())
if err != nil {
Expand Down
16 changes: 0 additions & 16 deletions backend/openvpn/process_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,6 @@ type ProcessInfo struct {
IsZombie bool
}

// findOpenVPNProcesses finds running openvpn processes matching
// executablePath whose command line references configPath as their
// "--config" argument.
//
// Unlike backend/singbox's findSingBoxProcesses (which only ever has to find
// at most one sing-box process for the whole backend), this backend runs one
// openvpn process per configured instance, so matching by executable path
// alone would risk attributing (and potentially killing) a sibling
// instance's healthy process during cleanup. Matching the config path out of
// /proc/<pid>/cmdline disambiguates between instances.
func findOpenVPNProcesses(executablePath, configPath string) ([]ProcessInfo, error) {
absExe, err := filepath.Abs(executablePath)
if err != nil {
Expand Down Expand Up @@ -146,12 +136,6 @@ func findOpenVPNProcessesFromProc(absExe, absConfig string) ([]ProcessInfo, erro
return processes, nil
}

// killProcessTree, getProcessGroupID, verifyProcessDead, isProcessRunning,
// and pathsMatch mirror backend/singbox/process_unix.go (generic
// process-management helpers with no openvpn-specific logic - this repo does
// not share such helpers between backend packages, see log.go's doc
// comment).

func killProcessTree(pid int) error {
proc, err := os.FindProcess(pid)
if err != nil {
Expand Down
5 changes: 0 additions & 5 deletions backend/openvpn/smoke_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,6 @@ import (
"github.com/pasarguard/node/config"
)

// discoverOpenVPNBinary looks for a real openvpn binary to run the live
// smoke test against. It skips the test rather than failing when none is
// found, mirroring backend/singbox/smoke_test.go's discoverSingBoxBinary -
// this needs a real subprocess, a real tun device, and root, and has no
// business running in an ordinary CI environment.
func discoverOpenVPNBinary(t *testing.T) string {
t.Helper()

Expand Down
Loading
Loading