diff --git a/intercept/target_dial.go b/intercept/target_dial.go index 2ed1d07..62007db 100644 --- a/intercept/target_dial.go +++ b/intercept/target_dial.go @@ -3,12 +3,15 @@ package intercept import ( "context" "encoding/json" + "errors" "fmt" "net" "net/netip" "strconv" "strings" "time" + + "github.com/Autumn-27/artex/db" ) // The HTTP clients the platform owns (WebFetch and the custom http tool) @@ -178,3 +181,59 @@ func (e *dialError) Error() string { } return msg + " Do not fetch the target with another tool or by its address." } + +// IsTargetBlocked reports whether err came from PinnedDialer / DialSOCKS5 +// refusing a target before dialing (rule block, unpinned target, or unavailable +// target gate), returning its platform control code. +func IsTargetBlocked(err error) (string, bool) { + var de *dialError + if errors.As(err, &de) { + return de.code, true + } + return "", false +} + +// DialSOCKS5 enforces the platform's target gate before dialing a SOCKS5 +// CONNECT destination, reusing the same policy functions as PinnedDialer: +// - When ctx carries an enabled TargetScope, delegates directly to dialTarget +// (asset block rules, exemptions, fresh DNS resolution, and pin checks). +// - Otherwise enforces global asset block rules (domain, IP, and CIDR, before +// and after fresh DNS resolution) and dials only the resolved addresses that +// passed those rules. +func (i *Interceptor) DialSOCKS5(ctx context.Context, network, addr string) (net.Conn, error) { + if i == nil { + return baseDial(ctx, network, addr) + } + if scope, ok := TargetScopeFromContext(ctx); ok && scope.Enabled != nil && scope.Enabled() { + return i.dialTarget(ctx, scope, "socks5", network, addr) + } + t, err := addrTarget(network, addr) + if err != nil { + return nil, &dialError{code: TargetGateUnavailable, target: addr, reason: "the address of the connection could not be read (" + err.Error() + ")"} + } + if i.targets == nil { + return i.baseDialer()(ctx, network, addr) + } + rules, err := i.targets.BlockRules(db.TargetScopeRef{}) + if err != nil { + return nil, &dialError{code: TargetGateUnavailable, target: t.String(), reason: "the asset rules could not be read: " + err.Error()} + } + ct := &checkedTarget{Target: t} + if t.Kind != TargetDomain { + ct.ips, ct.resolver, ct.resolvedAt = []string{t.Host}, literalResolver, time.Now().UTC() + } + if rule, hit := blockRule(rules, ct); hit { + return nil, &dialError{code: TargetRuleBlocked, target: t.String(), reason: fmt.Sprintf("%s is blocked by an asset rule. %s", t, rule.Reason())} + } + if t.Kind == TargetDomain { + c := &targetCheck{i: i, ctx: ctx, tool: "socks5", fresh: true} + c.resolve(ct, true) + if ct.err != nil { + return nil, ct.err + } + if rule, hit := blockRule(rules, ct); hit { + return nil, &dialError{code: TargetRuleBlocked, target: t.String(), reason: fmt.Sprintf("%s is blocked by an asset rule. %s", t, rule.Reason())} + } + } + return i.dialAddrs(ctx, network, ct.ips, t.Port) +} diff --git a/server/manager.go b/server/manager.go index 9e2a558..de1a294 100644 --- a/server/manager.go +++ b/server/manager.go @@ -463,6 +463,14 @@ func NewManager(dir, proxyAddr string) (*Manager, error) { if tr != nil { m.traffic = tr m.reloadRewriteRules() // in place before the proxy accepts a connection + if scfg, ok := traffic.SOCKS5ConfigFromEnv(); ok { + scfg.DialContext = m.interceptor.DialSOCKS5 + if bound, serr := tr.StartSOCKS5(scfg); serr != nil { + log.Printf("[traffic/socks5] disabled: %v", serr) + } else { + log.Printf("[traffic/socks5] opt-in SOCKS5 CONNECT listener on %s", bound) + } + } go func() { log.Printf("[traffic] recording proxy on %s (set HTTP_PROXY=%s + trust _ca CA)", proxyAddr, tr.ProxyAddr()) if err := tr.Start(); err != nil { diff --git a/traffic/socks5.go b/traffic/socks5.go new file mode 100644 index 0000000..e7eab68 --- /dev/null +++ b/traffic/socks5.go @@ -0,0 +1,688 @@ +package traffic + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "net" + "net/url" + "os" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "github.com/Autumn-27/artex/egress" + "github.com/Autumn-27/artex/intercept" +) + +// Opt-in environment flags for the SOCKS5 inbound listener (P4.1a). +// Off by default: when neither is set, no SOCKS5 listener is started and the +// HTTP recording proxy is unchanged. +const ( + // SOCKS5EnabledEnv turns on the SOCKS5 CONNECT listener on DefaultSOCKS5Addr + // (loopback) when set to 1/true/on/yes. + SOCKS5EnabledEnv = "ARTEX_SOCKS5_ENABLED" + // SOCKS5AddrEnv optionally overrides the bind address (default 127.0.0.1:1080). + // Setting a non-empty address also enables the listener unless + // ARTEX_SOCKS5_ENABLED is explicitly false/0/off/no. + SOCKS5AddrEnv = "ARTEX_SOCKS5_ADDR" + + DefaultSOCKS5Addr = "127.0.0.1:1080" + DefaultSOCKS5MaxConcurrent = 64 + DefaultSOCKS5MaxBytesPerDir = 4 * 1024 * 1024 + DefaultSOCKS5PreviewBytes = blobPreview + DefaultSOCKS5IdleTimeout = 2 * time.Minute + DefaultSOCKS5HandshakeTimeout = 10 * time.Second + DefaultSOCKS5DialTimeout = 30 * time.Second + DefaultSOCKS5PaceTimeout = paceWaitMax +) + +// RFC 1928 / RFC 1929 protocol constants. +const ( + socks5Version = 0x05 + socks5AuthNone = 0x00 + socks5AuthUserPass = 0x02 + socks5AuthNoAccept = 0xFF + socks5UserPassVer = 0x01 + + socks5CmdConnect = 0x01 + socks5CmdBind = 0x02 + socks5CmdUDPAssociate = 0x03 + + socks5AtypIPv4 = 0x01 + socks5AtypDomain = 0x03 + socks5AtypIPv6 = 0x04 + + socks5RepSuccess = 0x00 + socks5RepGeneralFailure = 0x01 + socks5RepNotAllowed = 0x02 + socks5RepNetworkUnreachable = 0x03 + socks5RepHostUnreachable = 0x04 + socks5RepConnectionRefused = 0x05 + socks5RepTTLExpired = 0x06 + socks5RepCmdNotSupported = 0x07 + socks5RepAtypNotSupported = 0x08 +) + +// SOCKS5Config configures the opt-in RFC 1928 SOCKS5 CONNECT listener. +type SOCKS5Config struct { + // Addr is the TCP bind address (default DefaultSOCKS5Addr, loopback-bound). + Addr string + // MaxConcurrent bounds simultaneous active SOCKS5 streams (default 64). + MaxConcurrent int + // MaxBytesPerDir caps bytes captured for storage per direction (default 4 MiB). + // Relay continues counting total bytes; exceeding the cap sets Truncated=true. + MaxBytesPerDir int64 + // PreviewBytes caps the inline preview per direction (default 8 KiB). + PreviewBytes int + // IdleTimeout closes a relayed stream after no bytes move in either direction. + IdleTimeout time.Duration + // HandshakeTimeout bounds the RFC 1928 greeting, auth, and CONNECT request. + HandshakeTimeout time.Duration + // DialTimeout bounds the outbound TCP dial. + DialTimeout time.Duration + // PaceTimeout bounds waiting on the egress governor before refusing the dial. + PaceTimeout time.Duration + // DialContext opens the outbound TCP connection after policy checks. + // Defaults to intercept.PinnedDialer("socks5", false). + DialContext func(ctx context.Context, network, addr string) (net.Conn, error) + // BaseContext, when non-nil, derives the context passed to the egress + // governor and DialContext (e.g. carrying an intercept.TargetScope). + BaseContext func() context.Context + // OnRecord, when non-nil, receives each completed raw TCP capture. + // When nil and attached to a Traffic store, the store's raw-TCP recorder runs. + OnRecord func(RawTCPCapture) +} + +// RawTCPCapture is the completed metadata and bounded directional payloads of +// one relayed SOCKS5 TCP connection. +type RawTCPCapture struct { + Host string + Port int + StartedAt time.Time + EndedAt time.Time + C2SBytes int64 + S2CBytes int64 + C2SData []byte + S2CData []byte + Truncated bool + Paced bool +} + +// SOCKS5ConfigFromEnv parses ARTEX_SOCKS5_ENABLED and ARTEX_SOCKS5_ADDR. +// Returns (cfg, false) when disabled (the default). +func SOCKS5ConfigFromEnv() (SOCKS5Config, bool) { + rawEnabled := strings.ToLower(strings.TrimSpace(os.Getenv(SOCKS5EnabledEnv))) + rawAddr := strings.TrimSpace(os.Getenv(SOCKS5AddrEnv)) + + switch rawEnabled { + case "0", "false", "off", "no": + return SOCKS5Config{}, false + case "1", "true", "on", "yes": + addr := rawAddr + if addr == "" { + addr = DefaultSOCKS5Addr + } + return SOCKS5Config{Addr: addr}, true + case "": + if rawAddr == "" { + return SOCKS5Config{}, false + } + return SOCKS5Config{Addr: rawAddr}, true + default: + log.Printf("[traffic] %s=%q is not a boolean; leaving SOCKS5 disabled", SOCKS5EnabledEnv, rawEnabled) + return SOCKS5Config{}, false + } +} + +func (c SOCKS5Config) withDefaults() SOCKS5Config { + if strings.TrimSpace(c.Addr) == "" { + c.Addr = DefaultSOCKS5Addr + } + if c.MaxConcurrent <= 0 { + c.MaxConcurrent = DefaultSOCKS5MaxConcurrent + } + if c.MaxBytesPerDir <= 0 { + c.MaxBytesPerDir = DefaultSOCKS5MaxBytesPerDir + } + if c.PreviewBytes <= 0 { + c.PreviewBytes = DefaultSOCKS5PreviewBytes + } + if c.IdleTimeout <= 0 { + c.IdleTimeout = DefaultSOCKS5IdleTimeout + } + if c.HandshakeTimeout <= 0 { + c.HandshakeTimeout = DefaultSOCKS5HandshakeTimeout + } + if c.DialTimeout <= 0 { + c.DialTimeout = DefaultSOCKS5DialTimeout + } + if c.PaceTimeout <= 0 { + c.PaceTimeout = DefaultSOCKS5PaceTimeout + } + if c.DialContext == nil { + c.DialContext = intercept.PinnedDialer("socks5", false) + } + return c +} + +type socks5Server struct { + t *Traffic + cfg SOCKS5Config + ln net.Listener + sem chan struct{} + stop chan struct{} + once sync.Once + wg sync.WaitGroup + + mu sync.Mutex + active map[net.Conn]struct{} +} + +// StartSOCKS5 binds and starts the opt-in RFC 1928 SOCKS5 CONNECT listener on t. +// Returns the actual bound address (useful when cfg.Addr uses port 0). +func (t *Traffic) StartSOCKS5(cfg SOCKS5Config) (string, error) { + cfg = cfg.withDefaults() + ln, err := net.Listen("tcp", cfg.Addr) + if err != nil { + return "", fmt.Errorf("socks5 listen %s: %w", cfg.Addr, err) + } + srv := &socks5Server{ + t: t, + cfg: cfg, + ln: ln, + sem: make(chan struct{}, cfg.MaxConcurrent), + stop: make(chan struct{}), + active: map[net.Conn]struct{}{}, + } + t.socksMu.Lock() + if t.socks != nil { + t.socksMu.Unlock() + _ = ln.Close() + return "", errors.New("socks5 listener already running") + } + t.socks = srv + t.socksMu.Unlock() + + srv.wg.Add(1) + go srv.serve() + return ln.Addr().String(), nil +} + +// SOCKS5Addr returns the bound SOCKS5 listener address, or "" when disabled. +func (t *Traffic) SOCKS5Addr() string { + t.socksMu.Lock() + defer t.socksMu.Unlock() + if t.socks == nil || t.socks.ln == nil { + return "" + } + return t.socks.ln.Addr().String() +} + +func (s *socks5Server) Close() error { + var closeErr error + s.once.Do(func() { + close(s.stop) + closeErr = s.ln.Close() + s.mu.Lock() + for c := range s.active { + _ = c.Close() + } + s.mu.Unlock() + }) + s.wg.Wait() + return closeErr +} + +func (s *socks5Server) stopping() bool { + select { + case <-s.stop: + return true + default: + return false + } +} + +func (s *socks5Server) trackConn(c net.Conn) bool { + s.mu.Lock() + defer s.mu.Unlock() + if s.stopping() { + return false + } + s.active[c] = struct{}{} + return true +} + +func (s *socks5Server) untrackConn(c net.Conn) { + s.mu.Lock() + delete(s.active, c) + s.mu.Unlock() +} + +func (s *socks5Server) serve() { + defer s.wg.Done() + for { + conn, err := s.ln.Accept() + if err != nil { + if s.stopping() || errors.Is(err, net.ErrClosed) { + return + } + var ne net.Error + if errors.As(err, &ne) && ne.Timeout() { + continue + } + log.Printf("[traffic/socks5] accept error: %v", err) + return + } + if !s.trackConn(conn) { + _ = conn.Close() + return + } + s.wg.Add(1) + go func(c net.Conn) { + defer s.wg.Done() + defer s.untrackConn(c) + defer c.Close() + s.handleConn(c) + }(conn) + } +} + +func (s *socks5Server) handleConn(client net.Conn) { + // 1. Handshake (greeting + optional RFC 1929 auth + CONNECT request) under HandshakeTimeout. + _ = client.SetDeadline(time.Now().Add(s.cfg.HandshakeTimeout)) + + paced, ok := s.negotiateAuth(client) + if !ok { + return + } + + host, port, rep := readSOCKS5Request(client) + if rep != socks5RepSuccess { + _ = writeSOCKS5Reply(client, rep, nil) + return + } + + // 2. Enforce max concurrent streams before touching policy or dialing. + select { + case s.sem <- struct{}{}: + defer func() { <-s.sem }() + default: + _ = writeSOCKS5Reply(client, socks5RepGeneralFailure, nil) + return + } + + // 3. Apply the egress governor and target gate before dialing. + targetAddr := net.JoinHostPort(host, strconv.Itoa(port)) + upstream, rep := s.dialTarget(host, port, targetAddr) + if rep != socks5RepSuccess { + _ = writeSOCKS5Reply(client, rep, nil) + return + } + if !s.trackConn(upstream) { + _ = upstream.Close() + _ = writeSOCKS5Reply(client, socks5RepGeneralFailure, nil) + return + } + defer s.untrackConn(upstream) + defer upstream.Close() + + // Clear handshake deadline before replying and starting the relay. + _ = client.SetDeadline(time.Time{}) + if err := writeSOCKS5Reply(client, socks5RepSuccess, upstream.LocalAddr()); err != nil { + return + } + + // 4. Bidirectional half-close-aware relay with idle timeout and bounded capture. + startedAt := time.Now().UTC() + c2sCap := &limitedCapture{max: s.cfg.MaxBytesPerDir} + s2cCap := &limitedCapture{max: s.cfg.MaxBytesPerDir} + + var relayWG sync.WaitGroup + relayWG.Add(2) + go func() { + defer relayWG.Done() + relayHalf(upstream, client, c2sCap, s.cfg.IdleTimeout) + closeWrite(upstream) + }() + go func() { + defer relayWG.Done() + relayHalf(client, upstream, s2cCap, s.cfg.IdleTimeout) + closeWrite(client) + }() + relayWG.Wait() + endedAt := time.Now().UTC() + + rec := RawTCPCapture{ + Host: host, + Port: port, + StartedAt: startedAt, + EndedAt: endedAt, + C2SBytes: c2sCap.total, + S2CBytes: s2cCap.total, + C2SData: c2sCap.buf, + S2CData: s2cCap.buf, + Truncated: c2sCap.truncated || s2cCap.truncated, + Paced: paced, + } + s.recordCapture(rec) +} + +func (s *socks5Server) recordCapture(rec RawTCPCapture) { + if s.cfg.OnRecord != nil { + s.cfg.OnRecord(rec) + } +} + +func (s *socks5Server) negotiateAuth(conn net.Conn) (paced bool, ok bool) { + var hdr [2]byte + if _, err := io.ReadFull(conn, hdr[:]); err != nil { + return false, false + } + if hdr[0] != socks5Version || hdr[1] == 0 { + return false, false + } + methods := make([]byte, int(hdr[1])) + if _, err := io.ReadFull(conn, methods); err != nil { + return false, false + } + + var hasNone, hasUserPass bool + for _, m := range methods { + switch m { + case socks5AuthNone: + hasNone = true + case socks5AuthUserPass: + hasUserPass = true + } + } + + // Prefer username/password when offered so clients carrying the pace marker + // (egress.PaceUser) can pass it through without requiring real credentials. + // Accept no-auth for loopback clients. + if hasUserPass { + if _, err := conn.Write([]byte{socks5Version, socks5AuthUserPass}); err != nil { + return false, false + } + return readSOCKS5UserPass(conn) + } + if hasNone && isLoopbackRemote(conn.RemoteAddr()) { + if _, err := conn.Write([]byte{socks5Version, socks5AuthNone}); err != nil { + return false, false + } + return false, true + } + _, _ = conn.Write([]byte{socks5Version, socks5AuthNoAccept}) + return false, false +} + +// readSOCKS5UserPass parses an RFC 1929 username/password subnegotiation. +// Credentials are never required (any username/password succeeds); a username +// equal to egress.PaceUser marks the connection as paced. +func readSOCKS5UserPass(conn net.Conn) (paced bool, ok bool) { + var head [2]byte + if _, err := io.ReadFull(conn, head[:]); err != nil { + return false, false + } + if head[0] != socks5UserPassVer { + _, _ = conn.Write([]byte{socks5UserPassVer, 0x01}) + return false, false + } + uname := make([]byte, int(head[1])) + if _, err := io.ReadFull(conn, uname); err != nil { + return false, false + } + var plen [1]byte + if _, err := io.ReadFull(conn, plen[:]); err != nil { + return false, false + } + if plen[0] > 0 { + pass := make([]byte, int(plen[0])) + if _, err := io.ReadFull(conn, pass); err != nil { + return false, false + } + } + if _, err := conn.Write([]byte{socks5UserPassVer, 0x00}); err != nil { + return false, false + } + return string(uname) == egress.PaceUser, true +} + +func readSOCKS5Request(conn net.Conn) (host string, port int, rep byte) { + var hdr [4]byte + if _, err := io.ReadFull(conn, hdr[:]); err != nil { + return "", 0, socks5RepGeneralFailure + } + if hdr[0] != socks5Version || hdr[2] != 0x00 { + return "", 0, socks5RepGeneralFailure + } + cmd := hdr[1] + atyp := hdr[3] + + // Read the address + port before rejecting unsupported commands so the stream + // stays cleanly framed if the peer reads our reply. + switch atyp { + case socks5AtypIPv4: + var ip [4]byte + if _, err := io.ReadFull(conn, ip[:]); err != nil { + return "", 0, socks5RepGeneralFailure + } + host = net.IP(ip[:]).String() + case socks5AtypDomain: + var l [1]byte + if _, err := io.ReadFull(conn, l[:]); err != nil { + return "", 0, socks5RepGeneralFailure + } + if l[0] == 0 { + return "", 0, socks5RepGeneralFailure + } + dom := make([]byte, int(l[0])) + if _, err := io.ReadFull(conn, dom); err != nil { + return "", 0, socks5RepGeneralFailure + } + host = strings.TrimSpace(string(dom)) + if host == "" { + return "", 0, socks5RepGeneralFailure + } + case socks5AtypIPv6: + var ip [16]byte + if _, err := io.ReadFull(conn, ip[:]); err != nil { + return "", 0, socks5RepGeneralFailure + } + host = net.IP(ip[:]).String() + default: + return "", 0, socks5RepAtypNotSupported + } + + var pbuf [2]byte + if _, err := io.ReadFull(conn, pbuf[:]); err != nil { + return "", 0, socks5RepGeneralFailure + } + port = int(binary.BigEndian.Uint16(pbuf[:])) + + if cmd != socks5CmdConnect { + return "", 0, socks5RepCmdNotSupported + } + if port <= 0 || port > 65535 { + return "", 0, socks5RepGeneralFailure + } + return host, port, socks5RepSuccess +} + +func writeSOCKS5Reply(conn net.Conn, rep byte, bindAddr net.Addr) error { + var bndIP net.IP + var bndPort int + if tcpAddr, ok := bindAddr.(*net.TCPAddr); ok && tcpAddr != nil { + bndIP = tcpAddr.IP + bndPort = tcpAddr.Port + } + var out []byte + if ip4 := bndIP.To4(); ip4 != nil { + out = make([]byte, 0, 10) + out = append(out, socks5Version, rep, 0x00, socks5AtypIPv4) + out = append(out, ip4...) + } else if ip16 := bndIP.To16(); ip16 != nil { + out = make([]byte, 0, 22) + out = append(out, socks5Version, rep, 0x00, socks5AtypIPv6) + out = append(out, ip16...) + } else { + out = make([]byte, 0, 10) + out = append(out, socks5Version, rep, 0x00, socks5AtypIPv4, 0, 0, 0, 0) + } + var p [2]byte + binary.BigEndian.PutUint16(p[:], uint16(bndPort)) + out = append(out, p[:]...) + _, err := conn.Write(out) + return err +} + +func (s *socks5Server) dialTarget(host string, port int, targetAddr string) (net.Conn, byte) { + baseCtx := context.Background() + if s.cfg.BaseContext != nil { + if ctx := s.cfg.BaseContext(); ctx != nil { + baseCtx = ctx + } + } + stopCtx, stopCancel := context.WithCancel(baseCtx) + defer stopCancel() + go func() { + select { + case <-s.stop: + stopCancel() + case <-stopCtx.Done(): + } + }() + + // Run through the same egress governor (egress.Do) and target gate dialer + // (intercept.PinnedDialer / Interceptor.DialSOCKS5) the HTTP path uses. + govCtx, govCancel := context.WithTimeout(stopCtx, s.cfg.PaceTimeout) + defer govCancel() + + targetURL := &url.URL{Scheme: "tcp", Host: targetAddr} + dialCalled := false + conn, err := egress.Do(egress.Current(), govCtx, targetURL, func() (net.Conn, error) { + dialCalled = true + dialCtx, dialCancel := context.WithTimeout(stopCtx, s.cfg.DialTimeout) + defer dialCancel() + return s.cfg.DialContext(dialCtx, "tcp", targetAddr) + }) + if err != nil { + if !dialCalled { + // Refused by the egress governor before dialing. + return nil, socks5RepNotAllowed + } + return nil, mapDialErrorToSOCKS5Reply(err) + } + return conn, socks5RepSuccess +} + +func mapDialErrorToSOCKS5Reply(err error) byte { + if _, blocked := intercept.IsTargetBlocked(err); blocked { + return socks5RepNotAllowed + } + var dnsErr *net.DNSError + if errors.As(err, &dnsErr) { + return socks5RepHostUnreachable + } + if errors.Is(err, syscall.ECONNREFUSED) { + return socks5RepConnectionRefused + } + if errors.Is(err, syscall.ENETUNREACH) { + return socks5RepNetworkUnreachable + } + if errors.Is(err, syscall.EHOSTUNREACH) { + return socks5RepHostUnreachable + } + if errors.Is(err, context.DeadlineExceeded) { + return socks5RepTTLExpired + } + low := strings.ToLower(err.Error()) + switch { + case strings.Contains(low, "connection refused"): + return socks5RepConnectionRefused + case strings.Contains(low, "network is unreachable"): + return socks5RepNetworkUnreachable + case strings.Contains(low, "no route to host"), strings.Contains(low, "no such host"), strings.Contains(low, "host is unreachable"): + return socks5RepHostUnreachable + } + return socks5RepGeneralFailure +} + +func isLoopbackRemote(addr net.Addr) bool { + if addr == nil { + return false + } + switch a := addr.(type) { + case *net.TCPAddr: + return a.IP != nil && a.IP.IsLoopback() + default: + h, _, err := net.SplitHostPort(addr.String()) + if err != nil { + h = addr.String() + } + ip := net.ParseIP(strings.Trim(h, "[]")) + return ip != nil && ip.IsLoopback() + } +} + +type limitedCapture struct { + max int64 + total int64 + buf []byte + truncated bool +} + +func (c *limitedCapture) record(p []byte) { + if len(p) == 0 { + return + } + c.total += int64(len(p)) + rem := c.max - int64(len(c.buf)) + if rem <= 0 { + c.truncated = true + return + } + if int64(len(p)) > rem { + c.buf = append(c.buf, p[:rem]...) + c.truncated = true + return + } + c.buf = append(c.buf, p...) +} + +func relayHalf(dst, src net.Conn, cap *limitedCapture, idle time.Duration) { + buf := make([]byte, 32*1024) + for { + if idle > 0 { + _ = src.SetReadDeadline(time.Now().Add(idle)) + } + n, rerr := src.Read(buf) + if n > 0 { + chunk := buf[:n] + cap.record(chunk) + if idle > 0 { + _ = dst.SetWriteDeadline(time.Now().Add(idle)) + } + if _, werr := dst.Write(chunk); werr != nil { + return + } + } + if rerr != nil { + return + } + } +} + +func closeWrite(c net.Conn) { + type halfCloser interface { + CloseWrite() error + } + if hc, ok := c.(halfCloser); ok { + _ = hc.CloseWrite() + } +} diff --git a/traffic/traffic.go b/traffic/traffic.go index 8444b83..f25ced4 100644 --- a/traffic/traffic.go +++ b/traffic/traffic.go @@ -232,6 +232,9 @@ type Traffic struct { // sweeping tracks the snapshot sweeper, which runs until Close. It is kept // apart from reaping, which only ever holds work that finishes on its own. sweeping sync.WaitGroup + // socks holds the opt-in SOCKS5 CONNECT listener when started via StartSOCKS5. + socksMu sync.Mutex + socks *socks5Server } // Open initializes the traffic tree, blob store and SQLite index under dir. @@ -445,6 +448,13 @@ func (t *Traffic) Close() error { if t.closed != nil { t.closeOnce.Do(func() { close(t.closed) }) } + t.socksMu.Lock() + srv := t.socks + t.socks = nil + t.socksMu.Unlock() + if srv != nil { + _ = srv.Close() + } t.reaping.Wait() t.sweeping.Wait() return t.db.Close()