Commit Graph
68 Commits
Author SHA1 Message Date
Max Lv 2ace0f2a24 Run clang-tidy on every ported test
The test regex skipped file names with digits (test_aead2022_cpp.cpp,
test_base64_cpp.cpp); include them, fix the two optional accesses it then
reports, and build test_jconf with the strict warning set.
2026-10-15 01:33:51 +08:00
Max Lv 678a891ef9 tests: port remaining C unit tests to the C++ test harness
Convert acl, acl_literal, aead2022, base64, buffer, cache (legacy
reference), crypto, ipset, ipset_reference, json, netutils, ppbloom,
process, ref, ssurl and utils tests to test_helpers.hpp. ctest names are
unchanged; every assertion is kept. Build the ported sources with the
strict C++ warning set.
2026-10-15 01:33:51 +08:00
Max Lv d168986dc6 tests: rename remaining C unit tests to .cpp (no content changes) 2026-10-15 01:33:51 +08:00
Max Lv 5f47a65c51 Parse the config file on arenas
read_jconf now reads the file and builds the JSON tree in a scratch arena
that is released before it returns, and copies the parsed strings into one
process-lifetime arena instead of a malloc per string. parse_addr and the
config parser share one address splitter.

Port test_jconf to C++ and cover every field copied out of the parse tree,
a re-read, and the densest file the size limit accepts.
2026-10-15 01:33:51 +08:00
Max Lv fad7c44d43 Rename test_jconf.c to test_jconf_cpp.cpp 2026-10-15 01:12:46 +08:00
Max Lv 5f264333a0 Remove the stream ciphers
The unauthenticated stream ciphers (aes-*-cfb, aes-*-ctr, camellia-*-cfb,
chacha20, chacha20-ietf, salsa20) are gone from every build, together
with the SS_ENABLE_LEGACY option, the C++ stream codecs, their C test
oracle and the stream-only tests and configurations. A configuration
naming one of them, or RC4/table, now fails at startup with a message
pointing to an AEAD method, and test_cli checks that.

Shell completions list only the supported methods (and now include the
2022 ones), and the docs and the compatibility contract say the stream
ciphers were removed.
2026-10-15 00:34:33 +08:00
Max Lv 4651184e1f test.py: accept host:port for --dns
The tunnel test hard-coded port 53, so it could only use a public
resolver or root. With a port it runs against a local DNS stand-in.
2026-10-15 00:34:32 +08:00
Max Lv af4e7a02af Fall back to the system heap when a library realloc cannot be served
heap_realloc returned NULL when a block outgrew the largest size class or
the budget, and libuv aborts when growing its watcher array fails: a poll
on fd 8190 or above (about 4,000 connections) killed the process.
Move the block to the system heap instead, as malloc and calloc already
do. test_heap_guard_cpp polls fd 16380 with the heaps installed.
2026-10-15 00:34:32 +08:00
Max Lv 680b3a3a62 Keep clang-tidy clean in the new C++ tests 2026-10-15 00:34:31 +08:00
Max Lv 53adaf380e Replace uthash and ss_list with the C++ containers
The C cache (now used only by the reference codecs) moves to
tests/reference and src/uthash.h is deleted. ACL rules and ss-manager's
servers are ListNodes on IntrusiveLists; destroying an element unlinks
it, so the free paths no longer have to remember to. core.h keeps only
ss_ip. test_rule is ported to C++ and also covers literal rules.
2026-10-15 00:34:31 +08:00
Max Lv 34da0def95 Move the C codecs to tests/reference and drop uthash from ss-manager
The programs now use only the C++ codecs. The C stream/AEAD/AEAD-2022
implementations stay as the reference the differential tests and the C
unit tests compare against. Key derivation and the cipher tables used by
the doc snippets move to src/crypto/keys.{hpp,cpp}.

