socks5lb

package module
v0.0.0-...-73e2520 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 7, 2025 License: MIT Imports: 18 Imported by: 0

README

socks5lb - Simple SOCKS5 Proxy Load Balancer

socks5lb

Sometimes SOCKS5 proxies become unreachable due to network fluctuations or routing changes, requiring manual node switching which can be tedious and time-consuming.

This tool solves that problem by acting as a front-end load balancer for SOCKS5 proxies, automatically routing traffic through verified, healthy proxy nodes.

For Linux systems, it also provides transparent proxy capabilities with SOCKS5 protocol conversion, making it easy to integrate with ipset and iptables.

Key Features

  • Load Balancing: Round-robin distribution across SOCKS5 proxies with automatic health checks
  • Transparent Proxy: Linux TPROXY support with SOCKS5 protocol conversion
  • Cross-Platform: Written in Go for easy deployment across platforms (including routers)

Changelog

  • 2025-10-07 Refactored codebase to update copyright information, improve health check mechanisms, and enhance concurrency handling with atomic operations and mutexes. Bump Go version to 1.25 and optimize HTTP server configurations.
  • 2022-07-16 Fixed connection performance issues, added HTTP management interface
  • 2022-07-06 Completed Linux transparent gateway functionality
  • 2022-06-20 Initial release with core features

Building

The recommended way to build is using docker-compose:

docker-compose build

Configuration

Here's a basic configuration example with three SOCKS5 proxies exposed on local port 1080, and transparent proxy on port 8848 for Linux systems:

server:
  http:
    addr: ":8080"
  socks5:
    addr: ":1080"
  tproxy:
    addr: ":8848"
backends:
  - addr: 192.168.100.254:1086
    check_config:
      check_url: https://www.google.com/robots.txt
      initial_alive: true
      timeout: 3
  - addr: 10.1.0.254:1086
    check_config:
      check_url: https://www.google.com/robots.txt
      initial_alive: false
      timeout: 30
  - addr: 172.16.100.254:1086
    check_config:
      check_url: https://www.google.com/robots.txt
      initial_alive: true
      timeout: 3
Environment Variables
  • SELECT_TIME_INTERVAL - Automatic proxy switching interval in seconds (default: 300 seconds / 5 minutes)
  • CHECK_TIME_INTERVAL - Health check polling interval in seconds (default: 60 seconds / 1 minute)
  • DEBUG - Enable debug mode (true/false)

Deployment

Docker Compose

It's recommended to use network_mode: 'host' to avoid network connectivity issues caused by Docker's iptables rules:

version: "3"
services:
  socks5lb:
    image: ghcr.io/mingcheng/socks5lb:latest
    restart: always
    dns:
      - 8.8.8.8
      - 8.8.4.4
    environment:
      TZ: "Asia/Shanghai"
      CHECK_TIME_INTERVAL: 3600
    network_mode: "host"
    privileged: true
    volumes:
      - ./socks5lb.yml:/etc/socks5lb.yml:ro
iptables Configuration

Example iptables rules to redirect traffic through port 8848 (note: the redrock ipset must be configured separately):

iptables -t nat -I PREROUTING -p tcp -m set --match-set redrock dst -j REDIRECT --to-ports 8848
iptables -t nat -I OUTPUT -p tcp -m set --match-set redrock dst -j REDIRECT --to-ports 8848

Web Management API

Version 1.1.0 introduced a simple web management interface for dynamic proxy configuration:

GET /version

Returns current version, build time, and uptime information.

GET /api/all

Lists all configured proxy servers. Add ?healthy=true parameter to show only healthy backends.

PUT /api/add

Adds new proxy backends. The request body should be a JSON array of backend configurations:

[
  {
    "addr": "192.168.1.254:1086",
    "check_config": {
      "check_url": "https://www.taobao.com/robots.txt"
    }
  },
  {
    "addr": "192.168.1.254:1087",
    "check_config": {
      "initial_alive": true
    }
  }
]

Returns the number of backends successfully added. Note: Existing backends must be deleted before re-adding.

Example using curl:

curl -X "PUT" "<your-address>/api/add" \
     -H 'Content-Type: text/plain; charset=utf-8' \
     -d $'[
  {
    "addr": "192.168.1.1:1086",
    "check_config": {
      "check_url": "https://www.taobao.com/robots.txt"
    }
  }
]'
DELETE /api/delete

Removes a specific proxy backend by address using the addr query parameter:

curl -X "DELETE" "http://localhost:8080/api/delete?addr=192.168.1.1:1086"

FAQ

How do I disable health checks for a specific backend?

Leave the check_url parameter empty and set initial_alive to true:

backends:
  - addr: 127.0.0.1:10860
    check_config:
      initial_alive: true
Can I use the tproxy_listen configuration on non-Linux systems?

No, transparent proxy support is Linux-only. Leave the tproxy configuration empty on other platforms.

Are there similar projects?

License

MIT License - see LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	// DefaultDialTimeout is the default timeout for dialing backend connections
	DefaultDialTimeout = 10 * time.Second
	// DefaultKeepAlivePeriod is the interval for TCP keepalive probes
	DefaultKeepAlivePeriod = 30 * time.Second
)
View Source
const AppName = "socks5lb"
View Source
const (
	// BufferSize defines the size of buffers used for copying data between connections
	BufferSize = 32 * 1024 // 32KB buffer for better performance
)
View Source
const (
	// DefaultCheckTimeout is the default timeout for health checks
	DefaultCheckTimeout = 10
)

Variables

