mirror of
https://github.com/shadowsocks/shadowsocks-libev.git
synced 2026-11-19 12:24:18 +00:00
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.
This commit is contained in:
+73
-68
@@ -6,24 +6,28 @@ include_directories(${SODIUM_INCLUDE_DIRS})
|
||||
include_directories(${PCRE2_INCLUDE_DIRS})
|
||||
include_directories(${CARES_INCLUDE_DIRS})
|
||||
|
||||
if(WITH_EMBEDDED_SRC)
|
||||
include_directories(${PROJECT_SOURCE_DIR}/libcork/include)
|
||||
include_directories(${PROJECT_SOURCE_DIR}/libipset/include)
|
||||
include_directories(${PROJECT_SOURCE_DIR}/libbloom/murmur2)
|
||||
include_directories(${PROJECT_SOURCE_DIR}/libbloom)
|
||||
endif()
|
||||
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
find_program(VALGRIND_EXECUTABLE NAMES valgrind)
|
||||
endif()
|
||||
|
||||
# Helper function to add a unit test
|
||||
function(ss_add_test name sources libs)
|
||||
if(WIN32 AND "${sources}" MATCHES "utils.c")
|
||||
list(APPEND sources ${PROJECT_SOURCE_DIR}/src/winsock.c)
|
||||
endif()
|
||||
add_executable(${name} ${sources})
|
||||
target_compile_definitions(${name} PRIVATE -DHAVE_CONFIG_H)
|
||||
target_link_libraries(${name} ${libs})
|
||||
if(WIN32)
|
||||
target_link_libraries(${name} ws2_32)
|
||||
endif()
|
||||
# Keep assertions enabled for tests even in Release builds.
|
||||
target_compile_options(${name} PRIVATE -UNDEBUG)
|
||||
ss_project_options(${name})
|
||||
if(MSVC)
|
||||
target_compile_options(${name} PRIVATE /UNDEBUG)
|
||||
else()
|
||||
target_compile_options(${name} PRIVATE -UNDEBUG)
|
||||
endif()
|
||||
add_test(NAME ${name} COMMAND ${name})
|
||||
set_tests_properties(${name} PROPERTIES LABELS "unit")
|
||||
|
||||
@@ -53,88 +57,67 @@ ss_add_test(test_base64
|
||||
# test_utils - needs sodium (for ss_malloc -> uses sodium in utils.c)
|
||||
ss_add_test(test_utils
|
||||
"test_utils.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"${LIBSODIUM_SHARED}")
|
||||
"ss_sodium")
|
||||
|
||||
# test_json - standalone json parser
|
||||
ss_add_test(test_json
|
||||
"test_json.c;${PROJECT_SOURCE_DIR}/src/json.c"
|
||||
"m")
|
||||
"${SS_MATH_LIBRARY}")
|
||||
|
||||
# test_ssurl - ss:// URI parsing (SIP002 and legacy)
|
||||
ss_add_test(test_ssurl
|
||||
"test_ssurl.c;${PROJECT_SOURCE_DIR}/src/ssurl.c;${PROJECT_SOURCE_DIR}/src/base64.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"${LIBSODIUM_SHARED}")
|
||||
"ss_sodium")
|
||||
|
||||
# test_netutils - needs cork for ip address parsing
|
||||
# test_netutils - address parsing and resolver integration
|
||||
set(TEST_NETUTILS_LIBS
|
||||
${LIBSODIUM_SHARED}
|
||||
${LIBEV_SHARED}
|
||||
${LIBUDNS_SHARED}
|
||||
ss_sodium
|
||||
ss_ev
|
||||
ss_cares
|
||||
)
|
||||
if(WITH_EMBEDDED_SRC)
|
||||
list(APPEND TEST_NETUTILS_LIBS cork)
|
||||
else()
|
||||
list(APPEND TEST_NETUTILS_LIBS ${LIBCORK_SHARED})
|
||||
endif()
|
||||
ss_add_test(test_netutils
|
||||
"test_netutils.c;${PROJECT_SOURCE_DIR}/src/netutils.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"${TEST_NETUTILS_LIBS}")
|
||||
|
||||
# test_cache - needs libev for ev_time()
|
||||
# test_cache - expiration uses a platform monotonic clock
|
||||
ss_add_test(test_cache
|
||||
"test_cache.c;${PROJECT_SOURCE_DIR}/src/cache.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"${LIBEV_SHARED};${LIBSODIUM_SHARED}")
|
||||
"ss_sodium")
|
||||
|
||||
# test_ppbloom - needs bloom
|
||||
set(TEST_PPBLOOM_LIBS "")
|
||||
if(WITH_EMBEDDED_SRC)
|
||||
list(APPEND TEST_PPBLOOM_LIBS bloom)
|
||||
else()
|
||||
list(APPEND TEST_PPBLOOM_LIBS ${LIBBLOOM_SHARED})
|
||||
endif()
|
||||
list(APPEND TEST_PPBLOOM_LIBS bloom)
|
||||
ss_add_test(test_ppbloom
|
||||
"test_ppbloom.c;${PROJECT_SOURCE_DIR}/src/ppbloom.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"${TEST_PPBLOOM_LIBS};${LIBSODIUM_SHARED};m")
|
||||
"${TEST_PPBLOOM_LIBS};ss_sodium;${SS_MATH_LIBRARY}")
|
||||
|
||||
# test_rule - needs pcre and cork
|
||||
if(SS_ENABLE_REGEX)
|
||||
# test_rule - regex matching
|
||||
set(TEST_RULE_LIBS
|
||||
${LIBPCRE2_SHARED}
|
||||
${LIBSODIUM_SHARED}
|
||||
ss_pcre2
|
||||
ss_sodium
|
||||
)
|
||||
if(WITH_EMBEDDED_SRC)
|
||||
list(APPEND TEST_RULE_LIBS cork)
|
||||
else()
|
||||
list(APPEND TEST_RULE_LIBS ${LIBCORK_SHARED})
|
||||
endif()
|
||||
ss_add_test(test_rule
|
||||
"test_rule.c;${PROJECT_SOURCE_DIR}/src/rule.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"${TEST_RULE_LIBS}")
|
||||
|
||||
# test_acl - needs pcre, cork, and ipset
|
||||
# test_acl - ACL precedence and prefix matching
|
||||
set(TEST_ACL_LIBS ${TEST_RULE_LIBS})
|
||||
if(WITH_EMBEDDED_SRC)
|
||||
list(APPEND TEST_ACL_LIBS ipset)
|
||||
else()
|
||||
list(APPEND TEST_ACL_LIBS ${LIBCORKIPSET_SHARED})
|
||||
endif()
|
||||
ss_add_test(test_acl
|
||||
"test_acl.c;${PROJECT_SOURCE_DIR}/src/acl.c;${PROJECT_SOURCE_DIR}/src/rule.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"test_acl.c;${PROJECT_SOURCE_DIR}/src/acl.c;${PROJECT_SOURCE_DIR}/src/ipset.c;${PROJECT_SOURCE_DIR}/src/rule.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"${TEST_ACL_LIBS}")
|
||||
|
||||
# test_jconf - needs cork and json
|
||||
set(TEST_JCONF_LIBS
|
||||
${LIBSODIUM_SHARED}
|
||||
${LIBEV_SHARED}
|
||||
${LIBUDNS_SHARED}
|
||||
)
|
||||
if(WITH_EMBEDDED_SRC)
|
||||
list(APPEND TEST_JCONF_LIBS cork)
|
||||
else()
|
||||
list(APPEND TEST_JCONF_LIBS ${LIBCORK_SHARED})
|
||||
endif()
|
||||
|
||||
# test_jconf - configuration parsing
|
||||
set(TEST_JCONF_LIBS
|
||||
ss_sodium
|
||||
ss_ev
|
||||
ss_cares
|
||||
)
|
||||
ss_add_test(test_jconf
|
||||
"test_jconf.c;${PROJECT_SOURCE_DIR}/src/jconf.c;${PROJECT_SOURCE_DIR}/src/json.c;${PROJECT_SOURCE_DIR}/src/utils.c;${PROJECT_SOURCE_DIR}/src/netutils.c"
|
||||
"${TEST_JCONF_LIBS};m")
|
||||
"${TEST_JCONF_LIBS};${SS_MATH_LIBRARY}")
|
||||
|
||||
# Crypto sources shared by the tests that link the crypto layer. The AEAD-2022
|
||||
# ciphers pull in BLAKE3 (linked as the `blake3` target) and the session-based
|
||||
@@ -144,40 +127,39 @@ set(SS_CRYPTO_TEST_SOURCES
|
||||
${PROJECT_SOURCE_DIR}/src/aead.c
|
||||
${PROJECT_SOURCE_DIR}/src/aead2022.c
|
||||
${PROJECT_SOURCE_DIR}/src/aead2022_udp.c
|
||||
${PROJECT_SOURCE_DIR}/src/stream.c
|
||||
${PROJECT_SOURCE_DIR}/src/ppbloom.c
|
||||
${PROJECT_SOURCE_DIR}/src/cache.c
|
||||
${PROJECT_SOURCE_DIR}/src/base64.c
|
||||
${PROJECT_SOURCE_DIR}/src/utils.c
|
||||
)
|
||||
|
||||
if(SS_ENABLE_LEGACY)
|
||||
list(APPEND SS_CRYPTO_TEST_SOURCES ${PROJECT_SOURCE_DIR}/src/stream.c)
|
||||
endif()
|
||||
|
||||
# test_buffer - needs sodium and mbedtls for crypto.c buffer functions
|
||||
ss_add_test(test_buffer
|
||||
"test_buffer.c;${SS_CRYPTO_TEST_SOURCES}"
|
||||
"${LIBSODIUM_SHARED};${LIBMBEDTLS_SHARED};${LIBMBEDCRYPTO_SHARED};${LIBEV_SHARED};${TEST_PPBLOOM_LIBS};blake3;m")
|
||||
"ss_sodium;;ss_mbedcrypto;ss_ev;${TEST_PPBLOOM_LIBS};blake3;${SS_MATH_LIBRARY}")
|
||||
|
||||
# test_crypto - full crypto test
|
||||
set(TEST_CRYPTO_LIBS
|
||||
${LIBSODIUM_SHARED}
|
||||
${LIBMBEDTLS_SHARED}
|
||||
${LIBMBEDCRYPTO_SHARED}
|
||||
${LIBEV_SHARED}
|
||||
ss_sodium
|
||||
|
||||
ss_mbedcrypto
|
||||
ss_ev
|
||||
)
|
||||
if(WITH_EMBEDDED_SRC)
|
||||
list(APPEND TEST_CRYPTO_LIBS bloom)
|
||||
else()
|
||||
list(APPEND TEST_CRYPTO_LIBS ${LIBBLOOM_SHARED})
|
||||
endif()
|
||||
list(APPEND TEST_CRYPTO_LIBS bloom)
|
||||
# BLAKE3 backs the 2022 ciphers' key derivation
|
||||
list(APPEND TEST_CRYPTO_LIBS blake3)
|
||||
ss_add_test(test_crypto
|
||||
"test_crypto.c;${SS_CRYPTO_TEST_SOURCES}"
|
||||
"${TEST_CRYPTO_LIBS};m")
|
||||
"${TEST_CRYPTO_LIBS};${SS_MATH_LIBRARY}")
|
||||
|
||||
# test_aead2022 - Shadowsocks 2022 Edition (SIP022) ciphers
|
||||
ss_add_test(test_aead2022
|
||||
"test_aead2022.c;${SS_CRYPTO_TEST_SOURCES}"
|
||||
"${TEST_CRYPTO_LIBS};m")
|
||||
"${TEST_CRYPTO_LIBS};${SS_MATH_LIBRARY}")
|
||||
|
||||
# test_interop_rust - interoperability against shadowsocks-rust.
|
||||
# Skips itself when shadowsocks-rust or the built binaries are absent.
|
||||
@@ -187,10 +169,33 @@ add_test(NAME test_interop_rust
|
||||
set_tests_properties(test_interop_rust PROPERTIES
|
||||
LABELS "integration"
|
||||
TIMEOUT 300
|
||||
ENVIRONMENT "SS_BIN_DIR=${RUNTIME_SHARED_OUTPUT_DIRECTORY}")
|
||||
SKIP_RETURN_CODE 77
|
||||
ENVIRONMENT "SS_BIN_DIR=${CMAKE_RUNTIME_OUTPUT_DIRECTORY}")
|
||||
|
||||
# test_ss_setup - bash unit tests for the ss-setup TUI tool
|
||||
add_test(NAME test_ss_setup
|
||||
COMMAND bash "${PROJECT_SOURCE_DIR}/tests/test_ss_setup.sh"
|
||||
WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}")
|
||||
set_tests_properties(test_ss_setup PROPERTIES LABELS "integration")
|
||||
|
||||
ss_add_test(test_ipset
|
||||
"test_ipset.c;${PROJECT_SOURCE_DIR}/src/ipset.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"ss_sodium")
|
||||
|
||||
ss_add_test(test_process
|
||||
"test_process.c;${PROJECT_SOURCE_DIR}/src/process.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"ss_sodium")
|
||||
set_tests_properties(test_process PROPERTIES TIMEOUT 20)
|
||||
|
||||
ss_add_test(test_resolv
|
||||
"test_resolv.c;${PROJECT_SOURCE_DIR}/src/resolv.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"ss_ev;ss_cares;ss_sodium")
|
||||
set_tests_properties(test_resolv PROPERTIES TIMEOUT 20)
|
||||
|
||||
set(TEST_LITERAL_LIBS ss_sodium)
|
||||
if(SS_ENABLE_REGEX)
|
||||
list(APPEND TEST_LITERAL_LIBS ss_pcre2)
|
||||
endif()
|
||||
ss_add_test(test_acl_literal
|
||||
"test_acl_literal.c;${PROJECT_SOURCE_DIR}/src/acl.c;${PROJECT_SOURCE_DIR}/src/ipset.c;${PROJECT_SOURCE_DIR}/src/rule.c;${PROJECT_SOURCE_DIR}/src/utils.c"
|
||||
"${TEST_LITERAL_LIBS}")
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reject non-system runtime dependencies in static macOS/Windows outputs."""
|
||||
import argparse
|
||||
import platform
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
WINDOWS_SYSTEM_DLLS = {
|
||||
'advapi32.dll', 'bcrypt.dll', 'crypt32.dll', 'dnsapi.dll', 'iphlpapi.dll',
|
||||
'kernel32.dll', 'msvcrt.dll', 'ntdll.dll', 'ole32.dll', 'psapi.dll',
|
||||
'rpcrt4.dll', 'secur32.dll', 'shell32.dll', 'ucrtbase.dll', 'user32.dll',
|
||||
'userenv.dll', 'winmm.dll', 'ws2_32.dll',
|
||||
}
|
||||
|
||||
|
||||
def dependencies(binary, system):
|
||||
if system == 'Darwin':
|
||||
output = subprocess.check_output(['otool', '-L', str(binary)], text=True)
|
||||
return [line.strip().split(' (compatibility version', 1)[0]
|
||||
for line in output.splitlines() if line.startswith('\t')]
|
||||
output = subprocess.check_output(
|
||||
['llvm-readobj', '--coff-imports', str(binary)], text=True)
|
||||
return re.findall(r'^\s+Name: (.+)$', output, re.MULTILINE)
|
||||
|
||||
|
||||
def is_system_dependency(name, system):
|
||||
if system == 'Darwin':
|
||||
return name.startswith(('/usr/lib/', '/System/Library/'))
|
||||
name = name.strip().lower()
|
||||
return name in WINDOWS_SYSTEM_DLLS or (
|
||||
name.startswith(('api-ms-win-', 'ext-ms-win-')) and name.endswith('.dll'))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('binaries', type=Path, nargs='+')
|
||||
args = parser.parse_args()
|
||||
system = platform.system()
|
||||
if system not in ('Darwin', 'Windows'):
|
||||
parser.error('this check supports macOS and native Windows Python')
|
||||
for binary in args.binaries:
|
||||
names = dependencies(binary, system)
|
||||
if not names:
|
||||
raise SystemExit(f'{binary}: no OS imports found; check file format/tool output')
|
||||
unexpected = [name for name in names if not is_system_dependency(name, system)]
|
||||
if unexpected:
|
||||
raise SystemExit(f'{binary}: non-system dependencies: {unexpected}')
|
||||
print(f'PASS {binary}: {", ".join(names)}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,9 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(shadowsocks_consumer LANGUAGES C)
|
||||
find_package(shadowsocks-libev CONFIG REQUIRED)
|
||||
foreach(kind shared static)
|
||||
if(TARGET shadowsocks::${kind})
|
||||
add_executable(consumer_${kind} main.c)
|
||||
target_link_libraries(consumer_${kind} PRIVATE shadowsocks::${kind})
|
||||
endif()
|
||||
endforeach()
|
||||
@@ -0,0 +1,7 @@
|
||||
#include <stddef.h>
|
||||
#include <shadowsocks.h>
|
||||
/* Force the linker to resolve the complete embedding API and its dependencies
|
||||
* without starting an unbounded event loop in this installation smoke test. */
|
||||
static int (*volatile start)(profile_t) = start_ss_local_server;
|
||||
static int (*volatile callback_start)(profile_t, ss_local_callback, void *) = start_ss_local_server_with_callback;
|
||||
int main(void) { return start == NULL || callback_start == NULL; }
|
||||
@@ -0,0 +1,275 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real TCP/UDP interoperability, independent of HTTP proxy environment variables."""
|
||||
import argparse
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import contextlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import socketserver
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class TCPHandler(socketserver.BaseRequestHandler):
|
||||
def handle(self):
|
||||
self.request.settimeout(15)
|
||||
try:
|
||||
while chunk := self.request.recv(16384):
|
||||
self.request.sendall(chunk)
|
||||
except (OSError, TimeoutError):
|
||||
pass
|
||||
|
||||
|
||||
class UDPHandler(socketserver.BaseRequestHandler):
|
||||
def handle(self):
|
||||
data, sock = self.request
|
||||
sock.sendto(data, self.client_address)
|
||||
|
||||
|
||||
class TCPOrigin(socketserver.ThreadingTCPServer):
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
class UDPOrigin(socketserver.ThreadingUDPServer):
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
def receive(sock, size):
|
||||
data = bytearray()
|
||||
while len(data) < size:
|
||||
chunk = sock.recv(size - len(data))
|
||||
if not chunk:
|
||||
raise AssertionError(f"unexpected EOF after {len(data)}/{size} bytes")
|
||||
data.extend(chunk)
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def address(sock, kind):
|
||||
if kind == 1:
|
||||
host = socket.inet_ntop(socket.AF_INET, receive(sock, 4))
|
||||
elif kind == 4:
|
||||
host = socket.inet_ntop(socket.AF_INET6, receive(sock, 16))
|
||||
elif kind == 3:
|
||||
host = receive(sock, receive(sock, 1)[0]).decode("ascii")
|
||||
else:
|
||||
raise AssertionError(f"invalid SOCKS address type {kind}")
|
||||
return host, struct.unpack("!H", receive(sock, 2))[0]
|
||||
|
||||
|
||||
def socks(proxy_port, command, destination):
|
||||
sock = socket.create_connection(("127.0.0.1", proxy_port), timeout=10)
|
||||
try:
|
||||
sock.sendall(b"\x05\x01\x00")
|
||||
assert receive(sock, 2) == b"\x05\x00", "SOCKS authentication failed"
|
||||
host, port = destination
|
||||
encoded = host.encode("ascii")
|
||||
sock.sendall(bytes([5, command, 0, 3, len(encoded)]) + encoded + struct.pack("!H", port))
|
||||
header = receive(sock, 4)
|
||||
assert header[:3] == b"\x05\x00\x00", f"SOCKS request failed: {header.hex()}"
|
||||
relay = address(sock, header[3])
|
||||
return sock, relay
|
||||
except BaseException:
|
||||
sock.close()
|
||||
raise
|
||||
|
||||
|
||||
def tcp_case(proxy_port, origin_port, size):
|
||||
sock, _ = socks(proxy_port, 1, ("localhost", origin_port))
|
||||
payload = os.urandom(size)
|
||||
with sock, concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
||||
# Upload and download concurrently to exercise backpressure in both directions.
|
||||
upload = pool.submit(sock.sendall, payload)
|
||||
assert receive(sock, len(payload)) == payload, "TCP payload mismatch"
|
||||
upload.result(timeout=10)
|
||||
|
||||
|
||||
def udp_case(proxy_port, origin_port):
|
||||
control, relay = socks(proxy_port, 3, ("0.0.0.0", 0))
|
||||
host, port = relay
|
||||
if host in ("0.0.0.0", "::"):
|
||||
host = "127.0.0.1"
|
||||
with control, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
|
||||
sock.settimeout(10)
|
||||
for size in (1, 128, 1200, 4096):
|
||||
payload = os.urandom(size)
|
||||
header = b"\x00\x00\x00\x01" + socket.inet_aton("127.0.0.1") + struct.pack("!H", origin_port)
|
||||
sock.sendto(header + payload, (host, port))
|
||||
try:
|
||||
reply, sender = sock.recvfrom(65535)
|
||||
except TimeoutError as error:
|
||||
raise AssertionError(f"UDP timeout for {size}-byte payload") from error
|
||||
assert sender[1] == port, "UDP reply bypassed relay"
|
||||
assert reply[:3] == b"\x00\x00\x00", "fragmented or invalid SOCKS UDP reply"
|
||||
if reply[3] == 1:
|
||||
offset = 10
|
||||
elif reply[3] == 4:
|
||||
offset = 22
|
||||
elif reply[3] == 3:
|
||||
offset = 7 + reply[4]
|
||||
else:
|
||||
raise AssertionError("invalid UDP address type")
|
||||
assert reply[offset:] == payload, "UDP payload mismatch"
|
||||
|
||||
|
||||
def free_port():
|
||||
# TCP and UDP have separate port reservations, especially on Windows.
|
||||
# Probe both while holding the TCP socket so a TCP-only free port cannot
|
||||
# select a reserved or occupied UDP endpoint.
|
||||
for _ in range(100):
|
||||
with socket.socket() as tcp, socket.socket(type=socket.SOCK_DGRAM) as udp:
|
||||
tcp.bind(("127.0.0.1", 0))
|
||||
port = tcp.getsockname()[1]
|
||||
try:
|
||||
udp.bind(("127.0.0.1", port))
|
||||
except OSError:
|
||||
continue
|
||||
return port
|
||||
raise RuntimeError("could not find a free TCP/UDP port")
|
||||
|
||||
|
||||
def wait_ready(process, port):
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise AssertionError(f"peer exited with {process.returncode}")
|
||||
try:
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=.1):
|
||||
return
|
||||
except OSError:
|
||||
time.sleep(.03)
|
||||
raise AssertionError(f"peer failed to listen on port {port}")
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def peers(commands, ports, environment=None):
|
||||
processes = []
|
||||
with tempfile.TemporaryDirectory(prefix="ss-interop-") as temp, contextlib.ExitStack() as stack:
|
||||
logs = []
|
||||
try:
|
||||
for index, (command, port) in enumerate(zip(commands, ports)):
|
||||
path = Path(temp) / f"peer-{index}.log"
|
||||
log = stack.enter_context(path.open("wb"))
|
||||
logs.append(path)
|
||||
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, env=environment)
|
||||
processes.append(process)
|
||||
wait_ready(process, port)
|
||||
yield
|
||||
except BaseException:
|
||||
for path in logs:
|
||||
print(path.name + ":\n" + path.read_text(errors="replace")[-6000:], flush=True)
|
||||
raise
|
||||
finally:
|
||||
for process in reversed(processes):
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
for process in reversed(processes):
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--self", action="store_true", help="use this build for both peers")
|
||||
parser.add_argument("--method", help="run one cipher")
|
||||
parser.add_argument("--bin", default=os.environ.get("SS_BIN_DIR", "build/bin"), help="program directory")
|
||||
parser.add_argument("--plugin", help="SIP003 fixture executable (requires --self)")
|
||||
parser.add_argument("--isolate-windows-runtime", action="store_true",
|
||||
help="remove MSYS2/toolchain DLL directories from child PATH")
|
||||
args = parser.parse_args()
|
||||
if args.plugin and not args.self:
|
||||
parser.error("--plugin requires --self")
|
||||
environment = None
|
||||
if args.isolate_windows_runtime:
|
||||
if os.name != "nt":
|
||||
parser.error("--isolate-windows-runtime requires Windows")
|
||||
environment = os.environ.copy()
|
||||
system_root = os.environ["SYSTEMROOT"]
|
||||
environment["PATH"] = os.pathsep.join((system_root, os.path.join(system_root, "System32")))
|
||||
binary_dir = Path(args.bin).resolve()
|
||||
suffix = ".exe" if os.name == "nt" else ""
|
||||
local, server = [str(binary_dir / (name + suffix)) for name in ("ss-local", "ss-server")]
|
||||
rust_local, rust_server = shutil.which("sslocal"), shutil.which("ssserver")
|
||||
missing = [p for p in (local, server) if not os.path.isfile(p)]
|
||||
if not args.self:
|
||||
missing += [name for name, found in (("sslocal", rust_local), ("ssserver", rust_server)) if not found]
|
||||
if missing:
|
||||
print("Missing interoperability prerequisites: " + ", ".join(missing))
|
||||
return 1 if os.environ.get("SS_REQUIRE_INTEROP") == "1" else 77
|
||||
methods = ["2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm",
|
||||
"2022-blake3-chacha20-poly1305", "aes-128-gcm", "aes-256-gcm",
|
||||
"chacha20-ietf-poly1305"]
|
||||
if args.method:
|
||||
methods = [args.method]
|
||||
failures = 0
|
||||
with TCPOrigin(("127.0.0.1", 0), TCPHandler) as tcp, UDPOrigin(("127.0.0.1", 0), UDPHandler) as udp:
|
||||
for origin in (tcp, udp):
|
||||
threading.Thread(target=origin.serve_forever, daemon=True).start()
|
||||
try:
|
||||
for method in methods:
|
||||
key_size = 16 if method == "2022-blake3-aes-128-gcm" else 32
|
||||
psk = base64.b64encode(os.urandom(key_size)).decode("ascii")
|
||||
directions = ("self",) if args.self else ("C client -> Rust server", "Rust client -> C server")
|
||||
for direction in directions:
|
||||
label = f"{method}: {direction}"
|
||||
print("RUN " + label, flush=True)
|
||||
server_port, local_port = free_port(), free_port()
|
||||
c_server = [server, "-s", "127.0.0.1", "-p", str(server_port), "-k", psk, "-m", method, "-u"]
|
||||
c_local = [local, "-s", "127.0.0.1", "-p", str(server_port), "-l", str(local_port), "-k", psk, "-m", method, "-u"]
|
||||
commands = [c_server, c_local]
|
||||
plugin_temp = tempfile.TemporaryDirectory(prefix="ss-plugin-") if args.plugin else None
|
||||
markers = []
|
||||
if args.plugin:
|
||||
for mode, command in zip(("server", "client"), commands):
|
||||
marker = Path(plugin_temp.name) / mode
|
||||
markers.append(marker)
|
||||
command.extend(["--plugin", str(Path(args.plugin).resolve()),
|
||||
"--plugin-opts", f"{mode};marker={marker}"])
|
||||
if direction.startswith("C client"):
|
||||
commands[0] = [rust_server, "-s", f"127.0.0.1:{server_port}", "-k", psk, "-m", method, "-U"]
|
||||
elif direction.startswith("Rust client"):
|
||||
commands[1] = [rust_local, "-b", f"127.0.0.1:{local_port}", "-s", f"127.0.0.1:{server_port}", "-k", psk, "-m", method, "-U"]
|
||||
try:
|
||||
with peers(commands, [server_port, local_port], environment):
|
||||
for marker in markers:
|
||||
deadline = time.monotonic() + 10
|
||||
while not marker.exists() and time.monotonic() < deadline:
|
||||
time.sleep(.03)
|
||||
assert marker.exists(), "plugin did not become ready"
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
|
||||
cases = [pool.submit(tcp_case, local_port, tcp.server_address[1], size)
|
||||
for size in (1, 65536, 1048576)]
|
||||
for case in cases:
|
||||
case.result(timeout=30)
|
||||
udp_case(local_port, udp.server_address[1])
|
||||
for marker in markers:
|
||||
pid = int(marker.read_text())
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError(f"plugin child {pid} survived parent shutdown")
|
||||
print("PASS TCP (3 concurrent streams) + UDP: " + label, flush=True)
|
||||
except (OSError, AssertionError, TimeoutError) as error:
|
||||
failures += 1
|
||||
print(f"FAIL {label}: {error}", flush=True)
|
||||
finally:
|
||||
if plugin_temp is not None:
|
||||
plugin_temp.cleanup()
|
||||
finally:
|
||||
tcp.shutdown()
|
||||
udp.shutdown()
|
||||
return int(failures != 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Loopback UDP echo measurement; includes Python/SOCKS overhead, not a capacity test."""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from interop import UDPOrigin, UDPHandler, free_port, peers, socks
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--bin", required=True, type=Path)
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
parser.add_argument("--count", type=int, default=2000)
|
||||
parser.add_argument("--repeat", type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
results = []
|
||||
with UDPOrigin(("127.0.0.1", 0), UDPHandler) as origin:
|
||||
threading.Thread(target=origin.serve_forever, daemon=True).start()
|
||||
try:
|
||||
for method in ("aes-128-gcm", "aes-256-gcm", "chacha20-ietf-poly1305"):
|
||||
server_port, local_port = free_port(), free_port()
|
||||
key = base64.b64encode(os.urandom(32)).decode("ascii")
|
||||
common = ["-s", "127.0.0.1", "-p", str(server_port), "-m", method, "-k", key, "-u"]
|
||||
commands = [[str(args.bin.resolve() / "ss-server"), *common],
|
||||
[str(args.bin.resolve() / "ss-local"), *common, "-l", str(local_port)]]
|
||||
with peers(commands, [server_port, local_port]):
|
||||
control, relay = socks(local_port, 3, ("0.0.0.0", 0))
|
||||
with control, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp:
|
||||
udp.settimeout(5)
|
||||
relay = ("127.0.0.1", relay[1])
|
||||
prefix = b"\0\0\0\x01\x7f\0\0\x01" + struct.pack("!H", origin.server_address[1])
|
||||
for trial in range(args.repeat):
|
||||
start = time.perf_counter()
|
||||
for sequence in range(args.count):
|
||||
payload = struct.pack("!I", sequence) + bytes(1196)
|
||||
udp.sendto(prefix + payload, relay)
|
||||
response, sender = udp.recvfrom(65536)
|
||||
assert sender[1] == relay[1] and response[10:] == payload
|
||||
elapsed = time.perf_counter() - start
|
||||
results.append(dict(cipher=method, trial=trial, packets=args.count,
|
||||
payload_bytes=1200, seconds=elapsed,
|
||||
payload_mbps=args.count * 1200 * 8 / elapsed / 1e6))
|
||||
finally:
|
||||
origin.shutdown()
|
||||
args.output.write_text(json.dumps(results, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+43
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Transparent SIP003 test transport; never used as a production plugin."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import socketserver
|
||||
import threading
|
||||
|
||||
mode, marker = os.environ["SS_PLUGIN_OPTIONS"].split(";marker=", 1)
|
||||
local = (os.environ["SS_LOCAL_HOST"], int(os.environ["SS_LOCAL_PORT"]))
|
||||
remote = (os.environ["SS_REMOTE_HOST"], int(os.environ["SS_REMOTE_PORT"]))
|
||||
listen, destination = (remote, local) if mode == "server" else (local, remote)
|
||||
|
||||
|
||||
def copy(source, target):
|
||||
try:
|
||||
while data := source.recv(16384):
|
||||
target.sendall(data)
|
||||
target.shutdown(socket.SHUT_WR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
class Handler(socketserver.BaseRequestHandler):
|
||||
def handle(self):
|
||||
try:
|
||||
with socket.create_connection(destination, timeout=10) as upstream:
|
||||
self.request.settimeout(10)
|
||||
thread = threading.Thread(target=copy, args=(self.request, upstream), daemon=True)
|
||||
thread.start()
|
||||
copy(upstream, self.request)
|
||||
thread.join(timeout=10)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
class Server(socketserver.ThreadingTCPServer):
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
with Server(listen, Handler) as server:
|
||||
Path(marker).write_text(str(os.getpid()), encoding="ascii")
|
||||
server.serve_forever()
|
||||
+10
-19
@@ -1,7 +1,7 @@
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include "test_helpers.h"
|
||||
|
||||
#include "acl.h"
|
||||
|
||||
@@ -10,11 +10,8 @@ int verbose = 0;
|
||||
static void
|
||||
test_invalid_regex_is_not_installed(void)
|
||||
{
|
||||
char path[] = "/tmp/ss_acl_test.XXXXXX";
|
||||
int fd = mkstemp(path);
|
||||
assert(fd >= 0);
|
||||
|
||||
FILE *f = fdopen(fd, "w");
|
||||
char path[4096];
|
||||
FILE *f = test_tempfile(path, sizeof(path));
|
||||
assert(f != NULL);
|
||||
fprintf(f, "[black_list]\n");
|
||||
fprintf(f, "[invalid\n");
|
||||
@@ -31,17 +28,14 @@ test_invalid_regex_is_not_installed(void)
|
||||
assert(outbound_block_match_host("outbound.example") == 1);
|
||||
free_acl();
|
||||
|
||||
unlink(path);
|
||||
remove(path);
|
||||
}
|
||||
|
||||
static void
|
||||
test_long_acl_line_is_discarded(void)
|
||||
{
|
||||
char path[] = "/tmp/ss_acl_test.XXXXXX";
|
||||
int fd = mkstemp(path);
|
||||
assert(fd >= 0);
|
||||
|
||||
FILE *f = fdopen(fd, "w");
|
||||
char path[4096];
|
||||
FILE *f = test_tempfile(path, sizeof(path));
|
||||
assert(f != NULL);
|
||||
fprintf(f, "[black_list]\n");
|
||||
for (int i = 0; i < 400; i++) {
|
||||
@@ -55,17 +49,14 @@ test_long_acl_line_is_discarded(void)
|
||||
assert(acl_match_host("kept.example") == 1);
|
||||
free_acl();
|
||||
|
||||
unlink(path);
|
||||
remove(path);
|
||||
}
|
||||
|
||||
static void
|
||||
test_invalid_cidr_is_discarded(void)
|
||||
{
|
||||
char path[] = "/tmp/ss_acl_test.XXXXXX";
|
||||
int fd = mkstemp(path);
|
||||
assert(fd >= 0);
|
||||
|
||||
FILE *f = fdopen(fd, "w");
|
||||
char path[4096];
|
||||
FILE *f = test_tempfile(path, sizeof(path));
|
||||
assert(f != NULL);
|
||||
fprintf(f, "[black_list]\n");
|
||||
fprintf(f, "1.2.3.0/999\n");
|
||||
@@ -83,7 +74,7 @@ test_invalid_cidr_is_discarded(void)
|
||||
assert(acl_match_host("path/with/slash.example") == 1);
|
||||
free_acl();
|
||||
|
||||
unlink(path);
|
||||
remove(path);
|
||||
}
|
||||
|
||||
int
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "acl.h"
|
||||
#include "rule.h"
|
||||
int verbose = 0;
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
(void)argc;
|
||||
char path[4096];
|
||||
assert(snprintf(path, sizeof(path), "%s.acl", argv[0]) < (int)sizeof(path));
|
||||
FILE *file = fopen(path, "w");
|
||||
assert(file != NULL);
|
||||
fputs("[black_list]\nfull:Exact.example\nsuffix:blocked.example\n10.0.0.0/8\n"
|
||||
"2001:db8::/32\n[white_list]\nsuffix:allowed.example\n"
|
||||
"[outbound_block_list]\nfull:outbound.example\n", file);
|
||||
fclose(file);
|
||||
assert(init_acl(path) == 0);
|
||||
assert(acl_match_host("EXACT.example") == 1);
|
||||
assert(acl_match_host("sub.exact.example") == 0);
|
||||
assert(acl_match_host("blocked.example") == 1);
|
||||
assert(acl_match_host("a.blocked.example") == 1);
|
||||
assert(acl_match_host("notblocked.example") == 0);
|
||||
assert(acl_match_host("blocked.example.evil") == 0);
|
||||
assert(acl_match_host("a.allowed.example") == -1);
|
||||
assert(outbound_block_match_host("outbound.example") == 1);
|
||||
assert(outbound_block_match_host("a.outbound.example") == 0);
|
||||
assert(acl_match_host("10.42.1.2") == 1);
|
||||
assert(acl_remove_ip("10.42.1.2") == 0);
|
||||
assert(acl_match_host("10.42.1.2") == 0);
|
||||
assert(acl_match_host("10.42.1.3") == 1);
|
||||
assert(acl_add_ip("10.42.1.2") == 0);
|
||||
assert(acl_match_host("10.42.1.2") == 1);
|
||||
assert(acl_remove_ip("2001:db8::42") == 0);
|
||||
assert(acl_match_host("2001:db8::42") == 0);
|
||||
assert(acl_match_host("2001:db8::43") == 1);
|
||||
free_acl();
|
||||
#if !SS_ENABLE_REGEX
|
||||
file = fopen(path, "w");
|
||||
assert(file != NULL);
|
||||
fputs("[black_list]\n10.0.0.0/8\n^old\\.regex$\n", file);
|
||||
fclose(file);
|
||||
assert(init_acl(path) == -1);
|
||||
assert(acl_match_host("10.1.1.1") == 0);
|
||||
#endif
|
||||
remove(path);
|
||||
return 0;
|
||||
}
|
||||
@@ -181,6 +181,7 @@ test_aead_repeat_salt_rejection_releases_context(void)
|
||||
* the first segment carries the nonce, so a codec that mishandles the
|
||||
* post-nonce steady state still round-trips a single segment correctly.
|
||||
*/
|
||||
#if SS_ENABLE_LEGACY
|
||||
static void
|
||||
test_stream_multi_segment_roundtrip(const char *method)
|
||||
{
|
||||
@@ -222,6 +223,8 @@ test_stream_multi_segment_roundtrip(const char *method)
|
||||
ss_free(crypto);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
int
|
||||
main(void)
|
||||
{
|
||||
@@ -236,6 +239,7 @@ main(void)
|
||||
test_crypto_parse_key();
|
||||
test_aead_repeat_salt_rejection_releases_context();
|
||||
|
||||
#if SS_ENABLE_LEGACY
|
||||
/* mbedTLS-backed ciphers and libsodium-backed ciphers use different
|
||||
* code paths in stream.c, so cover both. */
|
||||
test_stream_multi_segment_roundtrip("aes-256-cfb");
|
||||
@@ -243,5 +247,8 @@ main(void)
|
||||
test_stream_multi_segment_roundtrip("camellia-128-cfb");
|
||||
test_stream_multi_segment_roundtrip("chacha20-ietf");
|
||||
test_stream_multi_segment_roundtrip("salsa20");
|
||||
#else
|
||||
assert(crypto_init("password", NULL, "aes-256-cfb") == NULL);
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#ifndef SS_TEST_HELPERS_H
|
||||
#define SS_TEST_HELPERS_H
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "platform.h"
|
||||
|
||||
static inline void test_network_cleanup(void)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
WSACleanup();
|
||||
#endif
|
||||
}
|
||||
static inline void test_network_init(void)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
WSADATA data;
|
||||
assert(WSAStartup(MAKEWORD(2, 2), &data) == 0);
|
||||
assert(atexit(test_network_cleanup) == 0);
|
||||
#endif
|
||||
}
|
||||
static inline FILE *test_tempfile(char *path, size_t size)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
char directory[MAX_PATH];
|
||||
DWORD length = GetTempPathA(sizeof(directory), directory);
|
||||
assert(length != 0 && length < sizeof(directory));
|
||||
assert(size >= MAX_PATH);
|
||||
assert(GetTempFileNameA(directory, "ssc", 0, path) != 0);
|
||||
return fopen(path, "w");
|
||||
#else
|
||||
assert(snprintf(path, size, "/tmp/ss-test.XXXXXX") < (int)size);
|
||||
int fd = mkstemp(path);
|
||||
assert(fd >= 0);
|
||||
return fdopen(fd, "w");
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
+8
-120
@@ -1,121 +1,9 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Interoperability tests against shadowsocks-rust.
|
||||
#
|
||||
# The 2022 (SIP022) ciphers are only useful if they interoperate with other
|
||||
# implementations, and a spec detail can be got wrong in a way that still
|
||||
# round-trips against ourselves. This drives our binaries against
|
||||
# shadowsocks-rust's in both directions.
|
||||
#
|
||||
# Skips (exit 0) when shadowsocks-rust is not installed, so it is safe to
|
||||
# run everywhere. Install it with `brew install shadowsocks-rust` or
|
||||
# `cargo install shadowsocks-rust`.
|
||||
|
||||
set -u
|
||||
|
||||
BIN_DIR="${SS_BIN_DIR:-build/shared/bin}"
|
||||
ORIGIN_PORT=${ORIGIN_PORT:-18999}
|
||||
SERVER_PORT=${SERVER_PORT:-18388}
|
||||
LOCAL_PORT=${LOCAL_PORT:-18081}
|
||||
|
||||
result=0
|
||||
SPID=""
|
||||
LPID=""
|
||||
HPID=""
|
||||
|
||||
cleanup() {
|
||||
[ -n "$SPID" ] && kill -9 "$SPID" 2>/dev/null
|
||||
[ -n "$LPID" ] && kill -9 "$LPID" 2>/dev/null
|
||||
[ -n "$HPID" ] && kill -9 "$HPID" 2>/dev/null
|
||||
wait 2>/dev/null
|
||||
return 0
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
for tool in sslocal ssserver; do
|
||||
if ! command -v "$tool" > /dev/null 2>&1; then
|
||||
echo "SKIP: shadowsocks-rust ($tool) not installed"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
for tool in curl python3 openssl; do
|
||||
if ! command -v "$tool" > /dev/null 2>&1; then
|
||||
echo "SKIP: $tool not available"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
if [ ! -x "$BIN_DIR/ss-local" ] || [ ! -x "$BIN_DIR/ss-server" ]; then
|
||||
echo "SKIP: shadowsocks-libev binaries not found in $BIN_DIR"
|
||||
echo " (set SS_BIN_DIR to override)"
|
||||
exit 0
|
||||
#!/bin/sh
|
||||
# Compatibility entry point. Python uses explicit SOCKS sockets, never curl
|
||||
# or HTTP proxy environment variables. Required CI treats missing peers as errors.
|
||||
if ! command -v python3 >/dev/null 2>&1; then
|
||||
echo 'Missing interoperability prerequisite: python3' >&2
|
||||
if [ "${SS_REQUIRE_INTEROP:-0}" = 1 ]; then exit 1; fi
|
||||
exit 77
|
||||
fi
|
||||
|
||||
# A local origin server keeps the test off the network.
|
||||
WWW_DIR="$(mktemp -d)"
|
||||
echo "interop-ok" > "$WWW_DIR/index.html"
|
||||
(cd "$WWW_DIR" && python3 -m http.server "$ORIGIN_PORT" --bind 127.0.0.1) \
|
||||
> /dev/null 2>&1 &
|
||||
HPID=$!
|
||||
sleep 1
|
||||
|
||||
# Fetch through the SOCKS5 proxy and check we got the origin's content back.
|
||||
fetch_through_proxy() {
|
||||
curl -s --max-time 15 --socks5-hostname "127.0.0.1:$LOCAL_PORT" \
|
||||
"http://127.0.0.1:$ORIGIN_PORT/" 2>/dev/null | grep -q "interop-ok"
|
||||
}
|
||||
|
||||
run_case() {
|
||||
local desc="$1" server_cmd="$2" client_cmd="$3"
|
||||
|
||||
printf '\e[0;36mrunning: %s\e[0m\n' "$desc"
|
||||
|
||||
$server_cmd > /dev/null 2>&1 &
|
||||
SPID=$!
|
||||
sleep 1
|
||||
$client_cmd > /dev/null 2>&1 &
|
||||
LPID=$!
|
||||
sleep 2
|
||||
|
||||
if fetch_through_proxy; then
|
||||
printf '\e[0;32mOK: %s\e[0m\n' "$desc"
|
||||
else
|
||||
printf '\e[0;31mFAILED: %s\e[0m\n' "$desc"
|
||||
result=1
|
||||
fi
|
||||
|
||||
kill -9 "$SPID" "$LPID" 2>/dev/null
|
||||
wait "$SPID" "$LPID" 2>/dev/null
|
||||
SPID=""
|
||||
LPID=""
|
||||
# let the listening sockets go away before the next case binds them
|
||||
sleep 2
|
||||
}
|
||||
|
||||
test_method() {
|
||||
local method="$1" key_size="$2"
|
||||
local psk
|
||||
|
||||
psk="$(openssl rand -base64 "$key_size")"
|
||||
|
||||
run_case "$method: libev client -> rust server" \
|
||||
"ssserver -s 127.0.0.1:$SERVER_PORT -k $psk -m $method" \
|
||||
"$BIN_DIR/ss-local -s 127.0.0.1 -p $SERVER_PORT -l $LOCAL_PORT -k $psk -m $method"
|
||||
|
||||
run_case "$method: rust client -> libev server" \
|
||||
"$BIN_DIR/ss-server -s 127.0.0.1 -p $SERVER_PORT -k $psk -m $method" \
|
||||
"sslocal -b 127.0.0.1:$LOCAL_PORT -s 127.0.0.1:$SERVER_PORT -k $psk -m $method"
|
||||
}
|
||||
|
||||
# SIP022. The key sizes are fixed by the spec.
|
||||
test_method 2022-blake3-aes-128-gcm 16
|
||||
test_method 2022-blake3-aes-256-gcm 32
|
||||
test_method 2022-blake3-chacha20-poly1305 32
|
||||
|
||||
# A legacy AEAD cipher, to catch a regression that only affects the old path.
|
||||
test_method aes-256-gcm 32
|
||||
|
||||
rm -rf "$WWW_DIR"
|
||||
|
||||
exit $result
|
||||
exec python3 "$(dirname "$0")/interop.py" "$@"
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#include <assert.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include "ipset.h"
|
||||
int verbose = 0;
|
||||
|
||||
static uint32_t state = 42;
|
||||
static uint32_t
|
||||
next_random(void)
|
||||
{
|
||||
state = state * 1664525u + 1013904223u;
|
||||
return state;
|
||||
}
|
||||
|
||||
static void
|
||||
check_family(unsigned width)
|
||||
{
|
||||
struct ss_ipset set = {0};
|
||||
uint8_t address[16] = {0};
|
||||
bool oracle[256] = {false};
|
||||
unsigned last = width / 8 - 1;
|
||||
/* Independent exhaustive bitmap oracle over a /24 or /120. Prefix writes
|
||||
* can cover the whole space; host deletion must punch holes in them. */
|
||||
for (unsigned round = 0; round < 2000; round++) {
|
||||
unsigned host = next_random() >> 24;
|
||||
unsigned bits = next_random() % 9;
|
||||
bool present = (next_random() >> 31) != 0;
|
||||
unsigned mask = bits == 0 ? 0 : (255u << (8 - bits)) & 255u;
|
||||
address[last] = (uint8_t)host;
|
||||
ss_ipset_assign(&set, address, width, width - 8 + bits, present);
|
||||
for (unsigned i = 0; i < 256; i++) {
|
||||
if ((i & mask) == (host & mask)) {
|
||||
oracle[i] = present;
|
||||
}
|
||||
address[last] = (uint8_t)i;
|
||||
assert(ss_ipset_contains(&set, address, width) == oracle[i]);
|
||||
}
|
||||
}
|
||||
ss_ipset_assign(&set, address, width, 0, true);
|
||||
memset(address, 255, sizeof(address));
|
||||
assert(ss_ipset_contains(&set, address, width));
|
||||
ss_ipset_assign(&set, address, width, width, false);
|
||||
assert(!ss_ipset_contains(&set, address, width));
|
||||
address[last]--;
|
||||
assert(ss_ipset_contains(&set, address, width));
|
||||
ss_ipset_assign(&set, address, width, width + 1, false);
|
||||
assert(ss_ipset_contains(&set, address, width));
|
||||
ss_ipset_clear(&set);
|
||||
ss_ipset_clear(&set);
|
||||
assert(!ss_ipset_contains(&set, address, width));
|
||||
}
|
||||
|
||||
int
|
||||
main(void)
|
||||
{
|
||||
check_family(32);
|
||||
check_family(128);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/* Optional migration differential test. Link against the pre-migration ipset
|
||||
* and cork archives; these are intentionally not production dependencies. */
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <ipset/ipset.h>
|
||||
#include "ipset.h"
|
||||
int verbose = 0;
|
||||
static uint32_t state = 0x725cab91;
|
||||
static uint32_t next_random(void)
|
||||
{
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
return state;
|
||||
}
|
||||
static void check_family(unsigned width)
|
||||
{
|
||||
struct ss_ipset current = {0};
|
||||
struct ip_set reference;
|
||||
ipset_init(&reference);
|
||||
for (unsigned round = 0; round < 2000; round++) {
|
||||
uint8_t bytes[16];
|
||||
for (unsigned i = 0; i < sizeof(bytes); i++) bytes[i] = (uint8_t)next_random();
|
||||
unsigned prefix = next_random() % (width + 1);
|
||||
bool present = (next_random() & 1) != 0;
|
||||
ss_ipset_assign(¤t, bytes, width, prefix, present);
|
||||
struct cork_ipv4 v4;
|
||||
struct cork_ipv6 v6;
|
||||
memcpy(v4._.u8, bytes, sizeof(v4._.u8));
|
||||
memcpy(v6._.u8, bytes, sizeof(v6._.u8));
|
||||
if (width == 32) {
|
||||
if (present) ipset_ipv4_add_network(&reference, &v4, prefix);
|
||||
else ipset_ipv4_remove_network(&reference, &v4, prefix);
|
||||
} else {
|
||||
if (present) ipset_ipv6_add_network(&reference, &v6, prefix);
|
||||
else ipset_ipv6_remove_network(&reference, &v6, prefix);
|
||||
}
|
||||
for (unsigned sample = 0; sample < 257; sample++) {
|
||||
if (sample != 0) {
|
||||
for (unsigned i = 0; i < sizeof(bytes); i++) bytes[i] = (uint8_t)next_random();
|
||||
}
|
||||
memcpy(v4._.u8, bytes, sizeof(v4._.u8));
|
||||
memcpy(v6._.u8, bytes, sizeof(v6._.u8));
|
||||
bool old = width == 32 ? ipset_contains_ipv4(&reference, &v4) : ipset_contains_ipv6(&reference, &v6);
|
||||
assert(old == ss_ipset_contains(¤t, bytes, width));
|
||||
}
|
||||
}
|
||||
ipset_done(&reference);
|
||||
ss_ipset_clear(¤t);
|
||||
}
|
||||
int main(void)
|
||||
{
|
||||
ipset_init_library();
|
||||
check_family(32);
|
||||
check_family(128);
|
||||
puts("1,028,000 IPv4/IPv6 membership comparisons matched the original libipset");
|
||||
return 0;
|
||||
}
|
||||
+36
-19
@@ -6,8 +6,10 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include "test_helpers.h"
|
||||
#ifndef _WIN32
|
||||
#include <sys/wait.h>
|
||||
#endif
|
||||
|
||||
int verbose = 0;
|
||||
|
||||
@@ -103,11 +105,8 @@ test_parse_addr_invalid_ipv6_like_host_is_not_rewritten(void)
|
||||
static void
|
||||
test_read_jconf_preserves_64bit_integer_strings(void)
|
||||
{
|
||||
char path[] = "/tmp/ss_jconf_test.XXXXXX";
|
||||
int fd = mkstemp(path);
|
||||
assert(fd >= 0);
|
||||
|
||||
FILE *f = fdopen(fd, "w");
|
||||
char path[4096];
|
||||
FILE *f = test_tempfile(path, sizeof(path));
|
||||
assert(f != NULL);
|
||||
fprintf(f, "{\n");
|
||||
fprintf(f, "\"server\":\"127.0.0.1\",\n");
|
||||
@@ -122,7 +121,7 @@ test_read_jconf_preserves_64bit_integer_strings(void)
|
||||
assert(conf->remote_port != NULL);
|
||||
assert(strcmp(conf->remote_port, "4294967296") == 0);
|
||||
|
||||
unlink(path);
|
||||
remove(path);
|
||||
}
|
||||
|
||||
static void
|
||||
@@ -139,19 +138,33 @@ write_minimal_config(FILE *f, const char *extra_line)
|
||||
fprintf(f, "\n}\n");
|
||||
}
|
||||
|
||||
#ifndef __MINGW32__
|
||||
static const char *test_executable;
|
||||
static void
|
||||
test_read_jconf_rejects_out_of_range_int_options(void)
|
||||
{
|
||||
char path[] = "/tmp/ss_jconf_test.XXXXXX";
|
||||
int fd = mkstemp(path);
|
||||
assert(fd >= 0);
|
||||
|
||||
FILE *f = fdopen(fd, "w");
|
||||
char path[4096];
|
||||
FILE *f = test_tempfile(path, sizeof(path));
|
||||
assert(f != NULL);
|
||||
write_minimal_config(f, "\"tcp_incoming_sndbuf\":2147483648");
|
||||
fclose(f);
|
||||
|
||||
#ifdef _WIN32
|
||||
char command[3 * 4096];
|
||||
assert(snprintf(command, sizeof(command), "\"%s\" --read-config \"%s\"",
|
||||
test_executable, path) < (int)sizeof(command));
|
||||
STARTUPINFOA startup = {0};
|
||||
PROCESS_INFORMATION child = {0};
|
||||
startup.cb = sizeof(startup);
|
||||
assert(CreateProcessA(test_executable, command, NULL, NULL, FALSE, 0,
|
||||
NULL, NULL, &startup, &child));
|
||||
CloseHandle(child.hThread);
|
||||
assert(WaitForSingleObject(child.hProcess, 10000) == WAIT_OBJECT_0);
|
||||
DWORD status;
|
||||
assert(GetExitCodeProcess(child.hProcess, &status));
|
||||
CloseHandle(child.hProcess);
|
||||
/* FATAL exits with -1, which is a valid nonzero DWORD exit status. */
|
||||
assert(status != 0);
|
||||
#else
|
||||
pid_t pid = fork();
|
||||
assert(pid >= 0);
|
||||
if (pid == 0) {
|
||||
@@ -163,14 +176,20 @@ test_read_jconf_rejects_out_of_range_int_options(void)
|
||||
assert(waitpid(pid, &status, 0) == pid);
|
||||
assert(WIFEXITED(status));
|
||||
assert(WEXITSTATUS(status) != 0);
|
||||
|
||||
unlink(path);
|
||||
}
|
||||
#endif
|
||||
|
||||
remove(path);
|
||||
}
|
||||
|
||||
int
|
||||
main(void)
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
test_executable = argv[0];
|
||||
test_network_init();
|
||||
if (argc == 3 && strcmp(argv[1], "--read-config") == 0) {
|
||||
read_jconf(argv[2]);
|
||||
return 0;
|
||||
}
|
||||
test_parse_addr_ipv4_with_port();
|
||||
test_parse_addr_ipv6_with_port();
|
||||
test_parse_addr_hostname_with_port();
|
||||
@@ -179,8 +198,6 @@ main(void)
|
||||
test_parse_addr_malformed_bracketed_ipv6_is_not_rewritten();
|
||||
test_parse_addr_invalid_ipv6_like_host_is_not_rewritten();
|
||||
test_read_jconf_preserves_64bit_integer_strings();
|
||||
#ifndef __MINGW32__
|
||||
test_read_jconf_rejects_out_of_range_int_options();
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -139,6 +139,15 @@ test_parse_empty_array(void)
|
||||
int
|
||||
main(void)
|
||||
{
|
||||
const char *wide_numbers = "[4294967296,9223372036854775807,-4294967296,0.4294967296]";
|
||||
json_value *wide = json_parse(wide_numbers, strlen(wide_numbers));
|
||||
assert(wide != NULL && wide->type == json_array && wide->u.array.length == 4);
|
||||
assert(wide->u.array.values[0]->u.integer == INT64_C(4294967296));
|
||||
assert(wide->u.array.values[1]->u.integer == INT64_MAX);
|
||||
assert(wide->u.array.values[2]->u.integer == -INT64_C(4294967296));
|
||||
assert(wide->u.array.values[3]->u.dbl > 0.4294967295 && wide->u.array.values[3]->u.dbl < 0.4294967297);
|
||||
json_value_free(wide);
|
||||
assert(json_parse("9223372036854775808", 19) == NULL);
|
||||
test_parse_simple_object();
|
||||
test_parse_array();
|
||||
test_parse_nested();
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include "test_helpers.h"
|
||||
|
||||
int verbose = 0;
|
||||
|
||||
@@ -129,6 +127,7 @@ test_get_sockaddr_rejects_invalid_ip_literal_ports(void)
|
||||
int
|
||||
main(void)
|
||||
{
|
||||
test_network_init();
|
||||
test_get_sockaddr_len();
|
||||
test_sockaddr_cmp();
|
||||
test_sockaddr_cmp_addr();
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "ss_process.h"
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
static void pause_tick(void) { Sleep(10); }
|
||||
#else
|
||||
#include <time.h>
|
||||
static void pause_tick(void) { struct timespec delay = {0, 10000000}; nanosleep(&delay, NULL); }
|
||||
#endif
|
||||
int verbose = 0;
|
||||
|
||||
int
|
||||
main(int argc, char **argv)
|
||||
{
|
||||
if (argc > 1 && strcmp(argv[1], "--child") == 0) {
|
||||
assert(argc == 5);
|
||||
FILE *file = fopen(argv[2], "w");
|
||||
assert(file != NULL);
|
||||
assert(strcmp(argv[3], "spaces and \"quotes\" with \\") == 0);
|
||||
assert(strcmp(argv[4], "") == 0);
|
||||
assert(strcmp(getenv("SS_PROCESS_TEST"), "child value") == 0);
|
||||
fputs("ready\n", file);
|
||||
fclose(file);
|
||||
for (unsigned i = 0; i < 1000; i++) pause_tick();
|
||||
return 0;
|
||||
}
|
||||
if (argc > 1 && strcmp(argv[1], "--exit") == 0) return 17;
|
||||
|
||||
struct ss_process *process = ss_process_new("ss-no-such-program-ef91ac");
|
||||
ss_process_arg(process, "ss-no-such-program-ef91ac");
|
||||
int started = ss_process_start(process, 0);
|
||||
assert(started == -1 || started == 0);
|
||||
/* POSIX permits exec failure to be reported by child exit (notably under
|
||||
* Valgrind's spawn wrapper), rather than synchronously by posix_spawnp. */
|
||||
if (started == 0) {
|
||||
for (unsigned i = 0; i < 500 && ss_process_running(process); i++) pause_tick();
|
||||
assert(!ss_process_running(process));
|
||||
}
|
||||
ss_process_free(process);
|
||||
|
||||
char path[4096];
|
||||
assert(snprintf(path, sizeof(path), "%s.child-output", argv[0]) < (int)sizeof(path));
|
||||
remove(path);
|
||||
process = ss_process_new(argv[0]);
|
||||
ss_process_arg(process, argv[0]);
|
||||
ss_process_arg(process, "--child");
|
||||
ss_process_arg(process, path);
|
||||
ss_process_arg(process, "spaces and \"quotes\" with \\");
|
||||
ss_process_arg(process, "");
|
||||
ss_process_env(process, "SS_PROCESS_TEST", "child value");
|
||||
const char *before = getenv("SS_PROCESS_TEST");
|
||||
char *saved = before == NULL ? NULL : strdup(before);
|
||||
assert(ss_process_start(process, 0) == 0);
|
||||
bool ready = false;
|
||||
for (unsigned i = 0; i < 500; i++) {
|
||||
FILE *file = fopen(path, "r");
|
||||
if (file != NULL) {
|
||||
char line[16];
|
||||
ready = fgets(line, sizeof(line), file) != NULL && strcmp(line, "ready\n") == 0;
|
||||
fclose(file);
|
||||
}
|
||||
if (ready) break;
|
||||
pause_tick();
|
||||
}
|
||||
assert(ready);
|
||||
assert(ss_process_running(process));
|
||||
const char *after = getenv("SS_PROCESS_TEST");
|
||||
assert(saved == NULL ? after == NULL : after != NULL && strcmp(after, saved) == 0);
|
||||
free(saved);
|
||||
ss_process_free(process);
|
||||
remove(path);
|
||||
|
||||
process = ss_process_new(argv[0]);
|
||||
ss_process_arg(process, argv[0]);
|
||||
ss_process_arg(process, "--exit");
|
||||
assert(ss_process_start(process, 0) == 0);
|
||||
for (unsigned i = 0; i < 500 && ss_process_running(process); i++) pause_tick();
|
||||
assert(!ss_process_running(process));
|
||||
ss_process_free(process);
|
||||
ss_process_free(NULL);
|
||||
return 0;
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
#
|
||||
# Usage: bash tests/test_redir_qemu.sh [BIN_DIR]
|
||||
# BIN_DIR: directory containing ss-server and ss-redir binaries
|
||||
# (default: build/shared/bin/)
|
||||
# (default: build/bin/)
|
||||
#
|
||||
# Requirements (Linux only):
|
||||
# - qemu-system-x86_64
|
||||
@@ -22,7 +22,7 @@ set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
BIN_DIR="${1:-$PROJECT_DIR/build/shared/bin}"
|
||||
BIN_DIR="${1:-$PROJECT_DIR/build/bin}"
|
||||
|
||||
# Resolve to absolute path
|
||||
BIN_DIR="$(cd "$BIN_DIR" && pwd)"
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/* Exercise real c-ares cancellation with outstanding A and AAAA requests. */
|
||||
#include "test_helpers.h"
|
||||
#include <ev.h>
|
||||
#include "resolv.h"
|
||||
|
||||
int verbose = 0;
|
||||
struct result { unsigned called, freed; };
|
||||
static void resolved(struct sockaddr *address, void *data)
|
||||
{
|
||||
struct result *result = data;
|
||||
assert(address == NULL);
|
||||
assert(result->freed == 0);
|
||||
result->called++;
|
||||
}
|
||||
static void released(void *data)
|
||||
{
|
||||
struct result *result = data;
|
||||
assert(result->called == 1);
|
||||
result->freed++;
|
||||
}
|
||||
int main(void)
|
||||
{
|
||||
test_network_init();
|
||||
/* A bound but unread UDP socket prevents DNS responses or ICMP rejection;
|
||||
* the test needs no external DNS server or connectivity. */
|
||||
ss_socket_t sink = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
struct sockaddr_in address = {0};
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
assert(bind(sink, (struct sockaddr *)&address, sizeof(address)) == 0);
|
||||
socklen_t size = sizeof(address);
|
||||
assert(getsockname(sink, (struct sockaddr *)&address, &size) == 0);
|
||||
char nameserver[64];
|
||||
snprintf(nameserver, sizeof(nameserver), "127.0.0.1:%u", ntohs(address.sin_port));
|
||||
struct ev_loop *loop = ev_loop_new(0);
|
||||
assert(loop != NULL);
|
||||
for (unsigned round = 0; round < 3; round++) {
|
||||
struct result results[64] = {{0}};
|
||||
assert(resolv_init(loop, nameserver, 0) == 0);
|
||||
for (unsigned i = 0; i < 64; i++) {
|
||||
char hostname[64];
|
||||
snprintf(hostname, sizeof(hostname), "pending-%u.invalid", i);
|
||||
resolv_start(hostname, htons(443), resolved, released, &results[i]);
|
||||
}
|
||||
ev_run(loop, EVRUN_NOWAIT);
|
||||
resolv_shutdown(loop);
|
||||
for (unsigned i = 0; i < 64; i++) {
|
||||
assert(results[i].called == 1);
|
||||
assert(results[i].freed == 1);
|
||||
}
|
||||
assert(ev_run(loop, EVRUN_NOWAIT) == 0);
|
||||
}
|
||||
ev_loop_destroy(loop);
|
||||
ss_socket_close(sink);
|
||||
return 0;
|
||||
}
|
||||
+2
-2
@@ -70,8 +70,8 @@ test_init_rule_invalid(void)
|
||||
static void
|
||||
test_lookup_rule(void)
|
||||
{
|
||||
struct cork_dllist rules;
|
||||
cork_dllist_init(&rules);
|
||||
struct ss_list rules;
|
||||
ss_list_init(&rules);
|
||||
|
||||
rule_t *rule1 = new_rule();
|
||||
accept_rule_arg(rule1, "^google\\.com$");
|
||||
|
||||
@@ -157,6 +157,7 @@ test_rejects_malformed(void)
|
||||
};
|
||||
|
||||
for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) {
|
||||
memset(&u, 0xa5, sizeof(u));
|
||||
assert(ss_url_parse(bad[i], &u) == -1);
|
||||
/* a rejected parse must leave nothing behind to free */
|
||||
assert(u.method == NULL && u.host == NULL && u.port == NULL);
|
||||
|
||||
Reference in New Issue
Block a user