ss-manager keeps its servers in an ss_list (at most MAX_PORT_NUM,
looked up only on control messages) instead of a uthash table, and
tests/test_manager.py covers add/ping/list/remove end to end.
2026-10-15 00:34:31 +08:00
Max Lv 3efcb79010 Remove ss_event and the C resolver shim
Each program's loop, signals, plugin watcher and stats timer now go
through ss::event::Program (src/event/program.hpp), held on main()'s
stack; ss-manager uses it too. ss-server resolves the manager address
with the relay resolver. With no C caller left, ss_event.cpp/.h,
resolv.cpp/.h and their C tests go; test_resolver_cpp.cpp replaces the
resolver tests against the same delayed local DNS server, and ss_ev is
now an interface target over libuv.
2026-10-15 00:34:31 +08:00
Max Lv 335eb10742 Add an embedding API: ss_local_start/stop/wait and a C++ wrapper
<shadowsocks/control.h> starts ss-local on a library-owned thread,
stops it from any thread through a libuv async handle and waits for it;
<shadowsocks/shadowsocks.hpp> wraps that in a move-only, header-only
shadowsocks::LocalServer whose destructor stops and waits. The library
exports only C symbols, shadowsocks.h is unchanged, and the shared
library version becomes 2.1.0 (SOVERSION 2). test_local_api_cpp covers
the lifecycle; the installed-package consumer gains a C++ program.
2026-10-15 00:34:30 +08:00
Max Lv 282f3606d7 Add --max-connections and --max-udp-sessions
The TCP connection pool and the UDP session table are sized from these
options (or max_connections / max_udp_sessions in the configuration
file) at startup instead of fixed constants; the DNS query pool follows
the connection limit. test_limits.py checks that a connection beyond
the limit is refused and that accepting resumes once one closes.
2026-10-15 00:34:30 +08:00
Max Lv c69fb4c4d9 Seal the heap: bounded library heaps and zero-allocation program tests
The programs point libuv, c-ares and Mbed TLS (MBEDTLS_PLATFORM_MEMORY in
the bundled build) at their own FixedHeap before anything runs, mark the
end of startup with heap_seal(), and in verbose mode report heap use and
any allocation after it at exit. The library build keeps the host's
allocator.

measure_alloc.py gains --udp, and the alloc_steady_programs_* tests now
fail on any malloc per relayed TCP connection (by name and by address)
or UDP association, for every cipher family.
2026-10-15 00:34:30 +08:00
Max Lv 29b1983409 Let the allocation audit target an IP so DNS costs show separately 2026-10-14 22:53:09 +08:00
Max Lv 892b45d1e5 Add the C++ TCP relay engine and run ss-tunnel on it
One engine (src/relay/tcp) for the four TCP relays: connections live in a
fixed pool owned through PoolPtr, handshake, cipher state and buffers are
inline, timeouts are intrusive deadline lists on one timer and DNS answers
come back through generation-checked handles. A full pool refuses new
connections and pauses accepting until a slot frees.

ss-tunnel is the first user; its hand-written relay callbacks are gone.
tests/tunnel_interop.py covers every method against ss-server and
shadowsocks-rust.
2026-10-14 22:53:09 +08:00
Max Lv 78ca0af745 Rewrite the resolver in C++ on a fixed query pool
Queries live in pool slots with their first A and AAAA answer inline,
c-ares sockets are watched from a fixed table, and answers reach the
waiter through a callback plus opaque words instead of a back-pointer.
resolv.cpp keeps the C API as a shim. The event Loop can now adopt the
ss_event loop, and a Poll can stop watching a socket it does not own.
2026-10-14 22:53:09 +08:00
Max Lv ca359160b2 Include C++ headers before crypto.h in test_crypto_aead2022_cpp.cpp
crypto.h defines min/max macros for the C sources; libstdc++ headers
included after it fail to parse.
2026-10-14 22:53:08 +08:00
Max Lv f92f578cce Include <algorithm> for std::min in test_crypto_aead2022_cpp.cpp 2026-10-14 22:53:08 +08:00
Max Lv 47163a57fd Add allocation-free C++ SIP022 codecs
TCP request/response streams with the salt echo between the two
directions, an exact-match salt pool on FixedLru, and UDP packets sealed
and opened in place with caller-owned session state. Differentially
tested against aead2022.cpp in both roles; the steady phase allocates
nothing.
2026-10-14 22:53:08 +08:00
Max Lv 98eda0bdff Include <netinet/in.h> in the UDP eviction test client (FreeBSD)
FreeBSD's <arpa/inet.h> does not define struct sockaddr_in.
2026-10-14 22:53:08 +08:00
Max Lv a6113cec4b Own AEAD-2022 UDP sessions by reference so eviction cannot free a live session
The session table and the relay contexts each hold a reference; evicting a
session from the full table no longer frees memory a relay still uses.
Ported from the parked fix/aead2022-udp-session-eviction work.
2026-10-14 22:53:08 +08:00
Max Lv 503f0f1936 Include C++ headers before crypto.h in test_crypto_stream_cpp.cpp
crypto.h defines min/max macros for the C sources; libstdc++ headers
included after it fail to parse.
2026-10-14 22:53:07 +08:00
Max Lv 8cf10ba890 Do not memcpy from an empty span in the stream decoder
An empty read before the IV arrived passed a null source to memcpy,
which UBSan reports (and the ASan CI job turns into a failure).
2026-10-14 22:53:07 +08:00
Max Lv bf5bc2f216 Include <algorithm> for std::min in test_crypto_stream_cpp.cpp 2026-10-14 22:53:07 +08:00
Max Lv d91ef14f76 Add allocation-free C++ stream cipher codecs
src/crypto/stream.hpp implements the legacy stream methods this build
supports (AES CFB/CTR, Camellia CFB, Salsa20, ChaCha20, ChaCha20-IETF)
as value types. The AES and Camellia contexts are held by value through
Mbed TLS's block-cipher APIs instead of an allocated
mbedtls_cipher_context_t, and the libsodium ciphers track their
keystream position, finishing partial 64-byte blocks from a stack block
instead of the padding copies stream.cpp makes.

test_crypto_stream_cpp runs TCP streams (with fragments that split
keystream blocks) and UDP packets between the C and C++
implementations in both directions for all twelve methods and checks
IV replay; alloc_steady_crypto_stream requires zero allocations for new
connections and packets.
2026-10-14 22:53:07 +08:00
Max Lv ed75faf80f Rewrite the cache on a fixed slab without per-entry allocation
cache.cpp keeps its C API but replaces uthash and the two mallocs per
entry with one slab of nodes holding their keys inline, linked in
last-use order, and an open-addressing index of node ids that hashes
through the slab with a per-cache random seed. Both blocks are reserved
by cache_create() and touched only as entries are used, so a large,
mostly empty cache costs no resident memory.

Semantics are unchanged: an insert evicts the least recently used entry
once the cache holds capacity entries (the AEAD-2022 session table's
4095/4096 boundary), lookups refresh recency and age, cache_clear()
drops stale entries, and free_cb may re-enter the cache. Re-inserting a
key now replaces its data instead of shadowing it. cache_create_keyed()
sizes keys per cache; the AEAD-2022 salt pool and session table use it.