View Source
var (
	Version     = "n/a"
	BuildCommit = "n/a"
	BuildDate   = "n/a"

	DebugMode = false
	StartTime time.Time
)

Functions

func GetEnv

func GetEnv(name, def string) string

GetEnv retrieves an environment variable value or returns a default if not set Trims whitespace from the result for cleaner configuration handling

func SecFromEnv

func SecFromEnv(name string, defVal uint64) time.Duration

SecFromEnv retrieves a duration in seconds from an environment variable Falls back to the default value if the variable is not set or invalid

Types

type Backend

type Backend struct {
	Addr        string             `yaml:"addr" json:"addr" binding:"required"`
	UserName    string             `yaml:"username" json:"username"`
	Password    string             `yaml:"password" json:"password"`
	CheckConfig BackendCheckConfig `yaml:"check_config" json:"check_config"`
	// contains filtered or unexported fields
}

func NewBackend

func NewBackend(addr string, config BackendCheckConfig) (backend *Backend)

NewBackend creates a new Backend instance with the specified configuration

func (*Backend) Alive

func (b *Backend) Alive() bool

Alive returns the current health status of the backend Uses atomic operation for thread-safe read

func (*Backend) Check

func (b *Backend) Check() (err error)

Check performs health check on the backend by testing connectivity Returns error if the backend is not reachable or unhealthy

func (*Backend) SetAlive

func (b *Backend) SetAlive(alive bool)

SetAlive atomically sets the backend's health status

func (*Backend) Socks5Conn

func (b *Backend) Socks5Conn(network, addr string, timeout int) (cc net.Conn, err error)

Socks5Conn creates a connection through the SOCKS5 proxy

type BackendCheckConfig

type BackendCheckConfig struct {
	CheckURL     string `yaml:"check_url" json:"check_url"`
	InitialAlive bool   `yaml:"initial_alive" json:"initial_alive"`
	Timeout      uint   `yaml:"timeout" json:"timeout"`
}

type Configure

type Configure struct {
	ServerConfig ServerConfig `yaml:"server"`
	Backends     []Backend    `yaml:"backends"`
}

Configure represents the complete application configuration

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

func NewPool

func NewPool(backends ...[]Backend) *Pool

NewPool instance for a new Pools instance

func (*Pool) Add

func (b *Pool) Add(backend *Backend) (err error)

Add add a backend to the pool

func (*Pool) All

func (b *Pool) All() (backends []*Backend)

All returns all backends in the pool

func (*Pool) AllHealthy

func (b *Pool) AllHealthy() (backends []*Backend)

AllHealthy returns all healthy backends from the pool

func (*Pool) Check

func (b *Pool) Check()

Check performs health checks on all backends in the pool

func (*Pool) Next

func (b *Pool) Next() *Backend

Next returns the next available healthy backend using round-robin algorithm Returns nil if no healthy backend is available

func (*Pool) NextIndex

func (b *Pool) NextIndex() int

NextIndex returns the next index for load balancer round-robin algorithm Uses atomic operations for thread-safe index management

func (*Pool) Remove

func (b *Pool) Remove(addr string) (err error)

Remove remove a backend from the pool

type Server

type Server struct {
	Pool   *Pool
	Config *ServerConfig
	// contains filtered or unexported fields
}

Server represents the main SOCKS5 load balancer server

func NewServer

func NewServer(pool *Pool, config ServerConfig) (*Server, error)

NewServer creates a new Server instance with the given pool and configuration

func (*Server) AddBackend

func (s *Server) AddBackend() error

AddBackend adds a new backend to the server's pool TODO: Implementation needed

func (*Server) Engine

func (s *Server) Engine() *gin.Engine

Engine returns the main http engine for testing purposes

func (*Server) ListenHTTPAdmin

func (s *Server) ListenHTTPAdmin(addr string) (err error)

ListenHTTPAdmin starts the HTTP administration server

func (*Server) ListenSocks5

func (s *Server) ListenSocks5(addr string) (err error)

ListenSocks5 listens on a specific address and handles SOCKS5 connections

func (*Server) ListenTProxy

func (s *Server) ListenTProxy(addr string) (err error)

ListenTProxy is listening the local tcp port on the given address Deprecated: this feature will be disabled in the future

func (*Server) Start

func (s *Server) Start() (err error)

Start initializes and starts all server components - Health check timer for periodic backend monitoring - HTTP admin interface (if configured) - SOCKS5 proxy listener

func (*Server) Stop

func (s *Server) Stop() (e error)

Stop gracefully shuts down the server and all listeners

func (*Server) Transport

func (s *Server) Transport(dst, src io.ReadWriter) (err error)

Transport bidirectionally copies data between dst and src connections Uses buffer pooling to reduce memory allocations and GC pressure

type ServerConfig

type ServerConfig struct {
	// HTTP admin interface configuration
	HTTP struct {
		Addr string `yaml:"addr"`
	} `yaml:"http"`

	// TProxy transparent proxy configuration (not yet implemented)
	TProxy struct {
		Addr string `yaml:"addr"`
	} `yaml:"tproxy"`

	// Sock5 SOCKS5 proxy configuration
	Sock5 struct {
		Addr string `yaml:"addr"`
	} `yaml:"socks5"`
}

ServerConfig holds the configuration for all server components

type Status

type Status struct {
	OutBytes, InBytes uint
	LastOnline        time.Time
	LastFailed        time.Time
	FailedTimes       uint
}

Status tracks statistics and health information for connections

Directories

Path Synopsis
cmd
socks5lb command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL