Architecture Overview
System architecture and crate map of trojan-rs
trojan-rs is organized as a Cargo workspace with specialized crates for each concern.
System Architecture
┌─────────────┐ TLS ┌──────────────────────────────────────┐
│ Client │──────────────►│ trojan-server │
│ (SOCKS5) │ │ │
└─────────────┘ │ ┌──────────┐ ┌─────────────────┐ │
│ │ TLS │ │ Header Parser │ │
│ │ Acceptor │─►│ (trojan-proto) │ │
│ └──────────┘ └────────┬────────┘ │
│ │ │
│ ┌────────▼────────┐ │
│ │ Auth Verify │ │
│ │ (trojan-auth) │ │
│ └────────┬────────┘ │
│ ┌─────────────┼──────┐ │
│ ┌─────▼─────┐ ┌─────▼────┐│ │
│ │ TCP Relay │ │ Fallback ││ │
│ │ to Target │ │ to HTTP ││ │
│ └───────────┘ └──────────┘│ │
│ │ │
│ ┌──────────┐ ┌────────────┐ │ │
│ │ Metrics │ │ Analytics │ │ │
│ └──────────┘ └────────────┘ │ │
└──────────────────────────────────────┘Connection Flow
- TLS Handshake — Client connects, TLS 1.2/1.3 handshake completes
- Header Parsing — Server reads the Trojan header (56-byte SHA-224 hash + request)
- Authentication — Hash is verified against configured passwords or SQL database
- Forwarding — On success: proxy to target. On failure: forward to fallback HTTP server
- Relay — Bidirectional data relay between client and target
Crate Map
trojan-rs (workspace root)
├── trojan-core Core types, I/O utilities, relay
├── trojan-proto Protocol encoding/decoding
├── trojan-config Configuration parsing & validation
├── trojan-auth Authentication backends
├── trojan-server Server implementation
├── trojan-client Client (SOCKS5 proxy)
├── trojan-cert Certificate generation
├── trojan-metrics Prometheus metrics
├── trojan-analytics ClickHouse event tracking
├── trojan-relay Multi-hop relay chain
├── trojan-transport Pluggable transports (TLS, plain TCP, WebSocket)
├── trojan-rules Rule-based routing engine (GeoIP, domain, CIDR)
├── trojan-lb Load balancer (round-robin, IP hash, least-conn, failover)
└── trojan-rs Binary entry point & re-exportsDependency Graph
trojan-rs (binary)
├── trojan-server
│ ├── trojan-core (relay, I/O, defaults)
│ ├── trojan-proto (header parsing)
│ ├── trojan-auth (password verification)
│ ├── trojan-config (configuration)
│ ├── trojan-metrics (Prometheus)
│ ├── trojan-analytics (ClickHouse)
│ ├── trojan-rules (routing engine)
│ └── trojan-lb (load balancing)
├── trojan-client
│ ├── trojan-core
│ ├── trojan-proto
│ └── trojan-auth (SHA-224 hashing only)
├── trojan-relay
│ ├── trojan-core
│ └── trojan-transport (TLS, plain TCP, WebSocket)
├── trojan-cert
└── trojan-auth (CLI)Core Crates
trojan-core — Shared foundation:
relay_bidirectional()— Zero-copy bidirectional TCP relayPrefixedStream— Stream wrapper for replaying buffered bytes- Transport abstractions (plain TCP, WebSocket)
- Default constants (timeouts, buffer sizes, protocol values)
trojan-proto — Protocol layer:
write_request_header()— Encode Trojan TCP request headerwrite_udp_packet()/parse_udp_packet()— UDP packet encodingAddressRef/HostRef— Address type representations
trojan-config — Configuration:
- Type definitions for all config sections
- TOML/YAML/JSON/JSONC loader
- Validation logic
- CLI argument merging
Server Crates
trojan-server — The main server:
- TCP and UDP handler pipelines
- WebSocket upgrade handling
- Fallback proxy with connection pool
- Rate limiting
- Signal handling (SIGHUP reload, SIGTERM shutdown)
trojan-auth — Authentication:
- In-memory password set
- SQL backends (SQLite, PostgreSQL, MySQL)
- Reloadable auth with periodic cache refresh
- CLI for user management (add/remove/list/update)
Client Crates
trojan-client — SOCKS5 proxy client:
- SOCKS5 handshake (NO AUTH method)
- TCP CONNECT and UDP ASSOCIATE support
- TLS connector with SNI and custom CA support
Infrastructure Crates
trojan-metrics — Prometheus integration:
- HTTP server with
/metrics,/health,/readyendpoints - 30+ metric definitions (connections, auth, bytes, errors)
- Counter, gauge, and histogram recording functions
trojan-analytics — Event tracking:
- Connection event definitions (18 fields)
- Buffered event collection with configurable flush intervals
- ClickHouse and file output writers
- Sampling and privacy controls
trojan-relay — Multi-hop relay:
- Entry node: multi-port listener with rule-based routing
- Relay node: handshake verification and dynamic forwarding
- Pluggable transports (TLS, plain TCP)
- Named chains with shared routing
trojan-cert — Certificate generation:
- ECDSA P-256 key pair generation
- Self-signed X.509 certificate creation
- Subject Alternative Names (domains and IPs)
trojan-transport — Pluggable transport layer:
TransportAcceptor/TransportConnectortraits- TLS transport with auto-generated self-signed certificates
- Plain TCP transport for trusted networks
- WebSocket transport via
tokio-tungstenite
trojan-rules — Rule-based routing:
- Domain matching (exact, suffix, keyword via Aho-Corasick)
- IP CIDR matching (IPv4 and IPv6)
- GeoIP country matching via MaxMind mmdb with auto-download and background updates
- Surge and Clash rule format parsers
- Hot-reloadable engine via
ArcSwap
trojan-lb — Load balancing:
- Round-robin, IP hash, least connections, failover strategies
LbPolicytrait for custom strategies- RAII
ConnectionGuardfor accurate active connection tracking - Health management with automatic recovery after cooldown