test_cache_cpp covers the boundary, ordering, replacement, ageing,
re-entrant callbacks and limits; alloc_steady_cache requires zero
allocations across 100,000 inserts on a full cache. AEAD-2022 ss-server
drops from 84 to 80 allocations per relayed connection.
2026-10-14 22:53:07 +08:00
Max Lv 110459eba8 Disable the zero-allocation checks with a system Mbed TLS
They hold for the bundled Mbed TLS (MBEDTLS_BLOCK_CIPHER_C); a system
one may allocate in GCM key setup, as the Debian package build shows.
2026-10-14 22:53:06 +08:00
Max Lv ab365b8fff Include C++ headers before crypto.h in test_crypto_aead_cpp.cpp
crypto.h defines min/max macros for the C sources; libstdc++ headers
included after it fail to parse.
2026-10-14 22:51:57 +08:00
Max Lv 3e662faae7 Include <algorithm> for std::min in test_crypto_aead_cpp.cpp 2026-10-14 22:51:57 +08:00
Max Lv 556c1f0696 Add allocation-free C++ AEAD codecs
src/crypto/aead.hpp implements the SIP004/SIP007 AEAD ciphers as value
types: AeadEngine holds the libsodium or Mbed TLS GCM state by value,
AeadTcpEncryptor/AeadTcpDecryptor frame the chunk stream with a fixed
reassembly buffer, and aead_udp_seal/open handle packets. HKDF-SHA1 runs
on stack SHA-1 state instead of Mbed TLS's allocating HMAC API.

The bundled Mbed TLS config now enables MBEDTLS_BLOCK_CIPHER_C, which
keeps the AES context inside mbedtls_gcm_context, so GCM key setup no
longer allocates. That alone saves the C programs two allocations per
connection.

test_crypto_aead_cpp checks HKDF against RFC 5869 and crypto_hkdf, runs
TCP streams and UDP packets between the C and C++ implementations in
both directions for all five AEAD methods, and covers tampering,
framing and salt replay. alloc_steady_crypto_aead runs it under the
malloc counter and requires zero allocations across 600 new
connections and 600 packets (tests/alloc_audit/check_steady.py).

ss_strict_warnings() now applies -Wextra per source file so targets
mixing new C++ with converted C modules keep the latter at -Wall, and
Result gains move assignment.
2026-10-14 22:51:56 +08:00
Max Lv df7a6dc13f Add the C++ event layer over libuv
src/event/loop.hpp wraps uv_loop/poll/timer/signal/async handles that
live by value inside their owner and dispatch to an owner member
function chosen at compile time. A Poll owns its socket and carries
read and write interest on one handle, closing the descriptor in
libuv's close callback. CloseGroup collects the asynchronous closes of
an owner's handles and reports completion afterwards, which is how
pooled owners implement AsyncClosable. DeadlineList drives the idle
timeouts of many owners from one timer.

