Debian Codegraph @

testsuite/daemon-zstd-thread-exhaustion_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """A daemon client must not control an unbounded Zstandard worker count.
3
4 The daemon parses the peer-supplied server argv, so a client that names a
5 large --compress-threads (or its --zt alias) on a PULL makes the daemon-side
6 sender materialize that many Zstandard workers. A stock client can do this
7 with -M--compress-threads=N; no custom client is needed. On an anonymous
8 module no authentication is required first.
9
10 The bound asserted here is the implementation's own: MAX_DAEMON_COMPRESSION
11 _THREADS workers plus the main thread. A looser threshold would go green on a
12 build that simply cannot create the workers -- a libzstd without
13 multithreading, or a process thread limit -- so the test first proves that a
14 threaded worker pool IS reachable here, and only then that it is bounded.
15 """
16
17 import json
18 import os
19 import re
20 import subprocess
21 import sys
22 import time
23
24 from rsyncfns import (
25 SCRATCHDIR, claim_ports, require_tcp, rmtree, run_rsync, start_rsyncd,
26 test_fail, test_skipped,
27 )
28 import rsync_proto as rp
29
30 PORT = 13120
31 REQUESTED_THREADS = 256
32 # options.c: MAX_DAEMON_COMPRESSION_THREADS, plus the main thread.
33 MAX_DAEMON_COMPRESSION_THREADS = 8
34 MAX_SAFE_THREADS = MAX_DAEMON_COMPRESSION_THREADS + 1
35
36 require_tcp("the malicious receiver needs a real TCP daemon; run with --use-tcp")
37 claim_ports(PORT)
38
39 version = json.loads(run_rsync('-VV', check=True, capture_output=True).stdout)
40 if 'zstd' not in version.get('compress_list', []):
41 test_skipped('this build does not include Zstandard')
42
43 base = SCRATCHDIR / 'daemon-zstd-thread-exhaustion'
44 rmtree(base)
45 mod = base / 'module'
46 mod.mkdir(parents=True)
47 # Incompressible output fills the socket while the client deliberately stops
48 # reading, keeping the per-connection process alive for a thread snapshot.
49 (mod / 'f').write_bytes(os.urandom(2 * 1024 * 1024))
50
51 log = base / 'rsyncd.log'
52 conf = base / 'rsyncd.conf'
53 conf.write_text(f"""\
54 pid file = {base}/rsyncd.pid
55 log file = {log}
56 use chroot = no
57
58 [mod]
59 path = {mod}
60 """)
61 start_rsyncd(conf, PORT)
62
63 c = rp.DaemonClient('127.0.0.1', PORT)
64 c.handshake(
65 'mod',
66 [
67 '--server', '--sender', '-e.LsfxCIu', '--compress',
68 '--compress-choice=zstd',
69 f'--compress-threads={REQUESTED_THREADS}', '.', 'mod/f',
70 ],
71 greeting_version=30,
72 )
73 entries = rp.sort_entries(c.recv_flist(preserve_links=False))
74 ndx = next(i for i, entry in enumerate(entries) if entry.name == b'f')
75 c.send_data(c.make_request(ndx) + c.w_ndx(rp.NDX_DONE))
76
77 # Identify the exact per-connection sender from the daemon log.
78 child_pid = None
79 for _ in range(100):
80 matches = re.findall(r'\[(\d+)\] rsync on mod/f',
81 log.read_text(errors='replace') if log.exists() else '')
82 if matches:
83 child_pid = int(matches[-1])
84 break
85 time.sleep(0.02)
86 if child_pid is None:
87 c.close()
88 test_fail('could not identify the per-connection daemon sender')
89
90
91 def thread_count(pid):
92 if sys.platform == 'darwin':
93 proc = subprocess.run(['ps', '-M', str(pid)], capture_output=True,
94 text=True)
95 return max(0, len(proc.stdout.splitlines()) - 1)
96 if sys.platform.startswith('linux'):
97 try:
98 status = open(f'/proc/{pid}/status').read()
99 except OSError:
100 return 0
101 match = re.search(r'^Threads:\s+(\d+)', status, re.M)
102 return int(match.group(1)) if match else 0
103 return -1
104
105
106 # Ask once whether this platform can be counted at all, BEFORE folding the
107 # answer into a max(): the -1 meaning "unsupported" never survives
108 # max(0, -1), so testing for it afterwards can never fire, and an uncountable
109 # platform instead looks like a sender that died before it could be read.
110 # Cygwin reported exactly that.
111 if thread_count(child_pid) < 0:
112 c.close()
113 test_skipped("counting a process's threads is unsupported on "
114 f'{sys.platform}, so a bound on the worker pool cannot be '
115 'observed here')
116
117 observed = 0
118 for _ in range(100):
119 observed = max(observed, thread_count(child_pid))
120 if observed >= REQUESTED_THREADS:
121 break
122 time.sleep(0.02)
123 c.close()
124
125 if observed == 0:
126 test_fail('the daemon sender exited before its thread count could be read')
127 if observed < 2:
128 # Only the main thread: this libzstd cannot make workers at all (built
129 # without multithreading, or a thread limit). The bound below would then
130 # hold for a reason that has nothing to do with the cap, so do not claim
131 # to have tested it.
132 test_skipped('this build creates no Zstandard worker threads, so a bound '
133 f'on them cannot be demonstrated (observed {observed})')
134 if observed > MAX_SAFE_THREADS:
135 test_fail(
136 f'one unauthenticated daemon client requested {REQUESTED_THREADS} '
137 f'Zstandard workers and the per-connection sender materialized '
138 f'{observed} threads'
139 )
140
141 print(f'daemon-zstd-thread-exhaustion: sender stayed at {observed} threads')