Files
ShadowsocksX-NG/ShadowsocksX-NG2/Domain/EndpointHealthProbe.swift
T
Qiu Yuzhou 6bfd3c0d35 feat(ng2): proxy runtime LaunchAgent, wrapper and sslocal lifecycle (#27)
GUI → LaunchAgent → wrapper → sslocal full chain (spec #21 D2/D5):

- ShadowsocksX-NG2Agent: Swift BundleProgram tool target embedded at
  Contents/MacOS, supervised by launchd via SMAppService agent plist
  (Contents/Library/LaunchAgents, bundle-relative ProgramArguments,
  KeepAlive={SuccessfulExit:false}). Wrapper reads the cross-process
  contract v2/sslocal-active.json, spawns sslocal -c <absolute path>
  and supervises it: SIGTERM chain stop, SIGUSR1 forward for
  server-only changes vs graceful restart on listen fingerprint
  changes, non-zero exit on unexpected child loss for KeepAlive
  replay, invalid/missing contract → clean exit with plain unlink.
- Runtime file protocol: RuntimeFileStore reuses AtomicFileWriter
  (0700 dir self-heal, 0600 temp at creation, atomic replace);
  explicit-stop cleanup unlinks contract, agent pid file and stale
  temporaries. Shared read-side validation via
  SslocalRuntimeDocument.decodeValidated so GUI and wrapper cannot
  drift. Wrapper pid file bridges SMAppService's missing pid.
- GUI: ProxyRuntimeController consumes ActivationStateMachine effects
  through pure ProxyRuntimePlan decision table (ordered actions,
  idempotent skip of identical contract); proxy toggle and launch
  failure presentation (naming endpoint:port) in the status menu;
  launch resync reconciles agent registration, wrapper liveness and
  on-disk contract; catalog commits re-expand immediately.
- Log sanitization baseline: closed RuntimeLogEvent enum plus Redactor,
  wrapper/sslocal output converged to a 0600 agent.log with RUST_LOG
  defaulting to warn.

Tests (126 total, all green): stub-sslocal driven wrapper lifecycle
(start/stop order, SIGTERM chain, crash replay, cleanup, reload
protocol), real sslocal smoke (SOCKS port binding + full SOCKS5
handshake), plan decision table, controller flows with fakes,
runtime file permissions/atomic replace, endpoint probe, redaction.

Manual release-gate items (real launchd/SMAppService): agent
registration approval flow, GUI-quit persistence, bootout behaviors.

Closes #27
2026-09-20 20:26:54 +08:00

61 lines
2.4 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Darwin
import Foundation
/// 本地端点健康探测(spec #21 D2/D8):进程存在不等于代理可用——激活后以
/// TCP 连接确认 sslocal 实际完成监听绑定。探测只做客户端 connect,不建立
/// 带复用选项的监听 socket(Legacy 的 reuse-port 残留假成功在此构造上不可
/// 复现);失败详情供「启动失败」点名端点与端口(D8)。
enum EndpointHealthProbe {
enum Outcome: Equatable {
case reachable
/// 立即失败(连接被拒、地址不可达等),携带系统层原因。
case refused(detail: String)
/// 超时内未完成连接。
case timedOut
}
static func probe(host: String, port: Int, timeout: TimeInterval) -> Outcome {
var hints = addrinfo()
hints.ai_family = AF_UNSPEC
hints.ai_socktype = SOCK_STREAM
hints.ai_protocol = IPPROTO_TCP
var info: UnsafeMutablePointer<addrinfo>?
guard getaddrinfo(host, String(port), &hints, &info) == 0, let first = info else {
return .refused(detail: "监听地址无法解析")
}
defer { freeaddrinfo(info) }
var lastFailure: Outcome?
for candidate in sequence(first: first, next: { $0.pointee.ai_next }) {
let descriptor = socket(
candidate.pointee.ai_family, candidate.pointee.ai_socktype, candidate.pointee.ai_protocol)
guard descriptor >= 0 else { continue }
defer { close(descriptor) }
let previousFlags = fcntl(descriptor, F_GETFL, 0)
_ = fcntl(descriptor, F_SETFL, previousFlags | O_NONBLOCK)
if connect(descriptor, candidate.pointee.ai_addr, candidate.pointee.ai_addrlen) == 0 {
return .reachable
}
guard errno == EINPROGRESS else {
lastFailure = .refused(detail: String(cString: strerror(errno)))
continue
}
var pollDescriptor = pollfd(fd: descriptor, events: Int16(POLLOUT), revents: 0)
let pollResult = poll(&pollDescriptor, 1, Int32(timeout * 1000))
guard pollResult > 0 else {
lastFailure = lastFailure ?? .timedOut
continue
}
var socketError: Int32 = 0
var length = socklen_t(MemoryLayout<Int32>.size)
getsockopt(descriptor, SOL_SOCKET, SO_ERROR, &socketError, &length)
if socketError == 0 {
return .reachable
}
lastFailure = .refused(detail: String(cString: strerror(socketError)))
}
return lastFailure ?? .refused(detail: "无法建立连接")
}
}