test_event_cpp covers readiness, closing a peer from inside a
callback, recycling a pooled owner only after its handles closed,
repeating timers, deadline ordering and cross-thread wakeups.
2026-10-14 22:51:38 +08:00
Max Lv 227ad1bb9c Compile the event loop, UDP relay and programs as C++
Rename utils, ss_event, udprelay, winsock, local, server, tunnel, redir
and manager from .c to .cpp. Inside the moved files only the
\snippet{doc} file references and header comments change; snippet
references in doc/*.md, tests/test_cli_docs.py, the build files and
CONTRIBUTION.md follow the new names.

Also cast the Windows-only string literal returned by
get_default_conf(), found by the zig x86_64-windows-gnu build.

Every module of src/ except the unbuilt android.c and the vendored
blake3 is now compiled as C++20. The new .cpp files join the no-heap
ratchet baseline.
2026-10-14 22:51:17 +08:00
Max Lv 349d895fd2 Compile the crypto, config, DNS, ACL and plugin modules as C++
Rename netutils, jconf, stream, aead, aead2022, aead2022_udp, crypto,
acl, plugin, plugin_disabled and resolv from .c to .cpp without changing
their contents, and update source lists, snippet references, test
comments and debian/copyright.

The Doxygen source list and scripts/check_cli_docs.py now accept either
extension for each module, so the remaining programs can move one at a
time. The new .cpp files are added to the no-heap ratchet baseline.
2026-10-14 22:51:16 +08:00
Max Lv 3ae698f5be Raise the test origin's listen backlog
socketserver listens with a backlog of 5. With concurrent connections
through the proxy on a loaded machine (parallel ctest), the backlog
overflows, the kernel resets the origin connection, and the proxy
correctly drops the client, which surfaced as intermittent
alloc_audit_report failures ("getpeername: Invalid argument" in
ss-local, "Connection reset by peer" in ss-server). Reproduced
reliably at 64 concurrent connections; gone with a backlog of 256.
2026-10-14 22:51:16 +08:00
Max Lv 738956b5da Compile the leaf modules as C++
Rename base64, json, ipset, process, ppbloom, rule, ssurl and cache from
.c to .cpp without touching their contents, and update the CMake source
lists, debian/copyright and the docs.

Ported code keeps -Wall; -Wextra is now opt-in through
ss_strict_warnings() for code written as C++ (the core tests).
check_no_heap.py gains a ratchet baseline for the converted modules,
which still allocate the way the C code did. A new check_cxx_runtime
test verifies with nm that the programs and libshadowsocks-c.a still
need no C++ runtime library, so C consumers are unaffected.
2026-10-14 22:51:15 +08:00
Max Lv 641643ec48 Add heap allocation audit for relayed connections
alloc_counter is a preloadable malloc counter (glibc, macOS) that writes
a snapshot on SIGUSR2. measure_alloc.py warms ss-local and ss-server up,
snapshots both, relays more connections and reports allocations per
connection. It runs report-only as the alloc_audit_report ctest.
interop.peers() now yields the started processes.
2026-10-14 12:51:47 +08:00
Max Lv f90cfe9034 Add C++20 ownership and allocation core
Header-only primitives for the no-heap-after-startup design:
Result/Status, Region, ObjectPool with PoolPtr (std::unique_ptr with a
pool deleter), generation-checked Handle and asynchronous close support,
intrusive RefPtr, FixedBuffer, MonotonicArena, FixedHashMap and FixedLru,
IntrusiveList, and a bounded FixedHeap for third-party allocator hooks.

Unit tests cover each primitive (test_core_*). scripts/check_no_heap.py
rejects heap allocation in C++ sources under src/ and runs as a ctest.
clang-tidy now also analyses C++ sources and the core headers.
2026-10-14 12:51:47 +08:00
Max LvandClaude 553cdc7945 Add opt-in printable TCP salt experiment for ss-local (#3063)
Add `ss-local --printable-salt` / `"printable_salt": true`, disabled by
default. For each outgoing TCP salt it picks a prefix length uniformly
from 6-12 bytes and samples those bytes as printable ASCII (0x20-0x7e)
immediately before key derivation. The salt stays 32 bytes with no
framing or markers, so the wire format is unchanged and any stock
server interoperates. Only chacha20-ietf-poly1305 and aes-256-gcm are
accepted; other ciphers fail at startup. UDP, server responses, and
AEAD-2022 are untouched.

Crypto unit tests cover length distribution, empty first writes, exact
framing overhead, salt-tail preservation, byte-at-a-time decryption,
tampering and replay rejection. CLI tests check local-only exposure and
cipher rejection via flag, config key and bad config type. interop.py
gains --printable-salt and --server-bin for independent stock servers.

docs/printable-salt.md records the design, entropy bound, fingerprint
caveats and route-experiment procedure; docs/encoding-experiments.md
and tests/experiments/ hold the Base85/lowpop85/TLS outer-transport
prototypes. docs/measurements/printable-salt-2026-09-23/ archives the
sanitized results of the aborted field trials.

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-13 09:09:51 +08:00
Max Lv 454bdc0a67 Accept combined server endpoints with strict IPv6 parsing 2026-09-13 07:15:28 +08:00
Max Lv ea951e6bd1 Redesign CLI flags, help, and argument validation 2026-09-12 21:17:38 +08:00
Max Lv 8773939dce Raise the file descriptor limit for descriptor-heavy tests
test_event opens 256 UDP receivers plus a sender on top of the loop's own
descriptors. macOS starts processes with a soft RLIMIT_NOFILE of 256, so
socket() eventually returned -1 and the unchecked descriptor tripped the
bind() assertion when running ctest from a stock terminal (#3058).

Wrap every registered unit test in a small sh launcher that raises the soft
limit to 1024 before exec'ing the binary, and have test_event raise its own
limit as well so it also passes when run directly. Assert on socket()
failures so a limit problem is reported as such instead of as a bind error.

Fixes #3058

Claude-Session: https://claude.ai/code/session_01PSG4XV3jiqitDgdgFSGATx
2026-09-12 15:23:43 +08:00
Max Lv f5d5bf0be1 Publish native Doxygen documentation with GitHub Pages 2026-09-12 14:46:42 +08:00
Max Lv 146818c182 Generate CLI manual sections from source option declarations 2026-09-12 10:51:25 +08:00
Max Lv bff687bd34 Add Docker publishing, recommended installation and project history (#3052)
Document the shadowsocks-libev history and shadowsocks-c rename, and recommend Docker installation with mounted configuration and TCP/UDP port mappings.

Add native AMD64/ARM64 builds of the unprivileged static runtime image, real container relay and shutdown tests, and GHCR publication after both architecture checks pass. All 24 build/test checks pass at reviewed head 3f3f6bf8e01e5614821d1e15fda3ad8f07812902; publication is intentionally skipped on pull requests.
2026-09-11 16:22:30 +08:00
Max Lv bdc77408cb Rename to shadowsocks-c with libuv, async DNS and CI lint (#3051)
Rename the project to shadowsocks-c while retaining ss-* commands, the embedding ABI, and legacy library/package lookup compatibility.

Replace libev with bundled libuv for IOCP/kqueue event backends, expand asynchronous runtime DNS coverage, and add actionlint/Ruff with strict clang-tidy failure handling. Validate native platforms, static builds, packaging, interoperability, sanitizers, and canonical/legacy consumers.

All 22 hosted checks pass at reviewed head a8493250eb.
2026-09-11 14:18:37 +08:00
Max Lv 201e70c4bd Modernize C builds with offline dependencies and portable runtime helpers (#3050)
Bundle pinned offline dependencies, remove libcork/libipset and submodule requirements, and add portable runtime helpers with relocatable static/shared library installations.

Add Clang static build validation for Linux/musl, macOS and Windows, real TCP/UDP and SIP003 interoperability coverage, and recorded performance tradeoffs. All 21 hosted checks pass at the reviewed PR head 8d504e6218.
2026-09-11 13:42:11 +08:00
Max Lv fdde2c7cee Release the bloom filter in the AEAD-2022 tests
crypto_init() initializes the nonce bloom filter on every call, so a test
that builds a crypto_t per case has to tear it down per case as well.
Freeing only once at the end leaked a pair of filters for every crypto_t
after the first, which the valgrind memcheck job caught.

test_crypto.c already frees it alongside each crypto_t; do the same here
by folding it into the local free_crypto() helper.
2026-08-20 09:14:04 +08:00
Max Lv 8cc58cea95 Accept an ss:// server URL on the ss-local command line
shadowsocks-rust takes a whole server definition as a URL; libev could
only be given the pieces separately, so importing a server meant taking a
URL apart by hand. ss-local now accepts --server-url and reads the
address, port, cipher, password and SIP003 plugin from it.

Both encodings are handled: the SIP002 form with the userinfo in
base64url, and the older form where the whole body is one base64 blob.
The userinfo is also accepted in the clear, because that is what
shadowsocks-rust's `ssurl` emits for the 2022 ciphers, whose base64
pre-shared keys it percent-encodes instead. IPv6 literals, a trailing
slash, the plugin query and the '#' tag are all covered.

Options given later on the command line still win, since they are applied
as getopt reaches them.

ssurl.c sits with the ss-local sources rather than the shared ones: it
depends on base64.c, which ss-manager does not link.

The tests include URLs copied verbatim from `ssurl --encode` output, so
the parser is pinned against what another implementation really produces
rather than only against my reading of the spec. Verified end to end by
pointing ss-local at a rust-generated URL and proxying through their
ssserver.
2026-08-19 20:15:38 +08:00