summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/accept_filter_probe.py110
-rw-r--r--tests/http_load.c148
-rw-r--r--tests/integration/.gitignore2
-rw-r--r--tests/integration/harness.py366
-rw-r--r--tests/integration/test_accesslist.py128
-rw-r--r--tests/integration/test_announce.py144
-rw-r--r--tests/integration/test_concurrency.py209
-rw-r--r--tests/integration/test_config.py72
-rw-r--r--tests/integration/test_dualstack.py89
-rw-r--r--tests/integration/test_dynamic_accesslist.py68
-rw-r--r--tests/integration/test_expiry.py44
-rw-r--r--tests/integration/test_fullscrape.py148
-rw-r--r--tests/integration/test_keepalive.py146
-rw-r--r--tests/integration/test_livesync.py240
-rw-r--r--tests/integration/test_shutdown.py58
-rw-r--r--tests/integration/test_statefile.py97
-rw-r--r--tests/integration/test_stats.py146
-rw-r--r--tests/integration/test_tcpworkers.py67
-rw-r--r--tests/integration/test_udp.py218
-rw-r--r--tests/integration/test_version.py36
-rw-r--r--tests/runner.c115
-rw-r--r--tests/stubs.c48
-rw-r--r--tests/sync_daemon.pl294
-rw-r--r--tests/syscount.c144
-rw-r--r--tests/t_accesslist.c120
-rw-r--r--tests/t_batch.c346
-rw-r--r--tests/t_buf.c203
-rw-r--r--tests/t_clean.c222
-rw-r--r--tests/t_event.c289
-rw-r--r--tests/t_fdstate.c230
-rw-r--r--tests/t_fmt.c106
-rw-r--r--tests/t_hex.c126
-rw-r--r--tests/t_iovec.c122
-rw-r--r--tests/t_ip.c215
-rw-r--r--tests/t_mutex.c136
-rw-r--r--tests/t_random.c112
-rw-r--r--tests/t_scan.c210
-rw-r--r--tests/t_socket.c416
-rw-r--r--tests/t_trackerlogic.c241
-rw-r--r--tests/t_urlencoded.c363
-rw-r--r--tests/t_vector.c308
-rw-r--r--tests/t_workqueue.c157
-rw-r--r--tests/test.c56
-rw-r--r--tests/test.h96
-rw-r--r--tests/testsuite2.sh22
-rw-r--r--tests/udp_load.c202
-rw-r--r--tests/udp_modes.c240
-rw-r--r--tests/udp_modes.py139
-rw-r--r--tests/udp_scaling.py159
-rw-r--r--tests/udp_wake_probe.c121
50 files changed, 8087 insertions, 7 deletions
diff --git a/tests/accept_filter_probe.py b/tests/accept_filter_probe.py
new file mode 100644
index 0000000..22f585a
--- /dev/null
+++ b/tests/accept_filter_probe.py
@@ -0,0 +1,110 @@
1"""What a deferred accept does to connections that never send anything.
2
3Those connections never reach opentracker, so its own client timeout cannot
4clean them up: whatever bound exists is the kernel's. This measures it, and
5then asks the question that follows from it -- whether enough of them keep
6the tracker from answering anybody else.
7
8 make opentracker
9 python3 tests/accept_filter_probe.py
10
11On FreeBSD the filter does nothing unless accf_data is loaded, so run it both
12ways to see whether the numbers differ:
13
14 kldload accf_data
15"""
16
17import os
18import socket
19import signal
20import subprocess
21import sys
22import tempfile
23import time
24import urllib.error
25import urllib.request
26
27TRACKER = os.environ.get("OPENTRACKER", "./opentracker")
28IDLE = int(os.environ.get("IDLE", "300"))
29PATIENCE = float(os.environ.get("PATIENCE", "90"))
30HASH = "".join("%%%02x" % b for b in range(1, 21))
31
32
33def start(port):
34 directory = tempfile.mkdtemp(prefix="ot-accf-")
35 with open(os.path.join(directory, "conf"), "w") as handle:
36 handle.write("listen.tcp 127.0.0.1:%d\nlisten.udp 127.0.0.1:%d\n" % (port, port))
37 log = open(os.path.join(directory, "log"), "w+b")
38 tracker = subprocess.Popen([TRACKER, "-f", os.path.join(directory, "conf")], stdout=log, stderr=log)
39 for _ in range(300):
40 try:
41 socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
42 return tracker, log
43 except OSError:
44 time.sleep(0.02)
45 tracker.kill()
46 raise SystemExit("tracker never listened on %d" % port)
47
48
49def announce(port, timeout=5):
50 """One ordinary request, so we can see whether the tracker still serves."""
51 started = time.time()
52 try:
53 urllib.request.urlopen(
54 "http://127.0.0.1:%d/announce?info_hash=%s&peer_id=-OT0001-probe0000001&port=6881&left=0" % (port, HASH),
55 timeout=timeout,
56 ).read()
57 return time.time() - started, None
58 except Exception as problem: # noqa: BLE001 - reported, not swallowed
59 return time.time() - started, problem
60
61
62def main():
63 port = int(os.environ.get("PORT", "28000"))
64 tracker, log = start(port)
65 try:
66 print(" how long a connection that says nothing is held")
67 quiet = socket.create_connection(("127.0.0.1", port), timeout=5)
68 quiet.settimeout(PATIENCE)
69 started = time.time()
70 try:
71 held = "dropped after %.1f s" % (time.time() - started) if quiet.recv(1) == b"" else "sent us something"
72 except socket.timeout:
73 held = "still open after %.0f s" % PATIENCE
74 except OSError as problem:
75 held = "ended after %.1f s: %s" % (time.time() - started, problem)
76 quiet.close()
77 print(" %s" % held)
78
79 print(" and whether %d of them keep anybody else out" % IDLE)
80 before, problem = announce(port)
81 print(" a request before: %.0f ms%s" % (before * 1000, "" if problem is None else " (%s)" % problem))
82
83 idlers = []
84 for _ in range(IDLE):
85 try:
86 idlers.append(socket.create_connection(("127.0.0.1", port), timeout=2))
87 except OSError as problem:
88 print(" could only open %d of them: %s" % (len(idlers), problem))
89 break
90 print(" holding %d connections that have sent nothing" % len(idlers))
91
92 during, problem = announce(port, timeout=10)
93 print(" a request during: %.0f ms%s" % (during * 1000, "" if problem is None else " REFUSED: %s" % problem))
94
95 for idler in idlers:
96 idler.close()
97 after, problem = announce(port)
98 print(" a request after: %.0f ms%s" % (after * 1000, "" if problem is None else " (%s)" % problem))
99 finally:
100 tracker.send_signal(signal.SIGINT)
101 try:
102 tracker.wait(timeout=10)
103 except subprocess.TimeoutExpired:
104 tracker.kill()
105 tracker.wait()
106 log.close()
107
108
109if __name__ == "__main__":
110 main()
diff --git a/tests/http_load.c b/tests/http_load.c
new file mode 100644
index 0000000..d04139b
--- /dev/null
+++ b/tests/http_load.c
@@ -0,0 +1,148 @@
1/* An HTTP load generator speaking the tracker's own protocol.
2
3 Each request is its own connection, which is what a BitTorrent client
4 normally does and what the tracker's hot path is built for: accept, read
5 one request, write a short reply, close. That makes this a measurement of
6 connection cost rather than of request cost, and connection cost is where
7 the tracker's system calls are.
8
9 cc -O2 -pthread -o http_load tests/http_load.c
10 ./http_load 127.0.0.1 6969 8 5 10000
11
12 Arguments: host, port, threads, seconds, and how many distinct torrents to
13 announce. Cycling a fixed set reaches a steady state where almost every
14 announce renews a peer that is already there, rather than measuring how
15 fast the tracker can insert torrents it will never see again. */
16
17#include <arpa/inet.h>
18#include <errno.h>
19#include <netinet/in.h>
20#include <netinet/tcp.h>
21#include <pthread.h>
22#include <stdatomic.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/socket.h>
28#include <sys/time.h>
29#include <unistd.h>
30
31static struct sockaddr_in g_tracker;
32static long g_torrents = 10000;
33static double g_seconds = 5;
34static _Atomic long long g_replies = 0;
35static _Atomic long long g_failed = 0;
36static _Atomic int g_running = 1;
37
38static double now_seconds(void) {
39 struct timeval tv;
40 gettimeofday(&tv, NULL);
41 return tv.tv_sec + tv.tv_usec / 1000000.0;
42}
43
44/* %xx for all twenty bytes, which is what a client sends and what the
45 tracker's urlencode reader has to walk */
46static void hash_of(long which, char *out) {
47 int i;
48
49 for (i = 0; i < 20; ++i) {
50 unsigned byte = (unsigned)((which >> ((i % 4) * 8)) & 0xff) ^ (unsigned)(i * 37);
51 sprintf(out + i * 3, "%%%02x", byte & 0xff);
52 }
53}
54
55static void *worker(void *args) {
56 long index = (long)(intptr_t)args;
57 long which = index * 7919;
58 char request[512], hash[61], reply[2048];
59
60 while (atomic_load_explicit(&g_running, memory_order_relaxed)) {
61 int sock = socket(AF_INET, SOCK_STREAM, 0);
62 int one = 1;
63 ssize_t got, sent;
64 size_t length;
65
66 if (sock < 0) {
67 atomic_fetch_add_explicit(&g_failed, 1, memory_order_relaxed);
68 continue;
69 }
70 setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
71
72 if (connect(sock, (struct sockaddr *)&g_tracker, sizeof(g_tracker)) < 0) {
73 atomic_fetch_add_explicit(&g_failed, 1, memory_order_relaxed);
74 close(sock);
75 continue;
76 }
77
78 hash_of(which, hash);
79 which = (which + 1) % g_torrents;
80 length = (size_t)snprintf(request, sizeof(request),
81 "GET /announce?info_hash=%s&peer_id=-OT0001-%06ld%06ld&port=%u&left=0 HTTP/1.0\r\n\r\n",
82 hash, index, which, (unsigned)(6881 + index));
83
84 for (sent = 0; (size_t)sent < length;) {
85 ssize_t wrote = write(sock, request + sent, length - (size_t)sent);
86 if (wrote <= 0)
87 break;
88 sent += wrote;
89 }
90
91 /* Read to end of reply, which the tracker marks by closing */
92 got = 0;
93 for (;;) {
94 ssize_t piece = read(sock, reply, sizeof(reply));
95 if (piece <= 0)
96 break;
97 got += piece;
98 }
99 close(sock);
100
101 if (got > 0)
102 atomic_fetch_add_explicit(&g_replies, 1, memory_order_relaxed);
103 else
104 atomic_fetch_add_explicit(&g_failed, 1, memory_order_relaxed);
105 }
106 return NULL;
107}
108
109int main(int argc, char **argv) {
110 const char *host = argc > 1 ? argv[1] : "127.0.0.1";
111 int port = argc > 2 ? atoi(argv[2]) : 6969;
112 long threads = argc > 3 ? atol(argv[3]) : 4;
113 pthread_t *pool;
114 double started, elapsed;
115 long i;
116
117 g_seconds = argc > 4 ? atof(argv[4]) : 5;
118 g_torrents = argc > 5 ? atol(argv[5]) : 10000;
119 if (g_torrents < 1)
120 g_torrents = 1;
121
122 memset(&g_tracker, 0, sizeof(g_tracker));
123 g_tracker.sin_family = AF_INET;
124 g_tracker.sin_port = htons((uint16_t)port);
125 if (inet_pton(AF_INET, host, &g_tracker.sin_addr) != 1) {
126 fprintf(stderr, "cannot parse address %s\n", host);
127 return 1;
128 }
129
130 pool = calloc((size_t)threads, sizeof(pthread_t));
131 started = now_seconds();
132 for (i = 0; i < threads; ++i)
133 pthread_create(pool + i, NULL, worker, (void *)(intptr_t)i);
134
135 while (now_seconds() - started < g_seconds)
136 usleep(20000);
137 atomic_store(&g_running, 0);
138
139 for (i = 0; i < threads; ++i)
140 pthread_join(pool[i], NULL);
141 elapsed = now_seconds() - started;
142
143 printf("%.0f replies/s (%lld replies, %lld failed, %ld threads, %.1f s)\n",
144 (double)atomic_load(&g_replies) / elapsed, (long long)atomic_load(&g_replies),
145 (long long)atomic_load(&g_failed), threads, elapsed);
146 free(pool);
147 return 0;
148}
diff --git a/tests/integration/.gitignore b/tests/integration/.gitignore
new file mode 100644
index 0000000..7a60b85
--- /dev/null
+++ b/tests/integration/.gitignore
@@ -0,0 +1,2 @@
1__pycache__/
2*.pyc
diff --git a/tests/integration/harness.py b/tests/integration/harness.py
new file mode 100644
index 0000000..f3cd0fa
--- /dev/null
+++ b/tests/integration/harness.py
@@ -0,0 +1,366 @@
1"""Starts a real opentracker and talks to it over the wire.
2
3Everything here drives the binary rather than the code, so these tests cover
4what the unit suite cannot reach: the event loop, the HTTP parser and the
5torrent store working together. Run against a sanitizer build and the tracker
6reports its own memory errors, which the teardown turns into test failures.
7"""
8
9import os
10import shutil
11import signal
12import socket
13import struct
14import subprocess
15import sys
16import tempfile
17import time
18import unittest
19import urllib.error
20import urllib.parse
21import urllib.request
22
23# groupip_1 in src/ot_livesync.c
24LIVESYNC_GROUP = "224.0.23.5"
25
26TRACKER = os.environ.get("OPENTRACKER", os.path.join(os.path.dirname(__file__), "..", "..", "opentracker.debug"))
27
28
29def bdecode(data):
30 """Enough bencode for what a tracker answers."""
31
32 def value(i):
33 if data[i : i + 1] == b"d":
34 i, out = i + 1, {}
35 while data[i : i + 1] != b"e":
36 i, key = value(i)
37 i, out[key] = value(i)
38 return i + 1, out
39 if data[i : i + 1] == b"l":
40 i, out = i + 1, []
41 while data[i : i + 1] != b"e":
42 i, item = value(i)
43 out.append(item)
44 return i + 1, out
45 if data[i : i + 1] == b"i":
46 end = data.index(b"e", i)
47 return end + 1, int(data[i + 1 : end])
48 colon = data.index(b":", i)
49 length = int(data[i:colon])
50 return colon + 1 + length, data[colon + 1 : colon + 1 + length]
51
52 return value(0)[1]
53
54
55def free_port(attempts=50):
56 """A port free for both protocols, because the tracker binds both.
57
58 Asking the kernel for a free tcp port says nothing about the udp port of
59 the same number, and anything on the machine holding that one makes the
60 tracker exit at once with "Address already in use".
61 """
62 for _ in range(attempts):
63 tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
64 udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
65 try:
66 tcp.bind(("127.0.0.1", 0))
67 udp.bind(("127.0.0.1", tcp.getsockname()[1]))
68 return tcp.getsockname()[1]
69 except OSError:
70 continue
71 finally:
72 tcp.close()
73 udp.close()
74 raise AssertionError("no port free for both tcp and udp after %d tries" % attempts)
75
76
77class Tracker:
78 """One tracker process, listening on loopback."""
79
80 def __init__(self, extra_config="", files=None, extra_args=()):
81 self.port = free_port()
82 # Only used by a config that asks for live sync, but allocated either
83 # way so {livesync_port} always resolves.
84 self.livesync_port = free_port()
85 self.dir = tempfile.mkdtemp(prefix="ot-integration-")
86 self.log = None
87 self.process = None
88 try:
89 for name, content in (files or {}).items():
90 with open(os.path.join(self.dir, name), "wb") as handle:
91 handle.write(content)
92 self.config = os.path.join(self.dir, "opentracker.conf")
93 with open(self.config, "w") as handle:
94 handle.write("listen.tcp 127.0.0.1:%d\n" % self.port)
95 handle.write("listen.udp 127.0.0.1:%d\n" % self.port)
96 handle.write(extra_config.replace("{dir}", self.dir).replace("{livesync_port}", str(self.livesync_port)))
97 self.log = open(os.path.join(self.dir, "tracker.log"), "w+b")
98 # Leak detection is left at the sanitizer's own default, which is on
99 # where LeakSanitizer exists and off where it does not. Asking for it
100 # by name makes the tracker refuse to start on macOS and FreeBSD.
101 environment = dict(os.environ, ASAN_OPTIONS="abort_on_error=0")
102 argv = [TRACKER, "-f", self.config] + [str(a) for a in extra_args]
103 self.process = subprocess.Popen(argv, stdout=self.log, stderr=self.log, env=environment)
104 self._wait_for_port()
105 except BaseException:
106 self._cleanup()
107 raise
108
109 def _cleanup(self):
110 """Close what we opened and take the scratch directory with it."""
111 if self.process is not None and self.process.poll() is None:
112 self.process.kill()
113 self.process.wait()
114 if self.log is not None:
115 self.log.close()
116 self.log = None
117 shutil.rmtree(self.dir, ignore_errors=True)
118
119 def _wait_for_port(self):
120 for _ in range(200):
121 if self.process.poll() is not None:
122 raise AssertionError("tracker exited at once:\n" + self.output())
123 try:
124 probe = socket.create_connection(("127.0.0.1", self.port), timeout=0.2)
125 probe.close()
126 return
127 except OSError:
128 time.sleep(0.05)
129 raise AssertionError("tracker never listened on %d:\n%s" % (self.port, self.output()))
130
131 def output(self):
132 if self.log is None:
133 return ""
134 self.log.flush()
135 self.log.seek(0)
136 return self.log.read().decode("utf-8", "replace")
137
138 def reload(self):
139 """SIGHUP makes the accesslist reader re-read its files, which also
140 empties the dynamic add/delete changesets."""
141 os.kill(self.process.pid, signal.SIGHUP)
142
143 def stop(self):
144 """Returns anything the tracker complained about on the way out.
145
146 The interrupt rather than a kill is what makes the leak check work at
147 all: LeakSanitizer reports from an exit handler, so a killed tracker
148 reports nothing and the suite passes over leaks it never looked for.
149 """
150 refused_to_exit = False
151 if self.process is not None and self.process.poll() is None:
152 self.process.send_signal(signal.SIGINT)
153 try:
154 self.process.wait(timeout=5)
155 except subprocess.TimeoutExpired:
156 self.process.kill()
157 self.process.wait()
158 refused_to_exit = True
159 complaints = [
160 line
161 for line in self.output().splitlines()
162 if "Sanitizer" in line or "runtime error" in line or line.startswith("ERROR")
163 ]
164 if refused_to_exit:
165 # Killing it throws away whatever the sanitizer had to say on the
166 # way out, so a test that ends this way has checked nothing.
167 complaints.append("the tracker did not exit within 5 s of SIGINT and had to be killed")
168 self._cleanup()
169 return complaints
170
171 # ----------------------------------------------------------- over http
172
173 def get(self, path, timeout=10):
174 return urllib.request.urlopen("http://127.0.0.1:%d%s" % (self.port, path), timeout=timeout).read()
175
176 def announce(self, info_hash, peer_id=b"-OT0001-aaaaaaaaaaaa", port=6881, left=0, **extra):
177 query = {
178 "info_hash": urllib.parse.quote_from_bytes(info_hash, safe=""),
179 "peer_id": urllib.parse.quote_from_bytes(peer_id, safe=""),
180 "port": port,
181 "left": left,
182 }
183 query.update(extra)
184 return bdecode(self.get("/announce?" + "&".join("%s=%s" % item for item in query.items())))
185
186 def scrape(self, info_hash):
187 return bdecode(self.get("/scrape?info_hash=" + urllib.parse.quote_from_bytes(info_hash, safe="")))
188
189 def stats(self, mode):
190 return self.get("/stats?mode=" + mode)
191
192 def get_with_headers(self, path, headers=None, timeout=10):
193 """The body and the response headers, for the compressed answers."""
194 request = urllib.request.Request("http://127.0.0.1:%d%s" % (self.port, path), headers=headers or {})
195 with urllib.request.urlopen(request, timeout=timeout) as response:
196 return response.read(), dict(response.headers)
197
198 def torrent_count(self):
199 return int(self.stats("torr").split()[0])
200
201 def livesync_send(self, payload, group=LIVESYNC_GROUP):
202 """Put a packet on the live sync group.
203
204 It has to go to the group rather than straight at the port: the
205 tracker binds two sockets there, the reader on the wildcard address
206 and the writer on the configured one, and the kernel gives a unicast
207 datagram to the more specific of the two, which nobody reads."""
208 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
209 try:
210 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton("127.0.0.1"))
211 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
212 sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)
213 sock.sendto(payload, (group, self.livesync_port))
214 finally:
215 sock.close()
216
217 def wait_until(self, predicate, timeout=5):
218 """A live sync packet is handled by another thread, so an effect of
219 one arrives some time after the send."""
220 deadline = time.time() + timeout
221 while time.time() < deadline:
222 if predicate():
223 return True
224 time.sleep(0.02)
225 return predicate()
226
227 # ------------------------------------------------------------ over udp
228
229 def udp_connect(self):
230 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
231 sock.settimeout(5)
232 sock.sendto(struct.pack(">QII", 0x41727101980, 0, 1), ("127.0.0.1", self.port))
233 answer = sock.recv(2048)
234 action, _, connection_id = struct.unpack(">IIQ", answer[:16])
235 assert action == 0, "udp connect answered action %d" % action
236 return sock, connection_id
237
238 def udp_announce(self, sock, connection_id, info_hash, left=0, event=0, port=6881, numwant=-1):
239 sock.sendto(
240 struct.pack(
241 ">QII20s20sQQQIIIiH", connection_id, 1, 2, info_hash, b"p" * 20, 0, left, 0, event, 0, 0, numwant, port
242 ),
243 ("127.0.0.1", self.port),
244 )
245 answer = sock.recv(2048)
246 action, _, interval, leechers, seeders = struct.unpack(">IIIII", answer[:20])
247 assert action == 1, "udp announce answered action %d" % action
248 return {"interval": interval, "leechers": leechers, "seeders": seeders, "peers": answer[20:]}
249
250 def udp_scrape(self, sock, connection_id, hashes):
251 """One (seeders, completed, leechers) triple per hash, in order."""
252 sock.sendto(struct.pack(">QII", connection_id, 2, 3) + b"".join(hashes), ("127.0.0.1", self.port))
253 answer = sock.recv(2048)
254 action, _ = struct.unpack(">II", answer[:8])
255 assert action == 2, "udp scrape answered action %d" % action
256 return [struct.unpack(">III", answer[8 + 12 * i : 20 + 12 * i]) for i in range(len(hashes))]
257
258 def connect(self):
259 """A connection the caller drives and closes."""
260 return Connection(self.port)
261
262 def udp_raw(self, payload, timeout=1.0):
263 """Sends a packet exactly as given. Returns the answer, or None if the
264 tracker chose to say nothing, which is how it treats a broken one."""
265 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
266 sock.settimeout(timeout)
267 try:
268 sock.sendto(payload, ("127.0.0.1", self.port))
269 try:
270 return sock.recv(2048)
271 except socket.timeout:
272 return None
273 finally:
274 sock.close()
275
276
277class Connection:
278 """One HTTP connection the caller keeps open, which urllib will not do.
279
280 Reads exactly one reply at a time, so a test can tell "the tracker
281 answered and kept the socket" from "the tracker answered and hung up"."""
282
283 def __init__(self, port, timeout=5):
284 self.sock = socket.create_connection(("127.0.0.1", port), timeout=timeout)
285 self.sock.settimeout(timeout)
286 self.buffer = b""
287
288 def send(self, path, connection="Keep-Alive", version="1.1"):
289 request = "GET %s HTTP/%s\r\nHost: tracker\r\n" % (path, version)
290 if connection is not None:
291 request += "Connection: %s\r\n" % connection
292 self.sock.sendall((request + "\r\n").encode())
293
294 def _fill(self):
295 chunk = self.sock.recv(65536)
296 if not chunk:
297 raise EOFError("the tracker closed the connection")
298 self.buffer += chunk
299
300 def reply(self):
301 """The one complete reply at the front of the stream, headers and body."""
302 while b"\r\n\r\n" not in self.buffer:
303 self._fill()
304 head, rest = self.buffer.split(b"\r\n\r\n", 1)
305 headers = {}
306 for line in head.split(b"\r\n")[1:]:
307 name, _, value = line.partition(b":")
308 headers[name.strip().lower()] = value.strip()
309
310 if headers.get(b"transfer-encoding") == b"chunked":
311 while not rest.endswith(b"0\r\n\r\n"):
312 self.buffer = head + b"\r\n\r\n" + rest
313 self._fill()
314 rest = self.buffer.split(b"\r\n\r\n", 1)[1]
315 body, self.buffer = rest, b""
316 else:
317 length = int(headers.get(b"content-length", b"0"))
318 while len(rest) < length:
319 self.buffer = head + b"\r\n\r\n" + rest
320 self._fill()
321 rest = self.buffer.split(b"\r\n\r\n", 1)[1]
322 body, self.buffer = rest[:length], rest[length:]
323 return head.split(b"\r\n")[0], headers, body
324
325 def is_open(self):
326 """True if the tracker is still holding the connection."""
327 try:
328 self.sock.settimeout(0.4)
329 return self.sock.recv(1) != b""
330 except socket.timeout:
331 return True
332 except OSError:
333 return False
334 finally:
335 try:
336 self.sock.settimeout(5)
337 except OSError:
338 pass
339
340 def close(self):
341 self.sock.close()
342
343
344class TrackerTestCase(unittest.TestCase):
345 """Gives every test its own tracker and fails it on any sanitizer output."""
346
347 config = ""
348 files = None
349
350 def setUp(self):
351 self.tracker = Tracker(self.config, self.files)
352
353 def tearDown(self):
354 # A connection the test closed is only reaped when the event loop gets
355 # round to it, and a cookie still held at exit reads as a leak. One
356 # more request puts us behind that work in the loop's queue.
357 try:
358 self.tracker.torrent_count()
359 except Exception:
360 pass
361 complaints = self.tracker.stop()
362 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
363
364 def hash_for(self, name):
365 """A distinct info hash per test, so tests cannot leak into each other."""
366 return (name.encode() + b"\0" * 20)[:20]
diff --git a/tests/integration/test_accesslist.py b/tests/integration/test_accesslist.py
new file mode 100644
index 0000000..3ed8ddf
--- /dev/null
+++ b/tests/integration/test_accesslist.py
@@ -0,0 +1,128 @@
1"""The blacklist, loaded from a file at startup.
2
3A blacklisted info hash must be refused at both the announce and the scrape
4entry, and the file parser has to cope with the shapes an operator actually
5produces: an empty file, and a last line with no newline after it.
6"""
7
8import os
9import struct
10import time
11import unittest
12
13from harness import Tracker, TrackerTestCase
14
15BLOCKED = b"\xb1" * 20
16ALLOWED = b"\xa1" * 20
17
18
19def listing(*hashes):
20 return b"".join(h.hex().upper().encode() + b"\n" for h in hashes)
21
22
23class Blacklist(TrackerTestCase):
24 config = "access.blacklist {dir}/blacklist\n"
25 files = {"blacklist": listing(BLOCKED)}
26
27 def test_a_blacklisted_hash_is_refused(self):
28 answer = self.tracker.announce(BLOCKED, port=6881, left=0)
29 self.assertIn(b"failure reason", answer)
30 self.assertIn(b"not authorized", answer[b"failure reason"])
31
32 def test_a_blacklisted_hash_never_becomes_a_torrent(self):
33 before = self.tracker.torrent_count()
34 self.tracker.announce(BLOCKED, port=6881, left=0)
35 self.assertEqual(self.tracker.torrent_count(), before, "the refused hash was stored anyway")
36
37 def test_any_other_hash_is_served(self):
38 answer = self.tracker.announce(ALLOWED, port=6881, left=0)
39 self.assertNotIn(b"failure reason", answer)
40 self.assertEqual(answer[b"complete"], 1)
41
42 def test_the_block_is_an_empty_announce_over_udp(self):
43 """An empty swarm with a long interval, not an error. BEP 15 binds a
44 client to the interval and says nothing about what to do with an
45 error, so an error puts the client on its own retry schedule, which
46 starts in the tens of seconds."""
47 sock, connection_id = self.tracker.udp_connect()
48 sock.close()
49 request = struct.pack(
50 ">QII20s20sQQQIIIiH", connection_id, 1, 7, BLOCKED, b"p" * 20, 0, 0, 0, 0, 0, 0, -1, 6881
51 )
52 answer = self.tracker.udp_raw(request)
53 self.assertIsNotNone(answer)
54 self.assertEqual(len(answer), 20, "header and counts, no peers behind them")
55 action, transaction, interval, leechers, seeders = struct.unpack(">IIIII", answer)
56 self.assertEqual(action, 1, "action 1 is the announce packet")
57 self.assertEqual(transaction, 7)
58 self.assertEqual((leechers, seeders), (0, 0))
59 self.assertGreaterEqual(interval, 60 * 60, "far enough out to be worth the trouble")
60 self.assertLessEqual(interval, 60 * 60 * 6, "not so far out that a client clamps it")
61
62 def test_a_blocked_hash_is_not_stored_when_it_arrives_over_udp(self):
63 sock, connection_id = self.tracker.udp_connect()
64 sock.close()
65 self.tracker.udp_raw(
66 struct.pack(">QII20s20sQQQIIIiH", connection_id, 1, 8, BLOCKED, b"p" * 20, 0, 0, 0, 0, 0, 0, -1, 6881)
67 )
68 self.assertEqual(self.tracker.torrent_count(), 0)
69
70
71class BlacklistWithoutTrailingNewline(TrackerTestCase):
72 """A single hash with no newline after it used to size the list at zero
73 and then write into it, which took the tracker down before it listened."""
74
75 config = "access.blacklist {dir}/blacklist\n"
76 files = {"blacklist": BLOCKED.hex().upper().encode()}
77
78 def test_the_last_line_counts_even_without_its_newline(self):
79 answer = self.tracker.announce(BLOCKED, port=6881, left=0)
80 self.assertIn(b"failure reason", answer)
81
82 def test_and_the_tracker_still_serves_everything_else(self):
83 self.assertEqual(self.tracker.announce(ALLOWED, port=6881, left=0)[b"complete"], 1)
84
85
86class EmptyBlacklist(TrackerTestCase):
87 config = "access.blacklist {dir}/blacklist\n"
88 files = {"blacklist": b""}
89
90 def test_an_empty_file_blocks_nothing_and_starts_cleanly(self):
91 self.assertEqual(self.tracker.announce(BLOCKED, port=6881, left=0)[b"complete"], 1)
92 self.assertEqual(self.tracker.announce(ALLOWED, port=6882, left=0)[b"complete"], 1)
93
94
95class MissingBlacklist(TrackerTestCase):
96 """The file is named but absent: the tracker warns and serves everything,
97 because it may be created later."""
98
99 config = "access.blacklist {dir}/absent\n"
100
101 def test_a_missing_file_blocks_nothing(self):
102 self.assertEqual(self.tracker.announce(BLOCKED, port=6881, left=0)[b"complete"], 1)
103
104
105class ListIsInPlaceBeforeTheStateFile(TrackerTestCase):
106 """The loader used to run in a thread of its own, so a state file read at
107 startup was checked against a list that was still empty."""
108
109 config = "access.blacklist {dir}/blacklist\n"
110 files = {"blacklist": listing(BLOCKED)}
111
112 def test_a_blacklisted_torrent_in_a_state_file_is_not_restored(self):
113 touched = int(time.time()) // 60 - 5
114 path = os.path.join(self.tracker.dir, "state")
115 with open(path, "w") as handle:
116 handle.write("%s:%d:7\n%s:%d:7\n" % (BLOCKED.hex(), touched, ALLOWED.hex(), touched))
117
118 restarted = Tracker(self.config, self.files, extra_args=["-l", path])
119 try:
120 self.assertNotIn(BLOCKED, restarted.scrape(BLOCKED)[b"files"], "the blacklist was not in place when the state file was read")
121 self.assertIn(ALLOWED, restarted.scrape(ALLOWED)[b"files"], "the state file was not read at all")
122 restarted.stop()
123 finally:
124 restarted._cleanup()
125
126
127if __name__ == "__main__":
128 unittest.main()
diff --git a/tests/integration/test_announce.py b/tests/integration/test_announce.py
new file mode 100644
index 0000000..2d21417
--- /dev/null
+++ b/tests/integration/test_announce.py
@@ -0,0 +1,144 @@
1"""What a peer's announce does to the swarm it joins."""
2
3import os
4import socket
5import sys
6import unittest
7
8sys.path.insert(0, os.path.dirname(__file__))
9from harness import TrackerTestCase
10
11
12def peers_of(answer, key=b"peers"):
13 """Compact peer list as a list of (address, port)."""
14 blob, out = answer.get(key, b""), []
15 size = 6 if key == b"peers" else 18
16 for offset in range(0, len(blob), size):
17 entry = blob[offset : offset + size]
18 address = socket.inet_ntop(socket.AF_INET if size == 6 else socket.AF_INET6, entry[:-2])
19 out.append((address, entry[-2] << 8 | entry[-1]))
20 return out
21
22
23class AnnounceLifetime(TrackerTestCase):
24 config = ""
25
26 def test_a_leecher_is_counted_as_incomplete(self):
27 info_hash = self.hash_for("leecher")
28 answer = self.tracker.announce(info_hash, left=100)
29 self.assertEqual(answer[b"complete"], 0)
30 self.assertEqual(answer[b"incomplete"], 1)
31
32 def test_no_bytes_left_means_seeding(self):
33 info_hash = self.hash_for("seeder")
34 answer = self.tracker.announce(info_hash, left=0)
35 self.assertEqual(answer[b"complete"], 1)
36 self.assertEqual(answer[b"incomplete"], 0)
37
38 def test_a_peer_that_finishes_moves_from_one_column_to_the_other(self):
39 info_hash = self.hash_for("finishes")
40 peer_id = b"-OT0001-finisher0001"
41 self.tracker.announce(info_hash, peer_id=peer_id, left=100)
42 self.assertEqual(self.tracker.announce(info_hash, peer_id=peer_id, left=100)[b"incomplete"], 1)
43
44 answer = self.tracker.announce(info_hash, peer_id=peer_id, left=0, event="completed")
45 self.assertEqual(answer[b"complete"], 1, "the peer should now count as a seeder")
46 self.assertEqual(answer[b"incomplete"], 0, "and no longer as a leecher")
47
48 def test_stopped_removes_the_peer(self):
49 info_hash = self.hash_for("stopped")
50 peer_id = b"-OT0001-leaves000001"
51 self.tracker.announce(info_hash, peer_id=peer_id, left=100)
52 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"incomplete"], 1)
53
54 self.tracker.announce(info_hash, peer_id=peer_id, left=100, event="stopped")
55 self.assertEqual(
56 self.tracker.scrape(info_hash)[b"files"][info_hash][b"incomplete"], 0, "the peer should be gone"
57 )
58
59 def test_the_same_peer_announcing_twice_is_still_one_peer(self):
60 info_hash = self.hash_for("twice")
61 peer_id = b"-OT0001-repeats00001"
62 for _ in range(5):
63 answer = self.tracker.announce(info_hash, peer_id=peer_id, left=100)
64 self.assertEqual(answer[b"incomplete"], 1, "re-announcing must not duplicate the peer")
65
66 def test_a_peer_is_its_address_and_port_not_its_peer_id(self):
67 """Two announces from one address and port are one peer, whatever
68 peer_id they carry, because that pair is the whole identity."""
69 info_hash = self.hash_for("identity")
70 self.tracker.announce(info_hash, peer_id=b"-OT0001-a00000000001", port=6881, left=100)
71 answer = self.tracker.announce(info_hash, peer_id=b"-OT0001-b00000000002", port=6881, left=100)
72 self.assertEqual(answer[b"incomplete"], 1, "same address and port, so still one peer")
73
74 answer = self.tracker.announce(info_hash, peer_id=b"-OT0001-c00000000003", port=6882, left=100)
75 self.assertEqual(answer[b"incomplete"], 2, "a different port makes a different peer")
76
77 def test_a_downloaded_count_is_kept(self):
78 info_hash = self.hash_for("downloaded")
79 self.tracker.announce(info_hash, port=7001, left=0, event="completed")
80 self.tracker.announce(info_hash, port=7002, left=0, event="completed")
81 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"downloaded"], 2)
82
83 def test_a_peer_is_given_the_whole_swarm_including_itself(self):
84 """opentracker does not filter the announcing peer out of its own
85 answer. Clients are expected to ignore themselves."""
86 info_hash = self.hash_for("sees")
87 self.tracker.announce(info_hash, port=1111, left=100)
88 answer = self.tracker.announce(info_hash, port=2222, left=100)
89
90 ports = sorted(port for _, port in peers_of(answer))
91 self.assertEqual(ports, [1111, 2222])
92
93 def test_an_unknown_torrent_scrapes_as_empty(self):
94 answer = self.tracker.scrape(self.hash_for("never-seen"))
95 self.assertEqual(answer[b"files"], {}, "a torrent nobody announced has no entry")
96
97
98class AnnounceRejects(TrackerTestCase):
99 def assert_rejected(self, query):
100 import urllib.error
101
102 with self.assertRaises(urllib.error.HTTPError) as caught:
103 self.tracker.get("/announce?" + query)
104 self.assertEqual(caught.exception.code, 400)
105
106 def test_a_short_info_hash_is_rejected(self):
107 self.assert_rejected("info_hash=tooshort&peer_id=" + "b" * 20 + "&port=6881&left=0")
108
109 def test_a_missing_info_hash_answers_a_failure_reason(self):
110 """Not a 400: the tracker answers 200 with a bencoded complaint, so
111 that a client shows the message to its user."""
112 from harness import bdecode
113
114 answer = bdecode(self.tracker.get("/announce?peer_id=" + "b" * 20 + "&port=6881&left=0"))
115 self.assertIn(b"failure reason", answer)
116 self.assertIn(b"info_hash", answer[b"failure reason"])
117
118 def test_a_port_out_of_range_is_rejected(self):
119 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=65536&left=0")
120
121 def test_a_negative_port_is_rejected(self):
122 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=-1&left=0")
123
124 def test_a_port_that_is_not_a_number_is_rejected(self):
125 self.assert_rejected("info_hash=" + "a" * 20 + "&peer_id=" + "b" * 20 + "&port=abc&left=0")
126
127 def test_an_ip_that_fills_the_reply_buffer_is_refused(self):
128 """The value is decoded into the reply buffer and then terminated, so
129 the longest one that fits has to leave room for the terminator. 8096
130 bytes is what lies between where it is decoded and the buffer's end."""
131 connection = self.tracker.connect()
132 try:
133 connection.sock.sendall(b"GET /a?ip=" + b"1" * 8096 + b"\n\n")
134 status, _, _ = connection.reply()
135 self.assertTrue(status.startswith(b"HTTP/1.0 400"), status)
136 finally:
137 connection.close()
138
139 def test_two_info_hashes_are_rejected(self):
140 self.assert_rejected("info_hash=" + "a" * 20 + "&info_hash=" + "c" * 20 + "&peer_id=" + "b" * 20 + "&port=6881&left=0")
141
142
143if __name__ == "__main__":
144 unittest.main()
diff --git a/tests/integration/test_concurrency.py b/tests/integration/test_concurrency.py
new file mode 100644
index 0000000..528992d
--- /dev/null
+++ b/tests/integration/test_concurrency.py
@@ -0,0 +1,209 @@
1"""Several clients at once.
2
3The rest of the suite talks to the tracker one request at a time, which
4leaves the worker threads and the bucket locks almost untouched. These reach
5them.
6
7What they assert is weak on purpose. A lost update needs two threads inside
8the same few instructions, which is rare enough that these tests pass
9against code that has the race: measured, eight runs in a row. Their worth
10is that they make the racing code run at all, so that "make check-tsan"
11has something to report. Reaching the code and judging it are two jobs, and
12these only do the first.
13"""
14
15import struct
16import threading
17import unittest
18
19from harness import TrackerTestCase, bdecode
20
21THREADS = 8
22PER_THREAD = 40
23
24
25def run_threads(target, count=THREADS):
26 errors = []
27
28 def guarded(index):
29 try:
30 target(index)
31 except Exception as exception: # noqa: BLE001 - reported, not swallowed
32 errors.append("thread %d: %r" % (index, exception))
33
34 threads = [threading.Thread(target=guarded, args=(i,)) for i in range(count)]
35 for thread in threads:
36 thread.start()
37 for thread in threads:
38 thread.join()
39 return errors
40
41
42class ConcurrentAnnounce(TrackerTestCase):
43 def test_every_peer_of_one_swarm_arrives(self):
44 """One torrent, one bucket, every thread contending for its lock."""
45 info_hash = self.hash_for("concurrent-one")
46
47 def announce(index):
48 for i in range(PER_THREAD):
49 self.tracker.announce(info_hash, port=10000 + index * PER_THREAD + i, left=0)
50
51 self.assertEqual(run_threads(announce), [])
52 answer = self.tracker.scrape(info_hash)
53 self.assertEqual(answer[b"files"][info_hash][b"complete"], THREADS * PER_THREAD)
54
55 def test_inserts_spread_over_buckets(self):
56 """Every thread inserts into a different bucket, so the bucket locks
57 serialise nothing between them, and the counter they all adjust is
58 the one global the locks do not cover. Under check-tsan this is what
59 names mutex_bucket_unlock if that counter stops being atomic."""
60
61 def announce(index):
62 for i in range(PER_THREAD):
63 self.tracker.announce(struct.pack(">HH", index, i) + b"\0" * 16, port=11000 + i, left=0)
64
65 self.assertEqual(run_threads(announce), [])
66 self.assertEqual(self.tracker.torrent_count(), THREADS * PER_THREAD)
67
68 def test_a_swarm_that_fills_and_empties_at_once(self):
69 """Inserts and removals racing in the same buckets."""
70 info_hash = self.hash_for("concurrent-churn")
71 for port in range(12000, 12000 + THREADS * PER_THREAD):
72 self.tracker.announce(info_hash, port=port, left=0)
73
74 def churn(index):
75 base = 12000 + index * PER_THREAD
76 for i in range(PER_THREAD):
77 self.tracker.announce(info_hash, port=base + i, left=0, event="stopped")
78 self.tracker.announce(info_hash, port=base + i, left=100)
79
80 self.assertEqual(run_threads(churn), [])
81 answer = self.tracker.scrape(info_hash)
82 self.assertEqual(answer[b"files"][info_hash][b"incomplete"], THREADS * PER_THREAD)
83 self.assertEqual(answer[b"files"][info_hash][b"complete"], 0)
84
85
86class ConcurrentMixedBearers(TrackerTestCase):
87 def test_tcp_and_udp_reach_the_same_swarm(self):
88 info_hash = self.hash_for("concurrent-mixed")
89
90 def over_tcp(index):
91 for i in range(PER_THREAD):
92 self.tracker.announce(info_hash, port=13000 + index * PER_THREAD + i, left=0)
93
94 def over_udp(index):
95 sock, connection_id = self.tracker.udp_connect()
96 try:
97 for i in range(PER_THREAD):
98 self.tracker.udp_announce(
99 sock, connection_id, info_hash, left=0, port=14000 + index * PER_THREAD + i
100 )
101 finally:
102 sock.close()
103
104 errors = []
105 threads = [threading.Thread(target=lambda i=i: over_tcp(i)) for i in range(THREADS // 2)]
106 threads += [threading.Thread(target=lambda i=i: over_udp(i)) for i in range(THREADS // 2)]
107 for thread in threads:
108 thread.start()
109 for thread in threads:
110 thread.join()
111
112 self.assertEqual(errors, [])
113 answer = self.tracker.scrape(info_hash)
114 self.assertEqual(answer[b"files"][info_hash][b"complete"], THREADS * PER_THREAD)
115
116
117class ConcurrentWorkerTasks(TrackerTestCase):
118 def test_full_scrapes_while_the_swarm_moves(self):
119 """The full scrape runs on a worker thread, walking the same buckets
120 the announces are changing."""
121 for i in range(200):
122 self.tracker.announce(struct.pack(">I", i) + b"\0" * 16, port=15000 + i, left=0)
123
124 def announce(index):
125 for i in range(PER_THREAD):
126 self.tracker.announce(struct.pack(">I", i) + b"\0" * 16, port=16000 + index * PER_THREAD + i, left=0)
127
128 def scrape(index):
129 for _ in range(6):
130 answer = bdecode(self.tracker.get("/scrape"))
131 for counts in answer[b"files"].values():
132 if counts[b"complete"] < 0 or counts[b"incomplete"] < 0:
133 raise AssertionError("negative count in a full scrape: %r" % counts)
134
135 threads = [threading.Thread(target=announce, args=(i,)) for i in range(THREADS // 2)]
136 threads += [threading.Thread(target=scrape, args=(i,)) for i in range(2)]
137 for thread in threads:
138 thread.start()
139 for thread in threads:
140 thread.join()
141
142 self.assertEqual(self.tracker.torrent_count(), 200)
143
144 def test_stats_while_the_swarm_moves(self):
145 def announce(index):
146 for i in range(PER_THREAD):
147 self.tracker.announce(struct.pack(">HH", index, i) + b"\0" * 16, port=17000 + i, left=i % 2)
148
149 def poll(index):
150 for _ in range(10):
151 for mode in ("everything", "top100", "peer", "torr"):
152 self.tracker.stats(mode)
153
154 threads = [threading.Thread(target=announce, args=(i,)) for i in range(THREADS // 2)]
155 threads += [threading.Thread(target=poll, args=(i,)) for i in range(2)]
156 for thread in threads:
157 thread.start()
158 for thread in threads:
159 thread.join()
160
161 self.assertEqual(self.tracker.torrent_count(), (THREADS // 2) * PER_THREAD)
162
163
164class CountersAcrossContexts(TrackerTestCase):
165 """With udp workers configured, every one of them counts into a block of
166 its own, and the figure reported is those blocks added up. A registry
167 that lost a block, or a worker that wrote into somebody else's, would
168 show here and nowhere else in the suite: without this directive udp is
169 served by the main loop, which is a single context."""
170
171 config = "listen.udp.workers 4\n"
172
173 def test_the_udp_count_is_the_sum_of_every_worker(self):
174 before = int(self.tracker.stats("udp4").splitlines()[0])
175
176 packets = 0
177 for round_ in range(6):
178 sock, connection_id = self.tracker.udp_connect() # one packet
179 packets += 1
180 try:
181 for i in range(10):
182 self.tracker.udp_announce(sock, connection_id, self.hash_for("ctx%d" % i), left=0)
183 packets += 1
184 finally:
185 sock.close()
186
187 after = int(self.tracker.stats("udp4").splitlines()[0])
188 self.assertEqual(after - before, packets, "every packet counted exactly once")
189
190 def test_announces_from_several_workers_reach_one_swarm(self):
191 info_hash = self.hash_for("ctx-swarm")
192
193 def announce(index):
194 sock, connection_id = self.tracker.udp_connect()
195 try:
196 for i in range(PER_THREAD):
197 self.tracker.udp_announce(
198 sock, connection_id, info_hash, left=0, port=18000 + index * PER_THREAD + i
199 )
200 finally:
201 sock.close()
202
203 self.assertEqual(run_threads(announce, 4), [])
204 answer = self.tracker.scrape(info_hash)
205 self.assertEqual(answer[b"files"][info_hash][b"complete"], 4 * PER_THREAD)
206
207
208if __name__ == "__main__":
209 unittest.main()
diff --git a/tests/integration/test_config.py b/tests/integration/test_config.py
new file mode 100644
index 0000000..fe5cf9d
--- /dev/null
+++ b/tests/integration/test_config.py
@@ -0,0 +1,72 @@
1"""Settings the tracker has to accept, and still work with.
2
3An unrecognised key only warns, so coming up proves nothing on its own and a
4test that cares has to look at what the tracker said. A key that is
5recognised but cannot be parsed is another matter, and for the listen
6statements it stops the tracker.
7"""
8
9import unittest
10
11from harness import Tracker, TrackerTestCase, free_port
12
13
14class TcpWorkers(TrackerTestCase):
15 config = "listen.tcp.workers 2\n"
16
17 def test_the_tracker_serves_with_tcp_workers_asked_for(self):
18 self.assertEqual(self.tracker.announce(self.hash_for("tcpworkers"))[b"complete"], 1)
19 self.assertNotIn("Unhandled line", self.tracker.output())
20
21
22class WorkersOnAListenStatement(unittest.TestCase):
23 def test_a_listen_statement_may_carry_a_worker_count(self):
24 """The option is read off the statement rather than inherited."""
25 second = free_port()
26 tracker = Tracker("listen.tcp 127.0.0.1:%d workers=2\n" % second)
27 try:
28 self.assertEqual(tracker.announce(b"listenopts\0\0\0\0\0\0\0\0\0\0")[b"complete"], 1)
29 complaints = tracker.stop()
30 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
31 finally:
32 tracker._cleanup()
33
34
35class AListenLineThatDoesNotParse(unittest.TestCase):
36 """Warning and carrying on left a tracker that had been told where to
37 listen coming up on its default instead, which is every interface."""
38
39 def refuses(self, line):
40 with self.assertRaises(AssertionError) as caught:
41 Tracker(line)
42 return str(caught.exception)
43
44 def test_an_address_that_is_not_one_stops_the_tracker(self):
45 self.assertIn("want an address", self.refuses("listen.tcp 10.0.0.300:7999\n"))
46
47 def test_so_does_a_port_out_of_range(self):
48 self.assertIn("want an address", self.refuses("listen.udp 127.0.0.1:99999\n"))
49
50 def test_so_does_an_option_it_does_not_know(self):
51 self.assertIn("want an address", self.refuses("listen.tcp 127.0.0.1:7999 wokers=2\n"))
52
53
54class EmptyTorrentTimeout(TrackerTestCase):
55 config = "tracker.empty_torrent_timeout 60\n"
56
57 def test_the_tracker_accepts_the_option_and_serves(self):
58 self.assertEqual(self.tracker.announce(self.hash_for("emptyto"))[b"complete"], 1)
59 self.assertNotIn("Unhandled line", self.tracker.output())
60 self.assertNotIn("Parse error", self.tracker.output())
61
62
63class EmptyTorrentTimeoutThatDoesNotParse(unittest.TestCase):
64 def test_a_non_numeric_value_warns_but_the_tracker_serves(self):
65 """A scalar that will not parse warns and is ignored, unlike a listen
66 line, which stops the tracker."""
67 tracker = Tracker("tracker.empty_torrent_timeout later\n")
68 try:
69 self.assertEqual(tracker.announce(b"emptytobad\0\0\0\0\0\0\0\0\0\0")[b"complete"], 1)
70 self.assertIn("Parse error", tracker.output())
71 finally:
72 tracker._cleanup()
diff --git a/tests/integration/test_dualstack.py b/tests/integration/test_dualstack.py
new file mode 100644
index 0000000..cd5ba7d
--- /dev/null
+++ b/tests/integration/test_dualstack.py
@@ -0,0 +1,89 @@
1"""A tracker serving both families from one socket.
2
3These need WANT_IP_FROM_QUERY_STRING so a peer's address can be dictated
4rather than being whatever loopback the test happened to come from.
5"""
6
7import os
8import socket
9import sys
10import unittest
11
12sys.path.insert(0, os.path.dirname(__file__))
13from harness import TrackerTestCase
14
15
16def addresses(answer, key):
17 blob, out = answer.get(key, b""), []
18 size = 6 if key == b"peers" else 18
19 for offset in range(0, len(blob), size):
20 entry = blob[offset : offset + size]
21 out.append(socket.inet_ntop(socket.AF_INET if size == 6 else socket.AF_INET6, entry[:-2]))
22 return out
23
24
25class DualStack(TrackerTestCase):
26 def test_an_ipv4_peer_lands_in_the_v4_list(self):
27 info_hash = self.hash_for("v4only")
28 self.tracker.announce(info_hash, ip="10.1.2.3", port=5001, left=100)
29 answer = self.tracker.announce(info_hash, ip="10.1.2.4", port=5002, left=100)
30
31 self.assertEqual(sorted(addresses(answer, b"peers")), ["10.1.2.3", "10.1.2.4"])
32 self.assertEqual(addresses(answer, b"peers6"), [], "no v6 peer was announced")
33
34 def test_an_ipv6_peer_lands_in_the_v6_list(self):
35 info_hash = self.hash_for("v6only")
36 self.tracker.announce(info_hash, ip="2001:db8::1", port=5001, left=100)
37 answer = self.tracker.announce(info_hash, ip="2001:db8::2", port=5002, left=100)
38
39 self.assertEqual(sorted(addresses(answer, b"peers6")), ["2001:db8::1", "2001:db8::2"])
40 self.assertEqual(addresses(answer, b"peers"), [], "no v4 peer was announced")
41
42 def test_the_two_families_are_kept_apart_but_both_returned(self):
43 info_hash = self.hash_for("both")
44 self.tracker.announce(info_hash, ip="10.9.9.9", port=6001, left=100)
45 answer = self.tracker.announce(info_hash, ip="2001:db8::9", port=6002, left=100)
46
47 self.assertEqual(addresses(answer, b"peers"), ["10.9.9.9"])
48 self.assertEqual(addresses(answer, b"peers6"), ["2001:db8::9"])
49
50 def test_a_v4_mapped_address_is_the_same_peer_as_the_plain_one(self):
51 info_hash = self.hash_for("v4mapped")
52 self.tracker.announce(info_hash, ip="10.5.5.5", port=7001, left=100)
53 answer = self.tracker.announce(info_hash, ip="::ffff:10.5.5.5", port=7001, left=100)
54
55 self.assertEqual(answer[b"incomplete"], 1, "the same address written two ways is one peer")
56 self.assertEqual(addresses(answer, b"peers"), ["10.5.5.5"], "and it is held as v4")
57
58 def test_the_two_families_count_into_one_swarm(self):
59 info_hash = self.hash_for("counts")
60 self.tracker.announce(info_hash, ip="10.4.4.4", port=8001, left=0)
61 answer = self.tracker.announce(info_hash, ip="2001:db8::4", port=8002, left=100)
62
63 self.assertEqual(answer[b"complete"], 1)
64 self.assertEqual(answer[b"incomplete"], 1)
65 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"complete"], 1)
66
67 def test_stopped_removes_only_the_family_it_came_from(self):
68 info_hash = self.hash_for("stopfamily")
69 self.tracker.announce(info_hash, ip="10.3.3.3", port=9001, left=100)
70 self.tracker.announce(info_hash, ip="2001:db8::3", port=9002, left=100)
71 self.tracker.announce(info_hash, ip="10.3.3.3", port=9001, left=100, event="stopped")
72
73 answer = self.tracker.announce(info_hash, ip="2001:db8::33", port=9003, left=100)
74 self.assertEqual(addresses(answer, b"peers"), [], "the v4 peer left")
75 self.assertIn("2001:db8::3", addresses(answer, b"peers6"), "the v6 one stayed")
76
77 def test_a_malformed_address_is_rejected(self):
78 import urllib.error
79
80 # The whole field has to be the address: a prefix that happens to
81 # parse would quietly record the peer somewhere else
82 for bad in ("999.1.2.3", "nonsense", "2001:db8:::1", "10.1.2.3.4", "10.1.2.3junk", "2001:db8::1%eth0"):
83 with self.assertRaises(urllib.error.HTTPError, msg="ip=%s should be refused" % bad) as caught:
84 self.tracker.announce(self.hash_for("badip"), ip=bad, port=6881, left=0)
85 self.assertEqual(caught.exception.code, 400)
86
87
88if __name__ == "__main__":
89 unittest.main()
diff --git a/tests/integration/test_dynamic_accesslist.py b/tests/integration/test_dynamic_accesslist.py
new file mode 100644
index 0000000..2072f5e
--- /dev/null
+++ b/tests/integration/test_dynamic_accesslist.py
@@ -0,0 +1,68 @@
1"""Hashes added to and removed from the blacklist while the tracker runs.
2
3The two FIFOs are read by threads of their own, which is also what makes
4this the test that drives those threads through a shutdown.
5"""
6
7import os
8import time
9import unittest
10
11from harness import TrackerTestCase
12
13BLOCKED = bytes(range(1, 21))
14
15
16def as_hex(info_hash):
17 return "".join("%02x" % b for b in info_hash)
18
19
20class DynamicAccesslist(TrackerTestCase):
21 config = ("access.blacklist {dir}/blacklist\n"
22 "access.fifo_add {dir}/add.fifo\n"
23 "access.fifo_delete {dir}/delete.fifo\n")
24 files = {"blacklist": b""}
25
26 def feed(self, name, info_hash):
27 """Writing to the FIFO blocks until the reader has it, so this also
28 tells us the thread is alive."""
29 with open(os.path.join(self.tracker.dir, name), "w") as fifo:
30 fifo.write("%s added by a test\n" % as_hex(info_hash))
31
32 def wait_for(self, info_hash, blocked, patience=5.0):
33 """The reader thread picks the hash up on its own schedule, so this
34 waits for the answer to change rather than assuming it already has."""
35 deadline = time.time() + patience
36 while time.time() < deadline:
37 answer = self.tracker.announce(info_hash)
38 if (b"failure reason" in answer) == blocked:
39 return True
40 time.sleep(0.05)
41 return False
42
43 def test_a_hash_added_after_a_reload_is_blocked(self):
44 """A reload leaves the add changeset an empty list rather than an
45 absent one. Adding against it walked a null array; the hash must be
46 blocked and the tracker must stay up."""
47 OTHER = bytes(range(21, 41))
48 self.feed("add.fifo", BLOCKED)
49 self.assertTrue(self.wait_for(BLOCKED, blocked=True), "the first hash was never blocked")
50
51 # The reload empties the add changeset, which unblocks the first hash.
52 # Wait for that before adding the second, so it lands on the empty list
53 # the bug walked, not on the changeset before the reload has cleared it.
54 self.tracker.reload()
55 self.assertTrue(self.wait_for(BLOCKED, blocked=False), "the reload never emptied the changeset")
56
57 self.feed("add.fifo", OTHER)
58 self.assertTrue(self.wait_for(OTHER, blocked=True), "the hash added after the reload was never blocked")
59 # tearDown's stop() surfaces any sanitizer complaint on the way out.
60
61 def test_a_hash_can_be_blocked_and_released_while_running(self):
62 self.assertNotIn(b"failure reason", self.tracker.announce(BLOCKED))
63
64 self.feed("add.fifo", BLOCKED)
65 self.assertTrue(self.wait_for(BLOCKED, blocked=True), "the hash was never blocked")
66
67 self.feed("delete.fifo", BLOCKED)
68 self.assertTrue(self.wait_for(BLOCKED, blocked=False), "the hash was never released")
diff --git a/tests/integration/test_expiry.py b/tests/integration/test_expiry.py
new file mode 100644
index 0000000..5e6dc0a
--- /dev/null
+++ b/tests/integration/test_expiry.py
@@ -0,0 +1,44 @@
1"""What the expiry sweep finds, and what it must not find.
2
3A plain request is answered and the connection closed by http_close, not by
4the sweep. If that path left the descriptor's slot behind, the sweep would
5walk into it once the client timeout had passed and free a cookie that is
6already gone; the sanitizer build reports that and teardown turns it into a
7failure.
8
9Both halves share one tracker and one wait, because the wait is the whole
10cost of the test.
11
12The two numbers below mirror OT_CLIENT_TIMEOUT and
13OT_CLIENT_TIMEOUT_CHECKINTERVAL in FEATURES_integration.
14"""
15
16import socket
17import time
18import unittest
19
20from harness import TrackerTestCase
21
22CLIENT_TIMEOUT = 5
23CHECK_INTERVAL = 1
24
25
26class ExpirySweep(TrackerTestCase):
27 def test_the_sweep_takes_the_idle_and_leaves_the_answered(self):
28 idle = socket.create_connection(("127.0.0.1", self.tracker.port), timeout=5)
29 try:
30 # Enough for a kernel that holds a connection back until data
31 # arrives to hand it over, and far too little to be answered, so
32 # the tracker has accepted it and is waiting for the rest
33 idle.sendall(b"GET /ann")
34
35 self.assertEqual(self.tracker.announce(self.hash_for("expiry-sweep"))[b"complete"], 1)
36
37 time.sleep(CLIENT_TIMEOUT + 3 * CHECK_INTERVAL)
38
39 self.assertEqual(self.tracker.torrent_count(), 1, "the tracker stopped serving while sweeping")
40
41 idle.settimeout(5)
42 self.assertEqual(idle.recv(64), b"", "a connection that went quiet mid-request was not swept")
43 finally:
44 idle.close()
diff --git a/tests/integration/test_fullscrape.py b/tests/integration/test_fullscrape.py
new file mode 100644
index 0000000..45b3ffb
--- /dev/null
+++ b/tests/integration/test_fullscrape.py
@@ -0,0 +1,148 @@
1"""The full scrape, in every format the tracker offers.
2
3Each format is a separate writer, and they differ in more than cosmetics:
4one is binary, one is bencoded, three are line based and one dumps the
5tracker's own state for a restart. A worker thread produces them in chunks,
6so these also exercise the chunked transfer the ordinary replies never take.
7"""
8
9import gzip
10import struct
11import time
12import unittest
13
14from harness import TrackerTestCase, bdecode
15
16HEX = b"0123456789ABCDEF"
17
18
19class FullScrape(TrackerTestCase):
20 def setUp(self):
21 TrackerTestCase.setUp(self)
22 self.seeding = self.hash_for("fsA")
23 self.leeching = self.hash_for("fsB")
24 self.tracker.announce(self.seeding, port=6001, left=0)
25 self.tracker.announce(self.leeching, port=6002, left=4096)
26
27 def scrape_all(self, query, headers=None):
28 body, head = self.tracker.get_with_headers(query, headers)
29 if head.get("Content-Encoding") == "gzip":
30 body = gzip.decompress(body)
31 return body
32
33 # --------------------------------------------------------- bencoded
34
35 def test_a_bare_scrape_returns_every_torrent(self):
36 answer = bdecode(self.scrape_all("/scrape"))
37 self.assertIn(self.seeding, answer[b"files"])
38 self.assertIn(self.leeching, answer[b"files"])
39 self.assertEqual(answer[b"files"][self.seeding][b"complete"], 1)
40 self.assertEqual(answer[b"files"][self.leeching][b"incomplete"], 1)
41
42 def test_the_bencoded_format_matches_the_bare_scrape(self):
43 self.assertEqual(bdecode(self.scrape_all("/stats?mode=tpbs&format=ben")), bdecode(self.scrape_all("/scrape")))
44
45 def test_a_full_scrape_can_be_gzipped(self):
46 plain = self.scrape_all("/scrape")
47 body, head = self.tracker.get_with_headers("/scrape", {"Accept-Encoding": "gzip"})
48 self.assertEqual(head.get("Content-Encoding"), "gzip")
49 self.assertEqual(gzip.decompress(body), plain)
50
51 # ----------------------------------------------------------- binary
52
53 def test_the_binary_format_is_a_hash_and_two_counts(self):
54 body = self.scrape_all("/stats?mode=tpbs&format=bin")
55 self.assertEqual(len(body) % 28, 0, "twenty byte hash plus two counts")
56 entries = {body[i : i + 20]: struct.unpack(">II", body[i + 20 : i + 28]) for i in range(0, len(body), 28)}
57 self.assertEqual(entries[self.seeding], (1, 0), "one seeder, no leechers")
58 self.assertEqual(entries[self.leeching], (0, 1), "no seeders, one leecher")
59
60 # ------------------------------------------------------- line based
61
62 def entries_from_lines(self, body):
63 return {line.split(b":")[0]: line.split(b":")[1:] for line in body.splitlines() if line}
64
65 def test_the_text_format_is_hex_colon_seeders_colon_leechers(self):
66 entries = self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txt"))
67 self.assertEqual(entries[self.seeding.hex().upper().encode()], [b"1", b"0"])
68 self.assertEqual(entries[self.leeching.hex().upper().encode()], [b"0", b"1"])
69
70 def test_the_text_plus_format_adds_the_completed_count(self):
71 entries = self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txtp"))
72 self.assertEqual(entries[self.seeding.hex().upper().encode()], [b"1", b"0", b"0"])
73
74 def test_the_urlencoded_format_escapes_the_hash(self):
75 body = self.scrape_all("/stats?mode=tpbs&format=url")
76 lines = [line for line in body.splitlines() if line]
77 self.assertEqual(len(lines), 2)
78 for line in lines:
79 escaped = line.rsplit(b":", 2)[0]
80 self.assertIn(b"%", escaped, "these hashes are mostly unprintable bytes")
81
82 def test_the_state_dump_carries_a_stamp_rather_than_a_peer_count(self):
83 """What a restart reads back. The second column is the minute the
84 torrent was last touched and not a count of anybody, by the wall
85 clock, which is the only one two runs of the tracker agree on."""
86 entries = self.entries_from_lines(self.scrape_all("/stats?mode=statedump"))
87 self.assertIn(self.seeding.hex().upper().encode(), entries)
88 stamp, completed = entries[self.seeding.hex().upper().encode()]
89 self.assertAlmostEqual(int(stamp), int(time.time()) // 60, delta=1, msg="announced a moment ago")
90 self.assertEqual(int(completed), 0)
91
92 # ------------------------------------------------------------ shape
93
94 def test_every_format_sees_the_same_torrents(self):
95 counts = {
96 "ben": len(bdecode(self.scrape_all("/stats?mode=tpbs&format=ben"))[b"files"]),
97 "bin": len(self.scrape_all("/stats?mode=tpbs&format=bin")) // 28,
98 "txt": len(self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txt"))),
99 "txtp": len(self.entries_from_lines(self.scrape_all("/stats?mode=tpbs&format=txtp"))),
100 "url": len([l for l in self.scrape_all("/stats?mode=tpbs&format=url").splitlines() if l]),
101 }
102 self.assertEqual(set(counts.values()), {2}, "all formats, two torrents: %r" % counts)
103
104
105class FullScrapeChunking(TrackerTestCase):
106 def test_a_scrape_larger_than_one_chunk_arrives_whole(self):
107 """The writer hands the socket a chunk at a time, so a scrape that
108 spans several is the case where the seams show."""
109 for i in range(400):
110 self.tracker.announce(struct.pack(">I", i) + b"\0" * 16, port=7000 + i, left=0)
111 answer = bdecode(self.tracker.get("/scrape"))
112 self.assertEqual(len(answer[b"files"]), 400)
113
114
115if __name__ == "__main__":
116 unittest.main()
117
118
119class PartialScrapeOrder(TrackerTestCase):
120 """A bencoded dictionary names its keys in order, once each. The full
121 scrape got that from walking the buckets; the partial scrape used to
122 echo whatever order the client asked in."""
123
124 def setUp(self):
125 TrackerTestCase.setUp(self)
126 self.hashes = [bytes([i]) + b"\0" * 19 for i in (9, 1, 5, 3, 7)]
127 for i, h in enumerate(self.hashes):
128 self.tracker.announce(h, port=6001 + i, left=0)
129
130 def scrape_many(self, hashes):
131 import urllib.parse
132
133 query = "&".join("info_hash=" + urllib.parse.quote_from_bytes(h, safe="") for h in hashes)
134 return bdecode(self.tracker.get("/scrape?" + query))
135
136 def test_the_keys_come_back_in_order(self):
137 answer = self.scrape_many(self.hashes)
138 self.assertEqual(list(answer[b"files"]), sorted(self.hashes))
139
140 def test_reversing_the_question_does_not_reverse_the_answer(self):
141 self.assertEqual(
142 list(self.scrape_many(self.hashes[::-1])[b"files"]), list(self.scrape_many(self.hashes)[b"files"])
143 )
144
145 def test_a_hash_asked_for_twice_is_named_once(self):
146 asked = [self.hashes[0], self.hashes[1], self.hashes[0]]
147 answer = self.scrape_many(asked)
148 self.assertEqual(list(answer[b"files"]), sorted({self.hashes[0], self.hashes[1]}))
diff --git a/tests/integration/test_keepalive.py b/tests/integration/test_keepalive.py
new file mode 100644
index 0000000..f9aa468
--- /dev/null
+++ b/tests/integration/test_keepalive.py
@@ -0,0 +1,146 @@
1"""Holding a connection open across several requests.
2
3The reply path has two shapes. A small answer goes out in one write and the
4connection is done with immediately. A large one is queued and finishes on a
5later pass through the event loop, by which time the workstruct that served
6the request has moved on, so whether to keep the connection has to be
7remembered on the connection itself.
8"""
9
10import time
11import unittest
12import urllib.parse
13
14from harness import TrackerTestCase, bdecode
15
16
17class KeepAlive(TrackerTestCase):
18 def announce_path(self, name, port=6881):
19 return "/announce?info_hash=%s&peer_id=%s&port=%d&left=0" % (
20 urllib.parse.quote_from_bytes(self.hash_for(name), safe=""),
21 "x" * 20,
22 port,
23 )
24
25 def test_two_requests_over_one_connection(self):
26 c = self.tracker.connect()
27 try:
28 c.send(self.announce_path("kaA"))
29 status, _, first = c.reply()
30 self.assertIn(b"200", status)
31 c.send(self.announce_path("kaB"))
32 status, _, second = c.reply()
33 self.assertIn(b"200", status)
34 self.assertIn(b"complete", bdecode(second))
35 finally:
36 c.close()
37
38 def test_close_ends_the_connection(self):
39 c = self.tracker.connect()
40 try:
41 c.send(self.announce_path("kaclose"), connection="close")
42 c.reply()
43 self.assertFalse(c.is_open(), "the tracker was asked to hang up")
44 finally:
45 c.close()
46
47 def test_a_connection_survives_a_reply_too_large_for_one_write(self):
48 """The case that was broken: a queued reply finished draining and the
49 connection was closed regardless of what the client had asked for."""
50 for i in range(400):
51 self.tracker.announce(bytes([i // 256, i % 256]) + b"\0" * 18, port=7000 + i, left=0)
52
53 c = self.tracker.connect()
54 try:
55 c.send("/scrape")
56 status, headers, body = c.reply()
57 self.assertIn(b"200", status)
58 self.assertGreater(len(body), 16384, "this reply has to outgrow one write")
59
60 c.send(self.announce_path("kaafter"))
61 status, _, after = c.reply()
62 self.assertIn(b"200", status)
63 self.assertIn(b"complete", bdecode(after))
64 finally:
65 c.close()
66
67 def test_several_requests_in_a_row(self):
68 c = self.tracker.connect()
69 try:
70 for i in range(20):
71 c.send(self.announce_path("karow%d" % i))
72 status, _, body = c.reply()
73 self.assertIn(b"200", status)
74 self.assertEqual(self.tracker.torrent_count(), 20)
75 finally:
76 c.close()
77
78 def test_without_the_header_the_connection_is_not_held(self):
79 """HTTP/1.1 calls a connection persistent unless told otherwise; this
80 tracker holds one only when asked by name. Pinned as it is."""
81 c = self.tracker.connect()
82 try:
83 c.send(self.announce_path("kanone"), connection=None)
84 c.reply()
85 self.assertFalse(c.is_open())
86 finally:
87 c.close()
88
89 def test_the_error_path_does_not_hold_the_connection(self):
90 c = self.tracker.connect()
91 try:
92 c.send("/announce?info_hash=short")
93 status, _, _ = c.reply()
94 self.assertIn(b"400", status)
95 finally:
96 c.close()
97
98 def test_an_error_after_a_kept_connection_is_still_an_error(self):
99 """The keep-alive decision used to be taken after the handler had run,
100 so an error reply inherited whatever the previous request wanted."""
101 c = self.tracker.connect()
102 try:
103 c.send(self.announce_path("kabefore"))
104 self.assertIn(b"200", c.reply()[0])
105 c.send("/announce?info_hash=short")
106 self.assertIn(b"400", c.reply()[0])
107 finally:
108 c.close()
109
110 def test_a_tiny_split_request_does_not_overread(self):
111 """A request that arrives in pieces and completes as a buffer shorter
112 than the dispatch literals (\"GET /\" etc.) used to read past the
113 exactly sized buffer. It must be rejected without a sanitizer hit."""
114 c = self.tracker.connect()
115 try:
116 c.sock.sendall(b"\r\n")
117 time.sleep(0.05)
118 c.sock.sendall(b"\r\n") # completes as a 4-byte buffer
119 time.sleep(0.1)
120 finally:
121 c.close()
122 # the tracker must still answer; tearDown's stop() surfaces any sanitizer abort
123 answer = self.tracker.announce(self.hash_for("after-tiny"), port=6881, left=0)
124 self.assertNotIn(b"failure reason", answer, "the tracker stopped serving after a tiny request")
125
126 def test_a_split_request_answered_by_a_worker_does_not_spin(self):
127 """A reply that a worker produces does not go through the send path,
128 so the request stays in the buffer the read loop is reading. The loop
129 used to find the same request again on every pass, queue a task for
130 it, and never hand the thread back to the event loop."""
131 for path in ("/stats", "/scrape"):
132 c = self.tracker.connect()
133 try:
134 c.sock.sendall(("GET %s HTTP/1.1\r\nConnection: keep-alive\r\n" % path).encode())
135 time.sleep(0.2)
136 c.sock.sendall(b"\r\n")
137 self.assertIn(b"200", c.reply()[0], "%s was not answered" % path)
138 finally:
139 c.close()
140
141 answer = self.tracker.announce(self.hash_for("after-" + path), port=6881, left=0)
142 self.assertNotIn(b"failure reason", answer, "the tracker stopped serving after %s" % path)
143
144
145if __name__ == "__main__":
146 unittest.main()
diff --git a/tests/integration/test_livesync.py b/tests/integration/test_livesync.py
new file mode 100644
index 0000000..e146d93
--- /dev/null
+++ b/tests/integration/test_livesync.py
@@ -0,0 +1,240 @@
1"""Live sync, driven over the multicast group a cluster would use.
2
3Live sync sits behind WANT_SYNC_LIVE, so these only run against a binary
4built with it: make check-livesync. Against any other build they skip, which
5is what the feature list in -v is for.
6"""
7
8import socket
9import struct
10import subprocess
11import unittest
12
13from harness import TRACKER, Tracker, TrackerTestCase
14
15# enum { OT_SYNC_PEER4, OT_SYNC_PEER6 } in src/ot_livesync.c
16SYNC_PEER4 = 0
17SYNC_PEER6 = 1
18
19# src/trackerlogic.h
20FLAG_SEEDING = 0x80
21FLAG_COMPLETED = 0x40
22FLAG_STOPPED = 0x20
23
24
25def has_livesync():
26 done = subprocess.run([TRACKER, "-v"], capture_output=True, timeout=30)
27 return b"WANT_SYNC_LIVE" in done.stderr
28
29
30def peer4(address, port, flags):
31 """Four bytes of address, two of port, one of flags, one the tracker
32 overwrites with its own idea of the time."""
33 return socket.inet_aton(address) + struct.pack("!H", port) + bytes([flags, 0])
34
35
36def peer6(address, port, flags):
37 return socket.inet_pton(socket.AF_INET6, address) + struct.pack("!H", port) + bytes([flags, 0])
38
39
40def packet(kind, entries, tracker_id=0xDEADBEEF):
41 body = b"".join(info_hash + peer for info_hash, peer in entries)
42 return struct.pack("!I", tracker_id) + struct.pack("!I", kind) + body
43
44
45@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
46class LiveSyncIn(TrackerTestCase):
47 config = "livesync.cluster.listen 127.0.0.1:{livesync_port}\nlivesync.cluster.node_ip 127.0.0.1\n"
48
49 def counts(self, info_hash):
50 """Seeders and leechers a scrape reports for one torrent."""
51 files = self.tracker.scrape(info_hash)[b"files"]
52 if info_hash not in files:
53 return None
54 entry = files[info_hash]
55 return entry[b"complete"], entry[b"incomplete"]
56
57 def test_a_synced_seeder_arrives(self):
58 info_hash = self.hash_for("sync-seed")
59 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.2.3", 6881, FLAG_SEEDING))]))
60 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (1, 0)),
61 "scrape says %r" % (self.counts(info_hash),))
62
63 def test_a_synced_leecher_arrives(self):
64 info_hash = self.hash_for("sync-leech")
65 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.2.4", 6881, 0))]))
66 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (0, 1)),
67 "scrape says %r" % (self.counts(info_hash),))
68
69 def test_a_v6_peer_arrives(self):
70 info_hash = self.hash_for("sync-v6")
71 self.tracker.livesync_send(packet(SYNC_PEER6, [(info_hash, peer6("2001:db8::1", 6881, FLAG_SEEDING))]))
72 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (1, 0)),
73 "scrape says %r" % (self.counts(info_hash),))
74
75 def test_many_v6_announces_do_not_overflow_the_send_buffer(self):
76 """The outgoing peer buffer is filled by announces to a clustered
77 tracker. The flush watermark used sizeof(ot_peer) (== 1), so a v6
78 record could be appended past the 1480-byte buffer onto the adjacent
79 fill field, which then drove an oversized stack copy. Well past the
80 old overflow point (~37 v6 peers) the tracker must still be alive."""
81 last = None
82 for i in range(80):
83 last = self.tracker.announce(self.hash_for("flood-%d" % i),
84 ip="2001:db8::%x" % (i + 1), port=7000 + i, left=1)
85 self.assertIn(b"complete", last, "the tracker stopped answering mid-flood")
86 # tearDown's stop() surfaces any sanitizer complaint on the way out.
87
88 def test_one_packet_carries_several_torrents(self):
89 hashes = [self.hash_for("sync-many-%d" % i) for i in range(4)]
90 self.tracker.livesync_send(packet(SYNC_PEER4, [(h, peer4("10.1.2.%d" % (5 + i), 6881, FLAG_SEEDING))
91 for i, h in enumerate(hashes)]))
92 self.assertTrue(self.tracker.wait_until(lambda: all(self.counts(h) == (1, 0) for h in hashes)))
93
94 def test_a_stopped_peer_is_taken_away_again(self):
95 info_hash = self.hash_for("sync-stop")
96 peer = peer4("10.1.2.9", 6881, FLAG_SEEDING)
97 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer)]))
98 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) == (1, 0)))
99
100 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.2.9", 6881, FLAG_STOPPED))]))
101 self.assertTrue(self.tracker.wait_until(lambda: self.counts(info_hash) in (None, (0, 0))),
102 "scrape still says %r" % (self.counts(info_hash),))
103
104 def test_a_truncated_entry_is_dropped(self):
105 """The loop takes whole hash and peer pairs and leaves a short tail
106 where it is, so the complete entry before it still lands."""
107 good, short = self.hash_for("sync-good"), self.hash_for("sync-short")
108 payload = packet(SYNC_PEER4, [(good, peer4("10.1.2.10", 6881, FLAG_SEEDING))]) + short + b"\x0a\x01"
109 self.tracker.livesync_send(payload)
110 self.assertTrue(self.tracker.wait_until(lambda: self.counts(good) == (1, 0)))
111 self.assertIsNone(self.counts(short))
112
113 def test_an_unknown_packet_type_is_ignored(self):
114 info_hash = self.hash_for("sync-unknown")
115 self.tracker.livesync_send(packet(99, [(info_hash, peer4("10.1.2.11", 6881, FLAG_SEEDING))]))
116 self.assertFalse(self.tracker.wait_until(lambda: self.counts(info_hash) is not None, timeout=1))
117
118 def test_synced_peers_are_counted(self):
119 """The live sync worker keeps its own tally like every other worker,
120 and ?mode=syncs is the sum of them."""
121 before = int(self.tracker.stats("syncs").split()[0])
122 hashes = [self.hash_for("sync-count-%d" % i) for i in range(3)]
123 self.tracker.livesync_send(packet(SYNC_PEER4, [(h, peer4("10.1.2.%d" % (20 + i), 6881, FLAG_SEEDING))
124 for i, h in enumerate(hashes)]))
125 self.assertTrue(self.tracker.wait_until(
126 lambda: int(self.tracker.stats("syncs").split()[0]) == before + 3),
127 "syncs says %s" % self.tracker.stats("syncs").split()[0])
128
129 def test_a_packet_with_nothing_but_a_header_is_ignored(self):
130 before = self.tracker.torrent_count()
131 self.tracker.livesync_send(struct.pack("!I", 0xDEADBEEF) + struct.pack("!I", SYNC_PEER4))
132 self.assertFalse(self.tracker.wait_until(lambda: self.tracker.torrent_count() != before, timeout=1))
133
134
135@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
136class LiveSyncAccess(TrackerTestCase):
137 """Nothing blesses 127.0.0.1 here, so the tracker should take nothing
138 from it. Source address checking is all live sync has."""
139
140 config = "livesync.cluster.listen 127.0.0.1:{livesync_port}\nlivesync.cluster.node_ip 10.0.0.1\n"
141
142 def test_an_unblessed_sender_is_ignored(self):
143 info_hash = self.hash_for("sync-unblessed")
144 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.2.12", 6881, FLAG_SEEDING))]))
145 self.assertFalse(self.tracker.wait_until(lambda: self.tracker.torrent_count() != 0, timeout=1))
146
147
148@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
149class LiveSyncUnconfigured(TrackerTestCase):
150 """A binary that has the feature but no cluster to join. Somebody whose
151 packager turned WANT_SYNC_LIVE on did not ask for live sync and should
152 not be able to tell that it is there."""
153
154 config = ""
155
156 def test_the_tracker_runs_anyway(self):
157 info_hash = self.hash_for("no-cluster")
158 self.tracker.announce(info_hash, port=6881, left=0)
159 self.assertEqual(self.tracker.torrent_count(), 1)
160
161 def test_nothing_is_said_about_the_missing_cluster(self):
162 self.assertNotIn("sync", self.tracker.output().lower())
163
164 def test_no_socket_is_bound_for_it(self):
165 """A configured tracker holds the wildcard address on that port, so
166 taking it here proves nothing was started."""
167 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
168 try:
169 sock.bind(("0.0.0.0", self.tracker.livesync_port))
170 finally:
171 sock.close()
172
173 def test_announcing_stays_clean(self):
174 """Enough announces to pass the watermark that would flush an
175 outgoing buffer, if there were one to flush. The sanitizers in this
176 build turn anything the attempt touched into a failure."""
177 for i in range(200):
178 self.tracker.announce(self.hash_for("no-cluster-%d" % i), port=6881 + i, left=0)
179 self.assertEqual(self.tracker.torrent_count(), 200)
180
181
182# RFC 2365 sets 239.192.0.0/14 aside for exactly this kind of use
183OWN_GROUP = "239.192.0.7"
184# A group nothing in this suite ever joins. Deliberately not the default one:
185# other trackers here do join that, on ports the harness picks at random, and
186# a socket bound to the wildcard address shares a port's multicast traffic
187# with anything else on the host that has joined the group it is addressed
188# to. Two clusters sharing a host and a port is pathological in the field but
189# routine in a test suite.
190UNJOINED_GROUP = "239.192.0.99"
191
192
193@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
194class LiveSyncGroup(TrackerTestCase):
195 config = ("livesync.cluster.group %s\n"
196 "livesync.cluster.listen 127.0.0.1:{livesync_port}\n"
197 "livesync.cluster.node_ip 127.0.0.1\n" % OWN_GROUP)
198
199 def test_the_configured_group_is_joined(self):
200 info_hash = self.hash_for("own-group")
201 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.3.1", 6881, FLAG_SEEDING))]),
202 group=OWN_GROUP)
203 self.assertTrue(self.tracker.wait_until(lambda: self.tracker.torrent_count() == 1))
204
205 def test_another_group_is_left_alone(self):
206 """A cluster that picked its own group hears nothing from the others."""
207 info_hash = self.hash_for("not-our-group")
208 self.tracker.livesync_send(packet(SYNC_PEER4, [(info_hash, peer4("10.1.3.2", 6881, FLAG_SEEDING))]),
209 group=UNJOINED_GROUP)
210 self.assertFalse(self.tracker.wait_until(lambda: self.tracker.torrent_count() != 0, timeout=1))
211
212
213@unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE")
214class LiveSyncGroupRefused(unittest.TestCase):
215 """A cluster that asked for a group of its own must not quietly end up on
216 the one every other opentracker is on, so a line that does not name a
217 group stops the tracker rather than falling back."""
218
219 def start_with(self, group):
220 return Tracker("livesync.cluster.group %s\n"
221 "livesync.cluster.listen 127.0.0.1:{livesync_port}\n"
222 "livesync.cluster.node_ip 127.0.0.1\n" % group)
223
224 def test_a_unicast_address_stops_the_tracker(self):
225 with self.assertRaises(AssertionError) as caught:
226 self.start_with("10.0.0.1")
227 self.assertIn("multicast address", str(caught.exception))
228
229 def test_so_does_something_that_is_not_an_address(self):
230 with self.assertRaises(AssertionError) as caught:
231 self.start_with("not-an-address")
232 self.assertIn("multicast address", str(caught.exception))
233
234 def test_a_group_at_either_end_of_the_range_is_taken(self):
235 for group in ("224.0.0.1", "239.255.255.255"):
236 tracker = self.start_with(group)
237 try:
238 self.assertEqual(tracker.torrent_count(), 0)
239 finally:
240 tracker.stop()
diff --git a/tests/integration/test_shutdown.py b/tests/integration/test_shutdown.py
new file mode 100644
index 0000000..063d779
--- /dev/null
+++ b/tests/integration/test_shutdown.py
@@ -0,0 +1,58 @@
1"""That every thread the tracker starts also ends when it is asked to stop.
2
3The rest of the suite stops a tracker too, so a thread left behind already
4shows up in teardown as the complaint that the tracker had to be killed.
5These ask for the arrangements that park a thread in a blocking read in the
6first place, and they time the exit, because a reader woken only by its own
7receive timeout passes a correctness check while taking a second over it.
8"""
9
10import time
11import unittest
12
13from harness import Tracker, TrackerTestCase
14
15# Generous enough for a platform where shutting the socket down does not wake
16# the reader and the receive timeout has to expire, tight enough that a reader
17# which is never woken at all fails instead of hanging the suite
18PATIENCE = 3.0
19
20
21def time_the_exit(extra_config):
22 tracker = Tracker(extra_config)
23 try:
24 # Serve one request of each kind first, so the threads that are about
25 # to be joined have actually run
26 tracker.announce(b"shutdown-probe\0\0\0\0\0\0")
27 sock, connection_id = tracker.udp_connect()
28 tracker.udp_announce(sock, connection_id, b"shutdown-probe\0\0\0\0\0\0")
29 sock.close()
30 started = time.time()
31 complaints = tracker.stop()
32 return time.time() - started, complaints
33 finally:
34 tracker._cleanup()
35
36
37class UdpWorkers(TrackerTestCase):
38 config = "listen.udp.workers 8\n"
39
40 def test_announce_reaches_one_of_eight_workers(self):
41 """Keeps the workers from being merely started and never used."""
42 sock, connection_id = self.tracker.udp_connect()
43 answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("eight-workers"))
44 sock.close()
45 self.assertEqual(answer["seeders"], 1)
46
47
48class ShutdownEndsEveryThread(unittest.TestCase):
49 def test_eight_udp_workers_are_joined(self):
50 took, complaints = time_the_exit("listen.udp.workers 8\n")
51 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
52 self.assertLess(took, PATIENCE, "stopping eight udp workers took %.1f s" % took)
53
54 def test_udp_in_the_event_loop_still_stops(self):
55 """Worker count zero leaves no thread to join, which must also work."""
56 took, complaints = time_the_exit("listen.udp.workers 0\n")
57 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
58 self.assertLess(took, PATIENCE, "stopping without workers took %.1f s" % took)
diff --git a/tests/integration/test_statefile.py b/tests/integration/test_statefile.py
new file mode 100644
index 0000000..a3c8d59
--- /dev/null
+++ b/tests/integration/test_statefile.py
@@ -0,0 +1,97 @@
1"""The state dump and the -l switch that reads it back.
2
3The second column is the minute a torrent was last touched, by the wall
4clock, which is what the file has recorded for years and the only clock two
5runs of the tracker agree on.
6"""
7
8import os
9import time
10import unittest
11
12from harness import Tracker, TrackerTestCase
13
14
15class StateFileRoundTrip(TrackerTestCase):
16 def dump(self):
17 return self.tracker.get("/stats?mode=statedump")
18
19 def test_a_dumped_torrent_comes_back_with_its_completed_count(self):
20 info_hash = self.hash_for("state-rt")
21 self.tracker.announce(info_hash, port=6001, left=0, event="completed")
22 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"downloaded"], 1)
23
24 path = os.path.join(self.tracker.dir, "state")
25 with open(path, "wb") as handle:
26 handle.write(self.dump())
27
28 restarted = Tracker(extra_args=["-l", path])
29 try:
30 files = restarted.scrape(info_hash)[b"files"]
31 self.assertIn(info_hash, files, "the torrent did not survive the restart")
32 entry = files[info_hash]
33 self.assertEqual(entry[b"downloaded"], 1, "the completed count did not survive")
34 self.assertEqual(entry[b"complete"], 0, "no peers are carried over, only the torrent")
35 self.assertEqual(entry[b"incomplete"], 0)
36 complaints = restarted.stop()
37 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
38 finally:
39 restarted._cleanup()
40
41 def test_a_torrent_older_than_the_tracker_would_keep_is_not_loaded(self):
42 """An age past the torrent timeout would be cleaned away on the first
43 sweep, so it is never built in the first place."""
44 info_hash = self.hash_for("state-stale")
45 path = os.path.join(self.tracker.dir, "stale")
46 with open(path, "w") as handle:
47 handle.write("%s:%d:7\n" % (info_hash.hex(), 24 * 60 + 1))
48
49 restarted = Tracker(extra_args=["-l", path])
50 try:
51 self.assertNotIn(info_hash, restarted.scrape(info_hash)[b"files"])
52 restarted.stop()
53 finally:
54 restarted._cleanup()
55
56
57class StateFileWithNonsenseStamps(TrackerTestCase):
58 """The column is read as unsigned and handed on as a signed ot_time. A
59 value at or above 2^63 arrived negative, cleared the timeout check, and
60 put the torrent's base in the future, where the cleaner never reaches it.
61 At exactly 2^63 the subtraction itself overflowed."""
62
63 def stamps(self):
64 now = int(time.time()) // 60
65 return {
66 "overflow": 2**63,
67 "minus-one": 2**64 - 1,
68 "int64-max": 2**63 - 1,
69 "in-the-future": now + 60,
70 "past-timeout": now - (24 * 60 + 1),
71 }
72
73 def test_no_stamp_outside_the_timeout_builds_a_torrent(self):
74 stamps = self.stamps()
75 lines = ["%s:%d:7" % (self.hash_for(name).hex(), stamp) for name, stamp in stamps.items()]
76 lines.append("%s:%d:7" % (self.hash_for("honest").hex(), int(time.time()) // 60 - 5))
77
78 path = os.path.join(self.tracker.dir, "nonsense")
79 with open(path, "w") as handle:
80 handle.write("\n".join(lines) + "\n")
81
82 restarted = Tracker(extra_args=["-l", path])
83 try:
84 for name, stamp in stamps.items():
85 self.assertNotIn(self.hash_for(name), restarted.scrape(self.hash_for(name))[b"files"],
86 "the line stamped %d was loaded" % stamp)
87 self.assertIn(self.hash_for("honest"), restarted.scrape(self.hash_for("honest"))[b"files"],
88 "the state file was not read at all")
89 self.assertEqual(restarted.torrent_count(), 1)
90 complaints = restarted.stop()
91 self.assertEqual(complaints, [], "the tracker reported:\n" + "\n".join(complaints))
92 finally:
93 restarted._cleanup()
94
95
96if __name__ == "__main__":
97 unittest.main()
diff --git a/tests/integration/test_stats.py b/tests/integration/test_stats.py
new file mode 100644
index 0000000..46ca39b
--- /dev/null
+++ b/tests/integration/test_stats.py
@@ -0,0 +1,146 @@
1"""The /stats endpoint.
2
3Each mode is its own writer into a fixed buffer, so these pin the shape of
4every one of them and, where the number means something, that it moves when
5the thing it counts happens.
6"""
7
8import re
9import unittest
10import urllib.error
11import xml.etree.ElementTree
12
13from harness import TrackerTestCase
14
15# The modes a default build answers. "tpbs" and "statedump" are full scrapes
16# and belong to test_fullscrape; "woodpeckers" sits behind a
17# feature flag this build does not set.
18MRTG_MODES = ["peer", "conn", "scrp", "udp4", "tcp4", "torr", "fscr", "completed", "syncs"]
19TEXT_MODES = ["herr", "top10", "top100", "renew"]
20
21
22class StatsShape(TrackerTestCase):
23 def test_every_mode_answers_something(self):
24 for mode in MRTG_MODES + TEXT_MODES + ["everything"]:
25 self.assertTrue(self.tracker.stats(mode), "mode %s answered empty" % mode)
26
27 def test_an_mrtg_mode_opens_with_two_numbers(self):
28 """MRTG reads the first two lines as counters and the rest as labels,
29 so the order matters to something outside this project."""
30 for mode in MRTG_MODES:
31 lines = self.tracker.stats(mode).splitlines()
32 self.assertGreaterEqual(len(lines), 2, "mode %s" % mode)
33 for line in lines[:2]:
34 self.assertRegex(line, rb"^\d+$", "mode %s line %r" % (mode, line))
35
36 def test_the_busy_mode_is_gone(self):
37 """It was listed in the mode table and implemented nowhere, so it only
38 ever answered 500. Removed rather than written: picking poisoning
39 networks out stopped being meaningful once consumer lines became bot
40 hosts and v6 made the address space too large to watch."""
41 with self.assertRaises(urllib.error.HTTPError) as caught:
42 self.tracker.stats("busy")
43 self.assertEqual(caught.exception.code, 400, "an unknown mode, like any other")
44
45 def test_an_unknown_mode_is_refused(self):
46 with self.assertRaises(urllib.error.HTTPError) as caught:
47 self.tracker.stats("nosuchmode")
48 self.assertEqual(caught.exception.code, 400)
49
50 def test_everything_is_well_formed_xml(self):
51 root = xml.etree.ElementTree.fromstring(self.tracker.stats("everything").decode())
52 self.assertEqual(root.tag, "stats")
53 self.assertIsNotNone(root.find("torrents/count_mutex"))
54 self.assertIsNotNone(root.find("connections/tcp/announce"))
55
56 def test_the_version_mode_is_gone(self):
57 """Which build a tracker is and what went into it is of use to whoever
58 attacks it and to nobody else on the far end of a socket. It is
59 reported by -v, to whoever already has the binary."""
60 with self.assertRaises(urllib.error.HTTPError) as caught:
61 self.tracker.stats("version")
62 self.assertEqual(caught.exception.code, 400, "an unknown mode, like any other")
63
64 def test_everything_does_not_name_the_build(self):
65 self.assertNotIn(b"opentracker 1", self.tracker.stats("everything"))
66
67 def test_everything_does_not_name_the_tracker_id(self):
68 """The id a tracker recognises its own live sync packets by. Knowing
69 it is of no use to a client and of some use to whoever would like a
70 tracker to discard what it is told."""
71 self.assertNotIn(b"tracker_id", self.tracker.stats("everything"))
72
73
74class StatsCount(TrackerTestCase):
75 def test_the_torrent_count_follows_the_torrents(self):
76 before = self.tracker.torrent_count()
77 self.tracker.announce(self.hash_for("statA"), port=6001, left=0)
78 self.assertEqual(self.tracker.torrent_count(), before + 1)
79 self.tracker.announce(self.hash_for("statB"), port=6002, left=0)
80 self.assertEqual(self.tracker.torrent_count(), before + 2)
81
82 def test_the_peer_count_separates_seeders_from_the_rest(self):
83 self.tracker.announce(self.hash_for("statpeers"), port=6001, left=0)
84 self.tracker.announce(self.hash_for("statpeers"), port=6002, left=4096)
85 peers, seeds = self.tracker.stats("peer").splitlines()[:2]
86 self.assertEqual(int(peers), 2)
87 self.assertEqual(int(seeds), 1)
88
89 def test_the_completed_count_follows_the_completed_event(self):
90 before = int(self.tracker.stats("completed").splitlines()[0])
91 self.tracker.announce(self.hash_for("statdone"), port=6001, left=0, event="completed")
92 self.assertEqual(int(self.tracker.stats("completed").splitlines()[0]), before + 1)
93
94 def test_a_bad_request_is_counted_as_an_http_error(self):
95 before = self.tracker.stats("herr")
96 try:
97 self.tracker.stats("nosuchmode")
98 except urllib.error.HTTPError:
99 pass
100 after = self.tracker.stats("herr")
101 self.assertNotEqual(before, after, "no error counter moved")
102
103 def test_the_tcp_counter_follows_tcp_requests(self):
104 before = int(self.tracker.stats("tcp4").splitlines()[0])
105 for _ in range(3):
106 self.tracker.announce(self.hash_for("stattcp"), port=6001, left=0)
107 self.assertGreaterEqual(int(self.tracker.stats("tcp4").splitlines()[0]), before + 3)
108
109 def test_the_udp_counter_follows_udp_requests(self):
110 before = int(self.tracker.stats("udp4").splitlines()[0])
111 sock, connection_id = self.tracker.udp_connect()
112 try:
113 self.tracker.udp_announce(sock, connection_id, self.hash_for("statudp"), left=0)
114 finally:
115 sock.close()
116 self.assertGreater(int(self.tracker.stats("udp4").splitlines()[0]), before)
117
118 def test_the_scrape_counter_follows_scrapes(self):
119 before = int(self.tracker.stats("scrp").splitlines()[0])
120 self.tracker.scrape(self.hash_for("statscrape"))
121 self.assertEqual(int(self.tracker.stats("scrp").splitlines()[0]), before + 1)
122
123
124class StatsTop(TrackerTestCase):
125 def test_the_top_list_ranks_by_peer_count(self):
126 busy = self.hash_for("topbusy")
127 quiet = self.hash_for("topquiet")
128 for port in range(6001, 6006):
129 self.tracker.announce(busy, port=port, left=0)
130 self.tracker.announce(quiet, port=6100, left=0)
131
132 body = self.tracker.stats("top10")
133 self.assertIn(b"Top 10 torrents by peers", body)
134 ranked = re.findall(rb"\t(\d+)\t([0-9A-F]{40})", body.split(b"by seeds")[0])
135 self.assertEqual(ranked[0][1], busy.hex().upper().encode(), "the busy torrent ranks first")
136 self.assertEqual(int(ranked[0][0]), 5)
137
138 def test_the_top_list_has_three_sections(self):
139 self.tracker.announce(self.hash_for("topsections"), port=6001, left=0)
140 body = self.tracker.stats("top100")
141 for heading in (b"by peers", b"by seeds", b"by leechers"):
142 self.assertIn(heading, body)
143
144
145if __name__ == "__main__":
146 unittest.main()
diff --git a/tests/integration/test_tcpworkers.py b/tests/integration/test_tcpworkers.py
new file mode 100644
index 0000000..e43612a
--- /dev/null
+++ b/tests/integration/test_tcpworkers.py
@@ -0,0 +1,67 @@
1"""The tracker with its tcp side handed to worker threads.
2
3With workers configured, a connection is accepted and answered on a worker's
4own stack. Anything it cannot finish there is copied to the heap and handed
5to the event loop, which is the one place where a worker and the main thread
6touch the same structures, so these drive all three outcomes: answered
7inline, held open, and parked waiting for another thread entirely.
8"""
9
10import threading
11import unittest
12import urllib.parse
13
14from harness import TrackerTestCase, bdecode
15
16WORKERS = 4
17
18
19class TcpWorkers(TrackerTestCase):
20 config = "listen.tcp.workers %d\n" % WORKERS
21
22 def announce_path(self, name, port=6881):
23 return "/announce?info_hash=%s&peer_id=%s&port=%d&left=0" % (
24 urllib.parse.quote_from_bytes(self.hash_for(name), safe=""),
25 "x" * 20,
26 port,
27 )
28
29 def test_many_at_once_are_all_answered(self):
30 """Every worker gets something to do, and the swarm adds up."""
31 info_hash = self.hash_for("workers-swarm")
32 errors = []
33
34 def announce(index):
35 try:
36 self.tracker.announce(info_hash, peer_id=b"-OT0001-%012d" % index, port=7000 + index, left=0)
37 except Exception as problem: # noqa: BLE001 - reported, not swallowed
38 errors.append("%d: %r" % (index, problem))
39
40 threads = [threading.Thread(target=announce, args=(i,)) for i in range(32)]
41 for thread in threads:
42 thread.start()
43 for thread in threads:
44 thread.join()
45
46 self.assertEqual(errors, [], "\n".join(errors))
47 self.assertEqual(self.tracker.scrape(info_hash)[b"files"][info_hash][b"complete"], 32)
48
49 def test_a_kept_connection_outlives_the_worker_that_took_it(self):
50 """Keep-alive is the plain case of a connection a worker hands on."""
51 connection = self.tracker.connect()
52 try:
53 for i in range(4):
54 connection.send(self.announce_path("workers-kept"))
55 status, _, body = connection.reply()
56 self.assertIn(b"200", status)
57 self.assertIn(b"complete", bdecode(body))
58 finally:
59 connection.close()
60
61 def test_a_full_scrape_asked_for_by_a_worker_still_arrives(self):
62 """The reply is built by another thread, so the worker parks the
63 connection waiting for nothing at all before handing it over."""
64 for i in range(20):
65 self.tracker.announce(bytes([i]) + b"\0" * 19, port=7100 + i, left=0)
66 body = self.tracker.get("/scrape")
67 self.assertEqual(len(bdecode(body)[b"files"]), 20)
diff --git a/tests/integration/test_udp.py b/tests/integration/test_udp.py
new file mode 100644
index 0000000..8a255ec
--- /dev/null
+++ b/tests/integration/test_udp.py
@@ -0,0 +1,218 @@
1"""The UDP tracker protocol, BEP 15.
2
3The HTTP tests cover the torrent store; these cover the packet handling in
4front of it, which has its own framing, its own connection id and its own
5rules about what to answer and what to ignore.
6"""
7
8import socket
9import struct
10import unittest
11
12from harness import Tracker, TrackerTestCase
13
14MAGIC = 0x41727101980
15
16
17class UdpProtocol(TrackerTestCase):
18 def test_connect_echoes_the_transaction_id(self):
19 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
20 sock.settimeout(5)
21 try:
22 sock.sendto(struct.pack(">QII", MAGIC, 0, 0xDEADBEEF), ("127.0.0.1", self.tracker.port))
23 action, transaction, connection_id = struct.unpack(">IIQ", sock.recv(2048)[:16])
24 self.assertEqual(action, 0)
25 self.assertEqual(transaction, 0xDEADBEEF)
26 self.assertNotEqual(connection_id, 0)
27 finally:
28 sock.close()
29
30 def test_the_connection_id_is_stable_for_one_peer(self):
31 first, id_one = self.tracker.udp_connect()
32 second, id_two = self.tracker.udp_connect()
33 try:
34 self.assertEqual(id_one, id_two)
35 finally:
36 first.close()
37 second.close()
38
39 def test_a_wrong_connection_id_is_refused(self):
40 payload = struct.pack(">QII20s20sQQQIIIiH", 0, 1, 2, self.hash_for("udpbad"), b"p" * 20, 0, 0, 0, 0, 0, 0, -1, 6881)
41 answer = self.tracker.udp_raw(payload)
42 self.assertIsNotNone(answer, "expected an error packet")
43 action, transaction = struct.unpack(">II", answer[:8])
44 self.assertEqual(action, 3, "action 3 is the error packet")
45 self.assertIn(b"Connection ID missmatch", answer[8:])
46
47 def test_a_wrong_connection_id_is_not_answered_with_more_than_was_sent(self):
48 """The sender's address is unverified at this point, so the error
49 must not be a way to throw bytes at somebody else."""
50 scrape = struct.pack(">QII", 0, 2, 3) + self.hash_for("udpbadscrape")
51 answer = self.tracker.udp_raw(scrape)
52 self.assertIsNotNone(answer, "a whole scrape is long enough to be told")
53 self.assertLessEqual(len(answer), len(scrape))
54 self.assertIsNone(self.tracker.udp_raw(scrape[:16]))
55 self.assertIsNone(self.tracker.udp_raw(scrape[: len(answer) - 1]))
56 self.assertIsNotNone(self.tracker.udp_raw(scrape[: len(answer)]))
57
58 def test_a_packet_shorter_than_the_header_is_ignored(self):
59 self.assertIsNone(self.tracker.udp_raw(b"\x00" * 15))
60
61 def test_an_unknown_action_is_ignored(self):
62 self.assertIsNone(self.tracker.udp_raw(struct.pack(">QII", MAGIC, 9, 1)))
63
64 def test_connect_requires_the_protocol_magic(self):
65 self.assertIsNone(self.tracker.udp_raw(struct.pack(">QII", MAGIC + 1, 0, 1)))
66
67 def test_an_announce_cut_short_is_ignored(self):
68 sock, connection_id = self.tracker.udp_connect()
69 try:
70 self.assertIsNone(self.tracker.udp_raw(struct.pack(">QII", connection_id, 1, 1) + b"\0" * 40))
71 finally:
72 sock.close()
73
74
75class UdpAnnounce(TrackerTestCase):
76 def test_a_seeder_is_counted_as_a_seeder(self):
77 sock, connection_id = self.tracker.udp_connect()
78 try:
79 answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("udpseed"), left=0)
80 self.assertEqual(answer["seeders"], 1)
81 self.assertEqual(answer["leechers"], 0)
82 self.assertGreater(answer["interval"], 0)
83 finally:
84 sock.close()
85
86 def test_a_leecher_is_counted_as_a_leecher(self):
87 sock, connection_id = self.tracker.udp_connect()
88 try:
89 answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("udpleech"), left=1024)
90 self.assertEqual(answer["seeders"], 0)
91 self.assertEqual(answer["leechers"], 1)
92 finally:
93 sock.close()
94
95 def test_stopped_removes_the_peer(self):
96 info_hash = self.hash_for("udpstop")
97 sock, connection_id = self.tracker.udp_connect()
98 try:
99 self.tracker.udp_announce(sock, connection_id, info_hash, left=0)
100 self.tracker.udp_announce(sock, connection_id, info_hash, left=0, event=3)
101 answer = self.tracker.udp_announce(sock, connection_id, info_hash, left=1024)
102 self.assertEqual(answer["seeders"], 0, "the seeder announced stopped")
103 finally:
104 sock.close()
105
106 def test_an_announce_over_udp_is_visible_over_http(self):
107 """One torrent store behind both bearers, not two."""
108 info_hash = self.hash_for("udpcross")
109 sock, connection_id = self.tracker.udp_connect()
110 try:
111 self.tracker.udp_announce(sock, connection_id, info_hash, left=0)
112 finally:
113 sock.close()
114 scrape = self.tracker.scrape(info_hash)
115 self.assertEqual(scrape[b"files"][info_hash][b"complete"], 1)
116
117 def test_the_peer_list_carries_the_announcing_peer(self):
118 info_hash = self.hash_for("udppeers")
119 sock, connection_id = self.tracker.udp_connect()
120 try:
121 answer = self.tracker.udp_announce(sock, connection_id, info_hash, left=0, port=6881)
122 self.assertEqual(len(answer["peers"]) % 6, 0, "v4 peers are six bytes each")
123 self.assertGreaterEqual(len(answer["peers"]), 6)
124 self.assertEqual(struct.unpack(">H", answer["peers"][4:6])[0], 6881)
125 finally:
126 sock.close()
127
128
129class UdpScrape(TrackerTestCase):
130 def test_scrape_reports_the_swarm(self):
131 info_hash = self.hash_for("udpscrape")
132 sock, connection_id = self.tracker.udp_connect()
133 try:
134 self.tracker.udp_announce(sock, connection_id, info_hash, left=0)
135 seeders, completed, leechers = self.tracker.udp_scrape(sock, connection_id, [info_hash])[0]
136 self.assertEqual(seeders, 1)
137 self.assertEqual(leechers, 0)
138 self.assertEqual(completed, 0)
139 finally:
140 sock.close()
141
142 def test_an_unknown_hash_scrapes_as_empty(self):
143 sock, connection_id = self.tracker.udp_connect()
144 try:
145 self.assertEqual(self.tracker.udp_scrape(sock, connection_id, [self.hash_for("udpnone")])[0], (0, 0, 0))
146 finally:
147 sock.close()
148
149 def test_several_hashes_answer_in_order(self):
150 seeding = self.hash_for("udpmultiA")
151 leeching = self.hash_for("udpmultiB")
152 sock, connection_id = self.tracker.udp_connect()
153 try:
154 self.tracker.udp_announce(sock, connection_id, seeding, left=0)
155 self.tracker.udp_announce(sock, connection_id, leeching, left=1024)
156 answers = self.tracker.udp_scrape(sock, connection_id, [seeding, leeching])
157 self.assertEqual(answers[0][0], 1, "first hash is the seeded one")
158 self.assertEqual(answers[1][2], 1, "second hash is the leeched one")
159 finally:
160 sock.close()
161
162 def test_a_hash_cut_short_is_not_scraped(self):
163 """What follows the last whole hash is not a hash, and the bytes that
164 would complete it are not the client's."""
165 info_hash = self.hash_for("udpcut")
166 sock, connection_id = self.tracker.udp_connect()
167 try:
168 sock.sendto(
169 struct.pack(">QII", connection_id, 2, 3) + info_hash + b"\x00" * 7, ("127.0.0.1", self.tracker.port)
170 )
171 self.assertEqual(len(sock.recv(2048)), 8 + 12)
172 finally:
173 sock.close()
174
175 def test_a_scrape_answers_no_more_hashes_than_the_protocol_allows(self):
176 sock, connection_id = self.tracker.udp_connect()
177 try:
178 hashes = b"".join(self.hash_for("udpmany%d" % n) for n in range(80))
179 sock.sendto(struct.pack(">QII", connection_id, 2, 4) + hashes, ("127.0.0.1", self.tracker.port))
180 self.assertEqual(len(sock.recv(2048)), 8 + 12 * 74)
181 finally:
182 sock.close()
183
184
185class UdpWorkersConfiguredAfterTheListener(TrackerTestCase):
186 """The harness writes its listen lines first, so this directive lands
187 below them: the position a config file should not care about."""
188
189 config = "listen.udp.workers 4\n"
190
191 def test_the_tracker_starts_and_still_answers_udp(self):
192 sock, connection_id = self.tracker.udp_connect()
193 try:
194 answer = self.tracker.udp_announce(sock, connection_id, self.hash_for("udpworkers"), left=0)
195 self.assertEqual(answer["seeders"], 1)
196 finally:
197 sock.close()
198
199
200if __name__ == "__main__":
201 unittest.main()
202
203
204class UdpAddressAlreadyTaken(TrackerTestCase):
205 def test_a_second_tracker_on_the_same_udp_address_says_so(self):
206 """Linux lets it start all the same, and from then on the two take
207 each other's packets. FreeBSD refuses the bind that follows, and the
208 warning is then what explains the refusal."""
209 try:
210 second = Tracker("listen.udp 127.0.0.1:%d\n" % self.tracker.port)
211 except AssertionError as refused:
212 said = str(refused)
213 else:
214 said = second.output()
215 second.stop()
216 second._cleanup()
217 self.assertIn("is already in use", said)
218 self.assertNotIn("is already in use", self.tracker.output())
diff --git a/tests/integration/test_version.py b/tests/integration/test_version.py
new file mode 100644
index 0000000..66f570d
--- /dev/null
+++ b/tests/integration/test_version.py
@@ -0,0 +1,36 @@
1"""The -v report, which is where a build says what went into it.
2
3Driving the binary is the only way to see this: the feature list is a table
4of #ifdefs, so it is only true for the flags the binary itself was built with.
5"""
6
7import subprocess
8import unittest
9
10from harness import TRACKER
11
12
13class VersionFlag(unittest.TestCase):
14 def report(self):
15 # -v writes to stderr and exits before it binds anything
16 done = subprocess.run([TRACKER, "-v"], capture_output=True, timeout=30)
17 self.assertEqual(done.returncode, 0, done.stderr)
18 return done.stderr.decode()
19
20 def test_first_line_names_the_release(self):
21 # The commit in brackets is there in a checkout and in a release
22 # tarball, and absent in a build that had neither to ask.
23 first = self.report().splitlines()[0]
24 self.assertRegex(first, r"^opentracker \d+\.\d+\.\d+( \(\S+\))?$")
25
26 def test_names_the_event_mechanism(self):
27 self.assertRegex(self.report(), r"(?m)^events: (epoll|kqueue|poll)$")
28
29 def test_lists_the_features_this_build_has(self):
30 # The Makefile builds this binary with these and not with those, so a
31 # feature table that stops following the build fails here.
32 report = self.report()
33 for want in ("WANT_KEEPALIVE", "WANT_ACCESSLIST_BLACK", "WANT_DYNAMIC_ACCESSLIST"):
34 self.assertIn(want, report)
35 for unwanted in ("WANT_SPOT_WOODPECKER", "WANT_V4_ONLY", "WANT_RESTRICT_STATS"):
36 self.assertNotIn(unwanted, report)
diff --git a/tests/runner.c b/tests/runner.c
new file mode 100644
index 0000000..2398991
--- /dev/null
+++ b/tests/runner.c
@@ -0,0 +1,115 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <sys/wait.h>
9#include <unistd.h>
10
11/* Opentracker */
12#include "test.h"
13
14struct module {
15 const char *name;
16 void (*run)(void);
17};
18
19static const struct module modules[] = {{"ot_urlencoded", test_urlencoded},
20 {"ot_iovec", test_iovec},
21 {"ot_vector", test_vector},
22 {"ot_random", test_random},
23 {"ot_hex", test_hex},
24 {"ot_scan", test_scan},
25 {"ot_buf", test_buf},
26 {"ot_ip", test_ip},
27 {"ot_socket", test_socket},
28 {"ot_mutex", test_mutex},
29 {"trackerlogic", test_trackerlogic},
30 {"clean", test_clean},
31 {"ot_workqueue", test_workqueue},
32 {"ot_batch", test_batch},
33 {"ot_fdstate", test_fdstate},
34 {"ot_event", test_event},
35 {"ot_fmt", test_fmt},
36 {"ot_accesslist", test_accesslist},
37 {NULL, NULL}};
38
39struct tally {
40 unsigned long checks;
41 unsigned long failures;
42};
43
44/* Each module runs in a child of its own, so that a crash or a sanitizer
45 abort costs that module's results rather than every module after it. The
46 child reports its tally through a pipe; one that dies without reporting is
47 counted as a failure under its own name. */
48static void run_forked(const struct module *m) {
49 struct tally tally = {0, 0};
50 int pipefd[2], status = 0;
51 pid_t child;
52 ssize_t got;
53
54 if (pipe(pipefd)) {
55 test_failf(__FILE__, __LINE__, "pipe failed, cannot isolate %s", m->name);
56 return;
57 }
58
59 fflush(stdout); /* or the child inherits a copy and prints it again */
60 child = fork();
61 if (child < 0) {
62 close(pipefd[0]);
63 close(pipefd[1]);
64 test_failf(__FILE__, __LINE__, "fork failed, cannot isolate %s", m->name);
65 return;
66 }
67
68 if (!child) {
69 close(pipefd[0]);
70 test_checks = test_failures = 0;
71 m->run();
72 tally.checks = test_checks;
73 tally.failures = test_failures;
74 if (write(pipefd[1], &tally, sizeof(tally)) != (ssize_t)sizeof(tally))
75 _exit(1);
76 fflush(stdout);
77 _exit(0);
78 }
79
80 close(pipefd[1]);
81 got = read(pipefd[0], &tally, sizeof(tally));
82 close(pipefd[0]);
83 while (waitpid(child, &status, 0) < 0)
84 ;
85
86 if (got == (ssize_t)sizeof(tally)) {
87 test_checks += tally.checks;
88 test_failures += tally.failures;
89 }
90 if (got != (ssize_t)sizeof(tally) || !WIFEXITED(status) || WEXITSTATUS(status))
91 test_failf(__FILE__, __LINE__, "%s did not run to the end", m->name);
92}
93
94/* Run every module, or only those whose name contains argv[1].
95 OT_TEST_FORK=0 keeps everything in one process, which is what a debugger
96 wants. */
97int main(int argc, char **argv) {
98 const char *fork_setting = getenv("OT_TEST_FORK");
99 int isolate = !fork_setting || strcmp(fork_setting, "0");
100 const struct module *m;
101
102 for (m = modules; m->name; ++m) {
103 if (argc > 1 && !strstr(m->name, argv[1]))
104 continue;
105 test_module(m->name);
106 if (!isolate) {
107 m->run();
108 continue;
109 }
110 test_case("the module runs to the end");
111 run_forked(m);
112 }
113
114 return test_summary();
115}
diff --git a/tests/stubs.c b/tests/stubs.c
new file mode 100644
index 0000000..b8ab174
--- /dev/null
+++ b/tests/stubs.c
@@ -0,0 +1,48 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* Stubs for symbols the modules under test reference but never reach along
5 the paths the tests exercise. If a test ever does reach one, the missing
6 behaviour should be supplied here rather than the test weakened. */
7
8/* Opentracker */
9#include "ot_stats.h"
10#include "trackerlogic.h"
11
12/* ot_accesslist.c is built with WANT_ACCESSLIST_BLACK so that the hash parser
13 is reachable. These two belong to accesslist_readfile and the reload worker,
14 neither of which any test drives. */
15_Atomic int g_opentracker_running;
16
17/* ot_mutex.c wakes the main loop through the self pipe when a result is
18 ready. The queue tests never get that far. */
19int g_self_pipe[2] = {-1, -1};
20long io_trywrite(long d, const char *buf, long len) {
21 (void)d;
22 (void)buf;
23 return len;
24}
25
26/* trackerlogic.c is under test, and starting it up starts every module it
27 leans on. None of them is driven by these tests, so they are answered here
28 rather than linked in and left to run threads of their own. */
29/* ot_clean.c is in the unit build for t_clean, so its thread control is the
30 real thing and only the stats hook it calls is stubbed here. */
31void fullscrape_init(void) {}
32void fullscrape_deinit(void) {}
33void stats_cleanup(void) {}
34void livesync_tell(struct ot_workstruct *ws) { (void)ws; }
35void stats_init(void) {}
36void stats_deinit(void) {}
37void stats_issue_event(struct ot_workstruct *ws, ot_status_event event, PROTO_FLAG proto, uintptr_t event_data) {
38 (void)ws;
39 (void)event;
40 (void)proto;
41 (void)event_data;
42}
43void stats_counters_register(struct ot_workstruct *ws) { (void)ws; }
44void stats_counters_retire(struct ot_workstruct *ws) { (void)ws; }
45
46const char *g_stats_path;
47ssize_t g_stats_path_len;
48uint32_t g_tracker_id;
diff --git a/tests/sync_daemon.pl b/tests/sync_daemon.pl
new file mode 100644
index 0000000..9e4bdb9
--- /dev/null
+++ b/tests/sync_daemon.pl
@@ -0,0 +1,294 @@
1#!/usr/bin/perl
2
3# This software was written by Philipp Wuensche <cryx-otsync@h3q.com>
4# It is considered beerware.
5
6use strict;
7
8#use Convert::Bencode_XS qw(:all);
9use Convert::Bencode qw(:all);
10use Data::Dumper;
11use LWP::UserAgent;
12use URI::Escape;
13
14# enable verbose output
15my $debug = 0;
16
17# tracker from where we get our sync data
18my @trackers = ('127.0.0.1:8989');
19# tracker to upload merged data
20my @client_tracker = ('127.0.0.1:8989');
21
22# time to wait between syncs
23my $sleeptime = '300';
24
25# SSL cert and key
26my $ssl_cert = 'cert.pem';
27my $ssl_key = 'key.pem';
28
29foreach(@trackers) {
30 print "Syncing from: $_\n";
31}
32foreach(@client_tracker) {
33 print "Syncing to: $_\n";
34}
35
36my $file = shift;
37
38
39# global hash for storing the merged syncs
40my %merged_syncs;
41
42while(1) {
43 %merged_syncs;
44 my @bencoded_sync_data;
45
46 # fetch the sync from every tracker and put it into an array in bencoded form
47 foreach my $tracker (@trackers) {
48 my $bencoded_sync = fetch_sync($tracker);
49# my $bencoded_sync = fetch_sync_from_file($file);
50 if($bencoded_sync ne 0 && $bencoded_sync =~ /^d4\:sync/) {
51 push(@bencoded_sync_data,$bencoded_sync);
52 }
53 }
54
55 # bdecode every sync and throw it into the merged-sync
56 foreach my $bencoded_sync (@bencoded_sync_data) {
57 print "Doing merge...\n";
58 merge_sync(bdecode($bencoded_sync));
59 my $num_torrents = keys(%merged_syncs);
60
61 print "number of torrents: $num_torrents\n";
62 }
63
64 # number of max. peers in one changeset
65 my $peer_limit = 500;
66 # max number of changesets per commit
67 my $max_changesets = 10;
68 my $hash_count = 0;
69 my $peer_count = 0;
70 my $changeset;
71 my @escaped_changesets;
72
73 # run until all hashes are put into changesets and commited to the trackers
74 while(keys(%merged_syncs) != 0) {
75
76 foreach my $hash (keys(%merged_syncs)) {
77 print "Starting new changeset\n" if($peer_count == 0 && $debug);
78 my $num_peers = keys(%{$merged_syncs{$hash}});
79
80 print "\t$peer_count peers for $hash_count hashes in changeset\n" if($debug);
81
82 my $pack_hash = pack('H*',$hash);
83
84 # as long as the peer_limit is not reached, add new hashes with peers to the changeset hash-table
85 if($peer_count < $peer_limit) {
86 print "\t\tAdd $num_peers peers for $hash changeset\n" if($debug);
87 $peer_count = $peer_count + $num_peers;
88 foreach my $peer_socket (keys(%{$merged_syncs{$hash}})) {
89
90 my $flags = $merged_syncs{$hash}{$peer_socket};
91
92 print "\t\t\tAdd $peer_socket $flags\n" if($debug);
93
94 my $pack_peer = packme($peer_socket,$flags);
95
96 $changeset->{'sync'}->{$pack_hash} = $changeset->{'sync'}->{$pack_hash}.$pack_peer;
97 }
98 $hash_count++;
99 # hash is stored in the changeset, delete it from the hash-table
100 delete $merged_syncs{$hash};
101 }
102
103 # the peer_limit is reached or we are out of torrents, so start preparing a changeset
104 if($peer_count >= $peer_limit || keys(%merged_syncs) == 0) {
105
106 print "Commit changeset for $hash_count hashes with $peer_count peers total\n" if($debug);
107
108 # bencode the changeset
109 my $enc_changeset = bencode($changeset);
110
111 # URL-escape the changeset and put into an array of changesets
112 my $foobar = uri_escape($enc_changeset);
113 push(@escaped_changesets,$foobar);
114
115 # the changeset is ready and stored, so delete it from the changeset hash-table
116 delete $changeset->{'sync'};
117
118 $hash_count = 0;
119 $peer_count = 0;
120 print "\n\n\n" if($debug);
121 }
122
123 # if enought changesets are prepared or we are out of torrents for more changesets,
124 # sync the changesets to the trackers
125 if($#escaped_changesets == $max_changesets || keys(%merged_syncs) == 0) {
126 print "\tSync...\n";
127 sync_to_tracker(\@escaped_changesets);
128 undef @escaped_changesets;
129 }
130
131 }
132 }
133
134 print "Sleeping for $sleeptime seconds\n";
135 sleep $sleeptime;
136}
137
138sub connect_tracker {
139 # connect a tracker via HTTPS, returns the body of the response
140 my $url = shift;
141
142 $ENV{HTTPS_DEBUG} = 0;
143 $ENV{HTTPS_CERT_FILE} = $ssl_cert;
144 $ENV{HTTPS_KEY_FILE} = $ssl_key;
145
146 my $ua = new LWP::UserAgent;
147 my $req = new HTTP::Request('GET', $url);
148 my $res = $ua->request($req);
149
150 my $content = $res->content;
151
152 if($res->is_success()) {
153 return $content;
154 } else {
155 print $res->code."|".$res->status_line."\n";
156 return 0;
157 }
158}
159
160sub sync_to_tracker {
161 # commit changesets to a tracker
162 my @changesets = @{(shift)};
163
164 # prepare the URI with URL-encoded changesets concatenated by a &
165 my $uri = 'sync?';
166 foreach my $set (@changesets) {
167 $uri .= 'changeset='.$set.'&';
168 }
169 my $uri_length = length($uri);
170
171 # commit the collection of changesets to the tracker via HTTPS
172 foreach my $tracker (@client_tracker) {
173 print "\t\tTracker: $tracker (URI: $uri_length)\n";
174 my $url = "https://$tracker/".$uri;
175 connect_tracker($url);
176 }
177}
178
179sub packme {
180 # pack data
181 # returns ipaddr, port and flags in packed format
182 my $peer_socket = shift;
183 my $flags = shift;
184
185 my($a,$b,$c,$d,$port) = split(/[\.,\:]/,$peer_socket);
186 my $pack_peer = pack('C4 n1 b16',$a,$b,$c,$d,$port,$flags);
187
188 return $pack_peer;
189}
190
191sub unpackme {
192 # unpack packed data
193 # returns ipaddr. in quad-form with port (a.b.c.d:port) and flags as bitfield
194 # data is packed as:
195 # - 4 byte ipaddr. (unsigned char value)
196 # - 2 byte port (unsigned short in "network" (big-endian) order)
197 # - 2 byte flags (bit string (ascending bit order inside each byte))
198 my $data = shift;
199
200 my($a, $b, $c, $d, $port, $flags) = unpack('C4 n1 b16',$data);
201 my $peer_socket = "$a\.$b\.$c\.$d\:$port";
202
203 return($peer_socket,$flags);
204}
205
206sub fetch_sync {
207 # fetch sync from a tracker
208 my $tracker = shift;
209 my $url = "https://$tracker/sync";
210
211 print "Fetching from $url\n";
212
213 my $body = connect_tracker($url);
214
215 if($body && $body =~ /^d4\:sync/) {
216 return $body;
217 } else {
218 return 0;
219 }
220}
221
222sub fetch_sync_from_file {
223 # fetch sync from a file
224 my $file = shift;
225 my $body;
226 print "Fetching from file $file\n";
227 open(FILE,"<$file");
228 while(<FILE>) {
229 $body .= $_;
230 }
231 close(FILE);
232 return $body;
233}
234
235sub merge_sync {
236 # This builds a hash table with the torrenthash as keys. The value is a hash table again with the peer-socket as keys
237 # and flags in the value
238 # Example:
239 # 60dd2beb4197f71677c0f5ba92b956f7d04651e5 =>
240 # 192.168.23.23:2323 => 0000000000000000
241 # 23.23.23.23:2342 => 0000000100000000
242 # b220b4d7136e84a88abc090db88bec8604a808f3 =>
243 # 42.23.42.23:55555 => 0000000000000000
244
245 my $hashref = shift;
246
247 my $nonuniq_hash_counter = 0;
248 my $nonuniq_peer_counter = 0;
249 my $hash_counter = 0;
250 my $peer_counter = 0;
251
252 foreach my $key (keys(%{$hashref->{'sync'}})) {
253 # start merge for every sha1-hash in the sync
254 my $hash = unpack('H*',$key);
255
256 $hash_counter++;
257 $nonuniq_hash_counter++ if exists $merged_syncs{$hash};
258
259 while(${$hashref->{'sync'}}{$key} ne "")
260 {
261 # split the value into 8-byte and unpack it for getting peer-socket and flags
262 my($peer_socket,$flags) = unpackme(substr(${$hashref->{'sync'}}{$key},0,8,''));
263
264 $peer_counter++;
265 $nonuniq_peer_counter++ if exists $merged_syncs{$hash}{$peer_socket};
266
267 # Create a hash table with sha1-hash as key and a hash table as value.
268 # The hash table in the value has the peer-socket as key and flags as value
269 # If the entry already exists, the flags are ORed together, if not it is ORed with 0
270 $merged_syncs{$hash}{$peer_socket} = $flags | $merged_syncs{$hash}{$peer_socket};
271 }
272 }
273 print "$hash_counter hashes $nonuniq_hash_counter non-uniq, $peer_counter peers $nonuniq_peer_counter non-uniq.\n";
274
275}
276
277sub test_decode {
278 my $hashref = shift;
279
280 print "CHANGESET DEBUG OUTPUT\n";
281
282 print Dumper $hashref;
283 foreach my $key (keys(%{$hashref->{'sync'}})) {
284 my $hash = unpack('H*',$key);
285
286 print "Changeset for $hash\n";
287 while(${$hashref->{'sync'}}{$key} ne "")
288 {
289
290 my($peer_socket,$flags) = unpackme(substr(${$hashref->{'sync'}}{$key},0,8,''));
291 print "\tSocket: $peer_socket Flags: $flags\n";
292 }
293 }
294}
diff --git a/tests/syscount.c b/tests/syscount.c
new file mode 100644
index 0000000..ec45c15
--- /dev/null
+++ b/tests/syscount.c
@@ -0,0 +1,144 @@
1/* Counts the system calls a run makes, by standing in front of libc.
2
3 cc -O2 -shared -fPIC -o syscount.so tests/syscount.c -ldl
4 LD_PRELOAD=./syscount.so ./opentracker -f conf (DYLD_INSERT_LIBRARIES on macOS)
5
6 The tally goes to stderr when the process exits. Reading the source tells
7 you which calls a path should make; this tells you which it does make,
8 which is not always the same thing. */
9
10#define _GNU_SOURCE
11#include <dlfcn.h>
12#include <stdarg.h>
13#include <stdatomic.h>
14#include <stdio.h>
15#include <sys/socket.h>
16#include <sys/types.h>
17#include <unistd.h>
18
19#ifdef __linux__
20#include <sys/epoll.h>
21#endif
22
23#define COUNTER(name) static _Atomic long g_##name
24#define BUMP(name) atomic_fetch_add_explicit(&g_##name, 1, memory_order_relaxed)
25#define REPORT(name) fprintf(stderr, " %-14s %10ld\n", #name, atomic_load(&g_##name))
26
27COUNTER(accept);
28COUNTER(accept4);
29COUNTER(read);
30COUNTER(write);
31COUNTER(close);
32COUNTER(fcntl);
33COUNTER(recvfrom);
34COUNTER(sendto);
35COUNTER(epoll_ctl);
36COUNTER(epoll_wait);
37
38typedef int (*fn_accept)(int, struct sockaddr *, socklen_t *);
39typedef int (*fn_accept4)(int, struct sockaddr *, socklen_t *, int);
40typedef ssize_t (*fn_read)(int, void *, size_t);
41typedef ssize_t (*fn_write)(int, const void *, size_t);
42typedef int (*fn_close)(int);
43typedef int (*fn_fcntl)(int, int, ...);
44typedef ssize_t (*fn_recvfrom)(int, void *, size_t, int, struct sockaddr *, socklen_t *);
45typedef ssize_t (*fn_sendto)(int, const void *, size_t, int, const struct sockaddr *, socklen_t);
46
47static fn_accept real_accept;
48static fn_accept4 real_accept4;
49static fn_read real_read;
50static fn_write real_write;
51static fn_close real_close;
52static fn_fcntl real_fcntl;
53static fn_recvfrom real_recvfrom;
54static fn_sendto real_sendto;
55
56/* Resolving lazily keeps the library out of the way until something is
57 actually called, which matters because dlsym itself allocates */
58#define WRAP(name) \
59 if (!real_##name) \
60 real_##name = (fn_##name)dlsym(RTLD_NEXT, #name); \
61 BUMP(name)
62
63int accept(int s, struct sockaddr *addr, socklen_t *len) {
64 WRAP(accept);
65 return real_accept(s, addr, len);
66}
67
68#ifdef SOCK_NONBLOCK
69int accept4(int s, struct sockaddr *addr, socklen_t *len, int flags) {
70 WRAP(accept4);
71 return real_accept4(s, addr, len, flags);
72}
73#endif
74
75ssize_t read(int fd, void *buf, size_t count) {
76 WRAP(read);
77 return real_read(fd, buf, count);
78}
79
80ssize_t write(int fd, const void *buf, size_t count) {
81 WRAP(write);
82 return real_write(fd, buf, count);
83}
84
85int close(int fd) {
86 WRAP(close);
87 return real_close(fd);
88}
89
90int fcntl(int fd, int cmd, ...) {
91 va_list args;
92 long arg;
93
94 va_start(args, cmd);
95 arg = va_arg(args, long);
96 va_end(args);
97 WRAP(fcntl);
98 return real_fcntl(fd, cmd, arg);
99}
100
101ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen) {
102 WRAP(recvfrom);
103 return real_recvfrom(s, buf, len, flags, from, fromlen);
104}
105
106ssize_t sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen) {
107 WRAP(sendto);
108 return real_sendto(s, buf, len, flags, to, tolen);
109}
110
111#ifdef __linux__
112typedef int (*fn_epoll_ctl)(int, int, int, struct epoll_event *);
113typedef int (*fn_epoll_wait)(int, struct epoll_event *, int, int);
114static fn_epoll_ctl real_epoll_ctl;
115static fn_epoll_wait real_epoll_wait;
116
117int epoll_ctl(int ep, int op, int fd, struct epoll_event *ev) {
118 WRAP(epoll_ctl);
119 return real_epoll_ctl(ep, op, fd, ev);
120}
121
122int epoll_wait(int ep, struct epoll_event *events, int max, int timeout) {
123 WRAP(epoll_wait);
124 return real_epoll_wait(ep, events, max, timeout);
125}
126#endif
127
128__attribute__((destructor)) static void report(void) {
129 fprintf(stderr, "\n system calls this run\n");
130 REPORT(accept);
131#ifdef SOCK_NONBLOCK
132 REPORT(accept4);
133#endif
134 REPORT(read);
135 REPORT(write);
136 REPORT(close);
137 REPORT(fcntl);
138 REPORT(recvfrom);
139 REPORT(sendto);
140#ifdef __linux__
141 REPORT(epoll_ctl);
142 REPORT(epoll_wait);
143#endif
144}
diff --git a/tests/t_accesslist.c b/tests/t_accesslist.c
new file mode 100644
index 0000000..14321f4
--- /dev/null
+++ b/tests/t_accesslist.c
@@ -0,0 +1,120 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdlib.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_accesslist.h"
10#include "test.h"
11
12#define A "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
13#define B "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
14#define C "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"
15
16static ot_hash dest[8];
17
18/* The parser is handed a mapped file, so it must never look at a byte beyond
19 the length it was given. These cases place a hex digit immediately after
20 that length: a parser that reads one byte too far sees it, decides the hash
21 runs on, and silently drops the last entry. */
22
23static void case_empty(void) {
24 test_case("an empty buffer yields nothing");
25 CHECK_INT(accesslist_parse_hashes(dest, 8, "", 0), 0);
26}
27
28static void case_single_with_newline(void) {
29 const char buf[] = A "\n";
30
31 test_case("one hash followed by a newline");
32 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 41), 1);
33}
34
35static void case_single_without_newline(void) {
36 const char buf[] = A "A";
37
38 test_case("one hash ending the buffer, with a hex digit just past the end");
39 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 40), 1);
40}
41
42static void case_several_last_without_newline(void) {
43 const char buf[] = A "\n" B "\n" C "C";
44
45 test_case("a final hash without a trailing newline still counts");
46 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 3 * 40 + 2), 3);
47}
48
49static void case_run_on_hash_is_rejected(void) {
50 const char buf[] = A "A\n";
51
52 test_case("forty one hex digits are not a hash");
53 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 42), 0);
54}
55
56static void case_junk_lines_skipped(void) {
57 const char buf[] = "# a comment\n" A "\nnot a hash\n" B "\n";
58
59 test_case("lines that are not hashes are ignored");
60 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, sizeof(buf) - 1), 2);
61}
62
63static void case_trailing_junk_on_line(void) {
64 const char buf[] = A " some comment\n" B "\n";
65
66 test_case("a hash followed by other text on the same line still counts");
67 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, sizeof(buf) - 1), 2);
68}
69
70static void case_capacity_is_respected(void) {
71 const char buf[] = A "\n" B "\n" C "\n";
72
73 test_case("no more than capacity hashes are written");
74 CHECK_INT(accesslist_parse_hashes(dest, 2, buf, sizeof(buf) - 1), 2);
75}
76
77static void case_zero_capacity_never_writes(void) {
78 const char buf[] = A "\n";
79
80 test_case("a zero capacity tolerates a null destination");
81 CHECK_INT(accesslist_parse_hashes(NULL, 0, buf, 41), 0);
82}
83
84static void case_decoded_value(void) {
85 const char buf[] = "000102030405060708090A0B0C0D0E0F10111213\n";
86 const uint8_t want[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
87
88 test_case("the hash is decoded, not merely counted");
89 CHECK_INT(accesslist_parse_hashes(dest, 8, buf, 41), 1);
90 CHECK_MEM(dest[0], want, sizeof(want));
91}
92
93static void case_capacity_bound_holds(void) {
94 /* (len + 1) / 41 is what accesslist_readfile allocates. Pack a buffer as
95 densely as the parser allows and check the bound is not exceeded. */
96 char buf[41 * 4];
97 size_t len, capacity, found;
98
99 test_case("the capacity formula bounds what the parser can produce");
100 memcpy(buf, A "\n" B "\n" C "\n" A, 4 * 40 + 3);
101 len = 4 * 40 + 3;
102 capacity = (len + 1) / 41;
103 found = accesslist_parse_hashes(dest, 8, buf, len);
104 CHECK_INT(found, 4);
105 CHECK(found <= capacity);
106}
107
108void test_accesslist(void) {
109 case_empty();
110 case_single_with_newline();
111 case_single_without_newline();
112 case_several_last_without_newline();
113 case_run_on_hash_is_rejected();
114 case_junk_lines_skipped();
115 case_trailing_junk_on_line();
116 case_capacity_is_respected();
117 case_zero_capacity_never_writes();
118 case_decoded_value();
119 case_capacity_bound_holds();
120}
diff --git a/tests/t_batch.c b/tests/t_batch.c
new file mode 100644
index 0000000..5a7ac1e
--- /dev/null
+++ b/tests/t_batch.c
@@ -0,0 +1,346 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <fcntl.h>
6#include <poll.h>
7#include <stdlib.h>
8#include <string.h>
9#include <sys/socket.h>
10#include <unistd.h>
11
12/* Opentracker */
13#include "ot_batch.h"
14#include "test.h"
15
16/* The batch writes to a real socket pair, because what is worth pinning down
17 is what it does when the kernel takes only part of what it was offered. */
18
19static char *dup_of(const char *text) {
20 size_t len = strlen(text);
21 char *copy = malloc(len);
22
23 memcpy(copy, text, len);
24 return copy;
25}
26
27static void drain(int s, char *into, size_t len) {
28 size_t got = 0;
29
30 while (got < len) {
31 ssize_t r = read(s, into + got, len - got);
32
33 if (r <= 0)
34 break;
35 got += (size_t)r;
36 }
37 into[got] = 0;
38}
39
40static void case_queue_accounting(void) {
41 ot_batch batch;
42
43 memset(&batch, 0, sizeof(batch));
44
45 test_case("a zeroed batch is empty and sends nothing");
46 CHECK_INT(batch_pending(&batch), 0);
47 CHECK_INT(batch_send(-1, &batch), BATCH_DONE);
48
49 test_case("anything queued makes it pending");
50 CHECK_INT(batch_add(&batch, dup_of("hello "), 6), 0);
51 CHECK_INT(batch_add_copy(&batch, "world", 5), 0);
52 CHECK_INT(batch_pending(&batch), 1);
53 CHECK_INT(batch.count, 2);
54
55 batch_reset(&batch);
56 test_case("and a reset empties it");
57 CHECK_INT(batch_pending(&batch), 0);
58 CHECK_PTR(batch.entries, NULL);
59}
60
61static void case_send_in_one_go(void) {
62 ot_batch batch;
63 int sv[2];
64 char got[32];
65
66 memset(&batch, 0, sizeof(batch));
67 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
68
69 test_case("several buffers arrive as one stream, in order");
70 CHECK_INT(batch_add(&batch, dup_of("opentracker"), 11), 0);
71 CHECK_INT(batch_add_copy(&batch, " says ", 6), 0);
72 CHECK_INT(batch_add(&batch, dup_of("hello"), 5), 0);
73 CHECK_INT(batch_send(sv[0], &batch), 22);
74 CHECK_INT(batch_pending(&batch), 0);
75
76 drain(sv[1], got, 22);
77 CHECK_STR(got, "opentracker says hello");
78
79 test_case("and an empty batch reports it has nothing left");
80 CHECK_INT(batch_send(sv[0], &batch), BATCH_DONE);
81
82 batch_reset(&batch);
83 close(sv[0]);
84 close(sv[1]);
85}
86
87/* Send everything the batch holds, reading the other end as we go so the
88 socket never stays full, and return what arrived. */
89static size_t pump(int writer, int reader, ot_batch *batch, char *into, size_t room) {
90 size_t got = 0;
91
92 while (batch_pending(batch) || got < room) {
93 ssize_t r;
94
95 if (batch_pending(batch)) {
96 ssize_t res = batch_send(writer, batch);
97
98 if (res == BATCH_FAILED)
99 break;
100 if (res > 0)
101 continue;
102 }
103
104 r = read(reader, into + got, room - got);
105 if (r <= 0)
106 break;
107 got += (size_t)r;
108 }
109 return got;
110}
111
112static void case_partial_write_resumes(void) {
113 const size_t size = 200000;
114 ot_batch batch;
115 int sv[2], sndbuf = 4096;
116 char *sent, *got;
117 size_t i, arrived;
118
119 memset(&batch, 0, sizeof(batch));
120 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
121 setsockopt(sv[0], SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
122 fcntl(sv[0], F_SETFL, fcntl(sv[0], F_GETFL, 0) | O_NONBLOCK);
123
124 sent = malloc(size);
125 got = malloc(size);
126 for (i = 0; i < size; ++i)
127 sent[i] = (char)(i % 251);
128
129 test_case("a buffer the kernel takes in pieces arrives whole and in order");
130 CHECK_INT(batch_add(&batch, memcpy(malloc(size), sent, size), size), 0);
131 arrived = pump(sv[0], sv[1], &batch, got, size);
132 CHECK_INT(arrived, size);
133 CHECK_INT(batch_pending(&batch), 0);
134 CHECK_MEM(got, sent, size);
135
136 free(sent);
137 free(got);
138 batch_reset(&batch);
139 close(sv[0]);
140 close(sv[1]);
141}
142
143/* writev refuses more than IOV_MAX entries at once, so a long batch has to be
144 sent across several calls. */
145static void case_more_entries_than_one_writev(void) {
146 const size_t entries = 3000, each = 4;
147 ot_batch batch;
148 int sv[2], sndbuf = 4096;
149 char *sent, *got;
150 size_t i, arrived, refused = 0;
151
152 memset(&batch, 0, sizeof(batch));
153 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
154 setsockopt(sv[0], SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
155 fcntl(sv[0], F_SETFL, fcntl(sv[0], F_GETFL, 0) | O_NONBLOCK);
156
157 sent = malloc(entries * each);
158 got = malloc(entries * each);
159
160 test_case("a batch of more entries than writev accepts still arrives whole");
161 for (i = 0; i < entries; ++i) {
162 char piece[4];
163
164 piece[0] = (char)(i), piece[1] = (char)(i >> 8), piece[2] = 'x', piece[3] = 'y';
165 memcpy(sent + i * each, piece, each);
166 if (batch_add(&batch, memcpy(malloc(each), piece, each), each))
167 ++refused;
168 }
169 CHECK_INT(refused, 0);
170 CHECK_INT(batch.count, entries);
171
172 arrived = pump(sv[0], sv[1], &batch, got, entries * each);
173 CHECK_INT(arrived, entries * each);
174 CHECK_MEM(got, sent, entries * each);
175
176 free(sent);
177 free(got);
178 batch_reset(&batch);
179 close(sv[0]);
180 close(sv[1]);
181}
182
183static void case_reset_frees_the_unsent(void) {
184 ot_batch batch;
185 int sv[2];
186
187 memset(&batch, 0, sizeof(batch));
188 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
189
190 test_case("a batch torn down mid flight keeps no bytes outstanding");
191 CHECK_INT(batch_add(&batch, dup_of("first"), 5), 0);
192 CHECK_INT(batch_add(&batch, dup_of("second"), 6), 0);
193 CHECK_INT(batch_send(sv[0], &batch), 11);
194 CHECK_INT(batch_add(&batch, dup_of("never sent"), 10), 0);
195 CHECK_INT(batch_pending(&batch), 1);
196
197 /* Whether the unsent buffer is freed is for the sanitizer to say */
198 batch_reset(&batch);
199 CHECK_INT(batch_pending(&batch), 0);
200 CHECK_INT(batch.count, 0);
201
202 close(sv[0]);
203 close(sv[1]);
204}
205
206static void case_closed_socket_is_fatal(void) {
207 ot_batch batch;
208 int sv[2];
209
210 memset(&batch, 0, sizeof(batch));
211 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
212 close(sv[1]);
213
214 test_case("writing to a socket whose peer is gone reports a dead connection");
215 CHECK_INT(batch_add(&batch, dup_of("nobody is listening"), 19), 0);
216 CHECK_INT(batch_send(sv[0], &batch), BATCH_FAILED);
217
218 batch_reset(&batch);
219 close(sv[0]);
220}
221
222static void case_vector_is_taken_whole(void) {
223 ot_batch batch;
224 struct iovec *vector = malloc(3 * sizeof(struct iovec));
225 int sv[2];
226 char got[32];
227
228 memset(&batch, 0, sizeof(batch));
229 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
230
231 test_case("a whole vector is queued in one go, in order");
232 vector[0].iov_base = dup_of("one "), vector[0].iov_len = 4;
233 vector[1].iov_base = dup_of("two "), vector[1].iov_len = 4;
234 vector[2].iov_base = dup_of("three"), vector[2].iov_len = 5;
235 CHECK_INT(batch_add_vector(&batch, vector, 3), 0);
236 free(vector);
237 CHECK_INT(batch.count, 3);
238 CHECK_INT(batch_send(sv[0], &batch), 13);
239
240 drain(sv[1], got, 13);
241 CHECK_STR(got, "one two three");
242
243 batch_reset(&batch);
244 close(sv[0]);
245 close(sv[1]);
246}
247
248/* The entry array starts small and doubles, so crossing that boundary one
249 buffer at a time is worth its own case. */
250static void case_growing_one_entry_at_a_time(void) {
251 const size_t entries = 100;
252 ot_batch batch;
253 int sv[2];
254 char sent[400], got[401];
255 size_t i, refused = 0;
256
257 memset(&batch, 0, sizeof(batch));
258 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
259
260 test_case("a batch grown one buffer at a time keeps them all, in order");
261 for (i = 0; i < entries; ++i) {
262 char piece[4];
263
264 piece[0] = (char)('a' + i % 26), piece[1] = (char)('0' + i % 10);
265 piece[2] = (char)('A' + i % 26), piece[3] = '.';
266 memcpy(sent + i * 4, piece, 4);
267 if (batch_add(&batch, memcpy(malloc(4), piece, 4), 4))
268 ++refused;
269 }
270 CHECK_INT(refused, 0);
271 CHECK_INT(batch.count, entries);
272 CHECK_INT(batch_send(sv[0], &batch), (ssize_t)(entries * 4));
273
274 drain(sv[1], got, entries * 4);
275 CHECK_MEM(got, sent, entries * 4);
276
277 batch_reset(&batch);
278 close(sv[0]);
279 close(sv[1]);
280}
281
282/* Appending while earlier entries are still on their way is what a chunked
283 transfer does. Rather than depend on when a kernel decides to block, this
284 takes entries off the front the way a completed send would and checks that
285 the array reuses the space instead of growing. */
286static void case_append_while_sending(void) {
287 const size_t per_round = 12, each = 8;
288 ot_batch batch;
289 int sv[2];
290 char expected[16], got[17];
291 size_t i, round, refused = 0, space_after_first = 0;
292
293 memset(&batch, 0, sizeof(batch));
294 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv), 0);
295
296 test_case("an array whose front has gone out is reused, not grown");
297 for (round = 0; round < 8; ++round) {
298 for (i = 0; i < per_round; ++i) {
299 /* Distinct per entry, so a move from the wrong index shows up */
300 char *piece = malloc(each);
301
302 memset(piece, (int)('a' + (round * per_round + i) % 26), each);
303 piece[0] = (char)('0' + i);
304 piece[1] = (char)('0' + round);
305 if (batch_add(&batch, piece, each))
306 ++refused;
307 }
308
309 /* All but the last entry have left and been freed */
310 while (batch.count - batch.first > 1)
311 free(batch.entries[batch.first++].iov_base);
312
313 if (!round)
314 space_after_first = batch.space;
315 }
316 CHECK_INT(refused, 0);
317 CHECK_INT(batch.space, space_after_first);
318
319 test_case("and what is still queued survives the move, in order");
320 CHECK_INT(batch.count - batch.first, 1);
321 CHECK_INT(batch_add(&batch, memset(malloc(each), 'Z', each), each), 0);
322 CHECK_INT(batch_send(sv[0], &batch), (ssize_t)(2 * each));
323
324 memset(expected, (int)('a' + (7 * per_round + per_round - 1) % 26), each);
325 expected[0] = (char)('0' + per_round - 1);
326 expected[1] = '7';
327 memset(expected + each, 'Z', each);
328 drain(sv[1], got, 2 * each);
329 CHECK_MEM(got, expected, 2 * each);
330
331 batch_reset(&batch);
332 close(sv[0]);
333 close(sv[1]);
334}
335
336void test_batch(void) {
337 case_queue_accounting();
338 case_send_in_one_go();
339 case_vector_is_taken_whole();
340 case_growing_one_entry_at_a_time();
341 case_append_while_sending();
342 case_partial_write_resumes();
343 case_more_entries_than_one_writev();
344 case_reset_frees_the_unsent();
345 case_closed_socket_is_fatal();
346}
diff --git a/tests/t_buf.c b/tests/t_buf.c
new file mode 100644
index 0000000..39c44f1
--- /dev/null
+++ b/tests/t_buf.c
@@ -0,0 +1,203 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_buf.h"
10#include "test.h"
11
12static void case_starts_empty(void) {
13 ot_buf buf = {NULL, 0};
14
15 test_case("a fresh buffer holds nothing and has no data pointer");
16 CHECK_PTR(buf.data, NULL);
17 CHECK_INT(buf.size, 0);
18}
19
20static void case_cat_appends(void) {
21 ot_buf buf = {NULL, 0};
22
23 test_case("appends concatenate in order and report success");
24 CHECK_INT(buf_cat(&buf, "GET /ann", 8), 0);
25 CHECK(buf.data != NULL);
26 CHECK_INT(buf.size, 8);
27 CHECK_INT(buf_cat(&buf, "ounce", 5), 0);
28 CHECK_INT(buf.size, 13);
29 CHECK_MEM(buf.data, "GET /announce", 13);
30 buf_reset(&buf);
31}
32
33static void case_cat_of_nothing_allocates_nothing(void) {
34 ot_buf buf = {NULL, 0};
35
36 /* handle_read tells an untouched buffer from a partial request by the data
37 pointer, so a zero length append must not quietly allocate one */
38 test_case("appending zero bytes leaves the buffer untouched");
39 CHECK_INT(buf_cat(&buf, "ignored", 0), 0);
40 CHECK_PTR(buf.data, NULL);
41 CHECK_INT(buf.size, 0);
42 buf_reset(&buf);
43}
44
45static void case_grows_across_many_appends(void) {
46 ot_buf buf = {NULL, 0};
47 char chunk[100];
48 size_t i;
49
50 test_case("content survives growing one packet at a time");
51 memset(chunk, 'x', sizeof(chunk));
52 for (i = 0; i < 100; ++i)
53 if (buf_cat(&buf, chunk, sizeof(chunk))) {
54 test_failf(__FILE__, __LINE__, "append %zu was refused", i);
55 buf_reset(&buf);
56 return;
57 }
58 ++test_checks;
59 CHECK_INT(buf.size, 10000);
60 for (i = 0; i < 10000; ++i)
61 if (buf.data[i] != 'x') {
62 test_failf(__FILE__, __LINE__, "byte %zu was not preserved across growth", i);
63 buf_reset(&buf);
64 return;
65 }
66 ++test_checks;
67 buf_reset(&buf);
68}
69
70static void case_grows_one_byte_at_a_time(void) {
71 ot_buf buf = {NULL, 0};
72 size_t i;
73
74 /* The shape a trickling client produces. Nothing here is optimised for it,
75 so the point is only that it stays correct. */
76 test_case("a byte at a time accumulates correctly");
77 for (i = 0; i < 2048; ++i) {
78 char c = (char)('a' + (i % 26));
79 if (buf_cat(&buf, &c, 1)) {
80 test_failf(__FILE__, __LINE__, "append %zu was refused", i);
81 buf_reset(&buf);
82 return;
83 }
84 }
85 ++test_checks;
86 CHECK_INT(buf.size, 2048);
87 for (i = 0; i < 2048; ++i)
88 if (buf.data[i] != (char)('a' + (i % 26))) {
89 test_failf(__FILE__, __LINE__, "byte %zu differs", i);
90 buf_reset(&buf);
91 return;
92 }
93 ++test_checks;
94 buf_reset(&buf);
95}
96
97static void case_truncate_shrinks_only(void) {
98 ot_buf buf = {NULL, 0};
99
100 test_case("truncate drops the tail but never grows");
101 buf_cat(&buf, "0123456789", 10);
102 buf_truncate(&buf, 4);
103 CHECK_INT(buf.size, 4);
104 CHECK_MEM(buf.data, "0123", 4);
105
106 buf_truncate(&buf, 9);
107 CHECK_INT(buf.size, 4);
108 buf_truncate(&buf, 4);
109 CHECK_INT(buf.size, 4);
110
111 buf_truncate(&buf, 0);
112 CHECK_INT(buf.size, 0);
113 buf_reset(&buf);
114}
115
116static void case_append_after_truncate(void) {
117 ot_buf buf = {NULL, 0};
118
119 test_case("appending after a truncate overwrites the dropped tail");
120 buf_cat(&buf, "keepdrop", 8);
121 buf_truncate(&buf, 4);
122 CHECK_INT(buf_cat(&buf, "MORE", 4), 0);
123 CHECK_INT(buf.size, 8);
124 CHECK_MEM(buf.data, "keepMORE", 8);
125 buf_reset(&buf);
126}
127
128static void case_reset_clears_everything(void) {
129 ot_buf buf = {NULL, 0};
130
131 test_case("reset releases the buffer and restores the initial state");
132 buf_cat(&buf, "something", 9);
133 buf_reset(&buf);
134 CHECK_PTR(buf.data, NULL);
135 CHECK_INT(buf.size, 0);
136}
137
138static void case_reset_of_empty_is_safe(void) {
139 ot_buf buf = {NULL, 0};
140
141 test_case("resetting a buffer that was never used is harmless");
142 buf_reset(&buf);
143 buf_reset(&buf);
144 CHECK_PTR(buf.data, NULL);
145 CHECK_INT(buf.size, 0);
146}
147
148static void case_refused_append_is_harmless(void) {
149 ot_buf buf = {NULL, 0};
150
151 /* A length that would wrap the size is rejected before src is read and
152 before anything is allocated, so a short string is safe to pass here.
153 A refused append must not destroy the partial request already collected:
154 the caller answers and closes rather than losing both. */
155 test_case("a length that would wrap the size is refused");
156 CHECK_INT(buf_cat(&buf, "already here", 12), 0);
157 CHECK_INT(buf_cat(&buf, "x", (size_t)-1), -1);
158
159 test_case("and earlier content survives it");
160 CHECK_INT(buf.size, 12);
161 CHECK_MEM(buf.data, "already here", 12);
162
163 test_case("and the buffer still works afterwards");
164 CHECK_INT(buf_cat(&buf, "!", 1), 0);
165 CHECK_INT(buf.size, 13);
166 CHECK_MEM(buf.data, "already here!", 13);
167 buf_reset(&buf);
168}
169
170static void case_accumulates_a_split_request(void) {
171 /* What handle_read actually does: collect a request that arrived in
172 pieces, then hand over the whole of it */
173 ot_buf buf = {NULL, 0};
174 const char *pieces[] = {"GET /announce?info_hash=", "0123456789abcdefghij", " HTTP/1.0\r\n\r\n"};
175 size_t i;
176
177 test_case("a request split over several reads is reassembled");
178 for (i = 0; i < 3; ++i)
179 if (buf_cat(&buf, pieces[i], strlen(pieces[i]))) {
180 test_failf(__FILE__, __LINE__, "piece %zu was refused", i);
181 buf_reset(&buf);
182 return;
183 }
184 ++test_checks;
185
186 CHECK_INT(buf.size, 24 + 20 + 13);
187 CHECK_MEM(buf.data, "GET /announce?info_hash=0123456789abcdefghij HTTP/1.0\r\n\r\n", 57);
188 buf_reset(&buf);
189}
190
191void test_buf(void) {
192 case_starts_empty();
193 case_cat_appends();
194 case_cat_of_nothing_allocates_nothing();
195 case_grows_across_many_appends();
196 case_grows_one_byte_at_a_time();
197 case_truncate_shrinks_only();
198 case_append_after_truncate();
199 case_reset_clears_everything();
200 case_reset_of_empty_is_safe();
201 case_refused_append_is_harmless();
202 case_accumulates_a_split_request();
203}
diff --git a/tests/t_clean.c b/tests/t_clean.c
new file mode 100644
index 0000000..ce17bc3
--- /dev/null
+++ b/tests/t_clean.c
@@ -0,0 +1,222 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#include <arpa/inet.h>
5#include <signal.h>
6#include <pthread.h>
7#include <string.h>
8
9#include "ot_clean.h"
10#include "ot_mutex.h"
11#include "trackerlogic.h"
12#include "test.h"
13
14/* A clock stepped backwards used to leave the torrent's base in the future, so
15 the span the cleaner works from came out negative. It was then added to a
16 peer's age and stored in the single byte that age lives in, where -1 reads
17 as 255 and the next pass threw the whole swarm away. */
18
19static void announce(struct ot_workstruct *ws, ot_hash *hash, uint8_t last_octet, int seeding) {
20 static const uint8_t v4mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
21
22 /* The peer list is written into the reply, which workstruct_init leaves
23 for its caller to point somewhere */
24 ws->reply = ws->outbuf;
25
26 memset(&ws->peer, 0, sizeof(ws->peer));
27 memcpy(&ws->peer, v4mapped, sizeof(v4mapped));
28 ((uint8_t *)&ws->peer)[15] = last_octet;
29 OT_SETPORT(&ws->peer, &(uint16_t){6881});
30 if (seeding)
31 OT_PEERFLAG(ws->peer) |= PEER_FLAG_SEEDING;
32 ws->hash = hash;
33 add_peer_to_torrent_and_return_peers(FLAG_TCP, ws, 0);
34}
35
36/* A distinct v4 peer addressed by two octets, to build swarms past 256 */
37static size_t announce_wide(struct ot_workstruct *ws, ot_hash *hash, unsigned int which, size_t amount) {
38 static const uint8_t v4mapped[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
39
40 ws->reply = ws->outbuf;
41 memset(&ws->peer, 0, sizeof(ws->peer));
42 memcpy(&ws->peer, v4mapped, sizeof(v4mapped));
43 ((uint8_t *)&ws->peer)[14] = (uint8_t)(which >> 8);
44 ((uint8_t *)&ws->peer)[15] = (uint8_t)which;
45 OT_SETPORT(&ws->peer, &(uint16_t){6881});
46 ws->hash = hash;
47 return add_peer_to_torrent_and_return_peers(FLAG_TCP, ws, amount);
48}
49
50static size_t peers_in(ot_hash *hash) {
51 char reply[1024];
52 size_t len = return_udp_scrape_for_torrent(*hash, reply);
53 uint32_t seeders, leechers;
54
55 if (len < 12)
56 return 0;
57 memcpy(&seeders, reply, 4);
58 memcpy(&leechers, reply + 8, 4);
59 return (size_t)ntohl(seeders) + (size_t)ntohl(leechers);
60}
61
62static ot_torrent *torrent_of(ot_hash *hash) {
63 ot_vector *bucket = mutex_bucket_lock_by_hash(*hash);
64 ot_torrent *t = (ot_torrent *)bucket->data;
65 ot_torrent *found = NULL;
66 size_t i;
67
68 for (i = 0; i < bucket->size; ++i)
69 if (!memcmp(t[i].hash, hash, sizeof(ot_hash)))
70 found = t + i;
71 mutex_bucket_unlock_by_hash(*hash, 0);
72 return found;
73}
74
75/* What a clock stepped back by `minutes` leaves behind */
76static void step_clock_back(ot_torrent *torrent, int minutes) {
77 torrent->base += minutes;
78}
79
80/* What the next minute of a well behaved clock looks like */
81static void age_by_a_minute(ot_torrent *torrent) {
82 torrent->base -= 1;
83}
84
85static void case_a_clock_that_went_back_keeps_the_swarm(void) {
86 struct ot_workstruct ws;
87 ot_hash hash;
88 ot_torrent *torrent;
89
90 test_case("a swarm survives the clock being stepped backwards");
91 memset(hash, 0x31, sizeof(hash));
92 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
93
94 announce(&ws, &hash, 1, 1);
95 announce(&ws, &hash, 2, 0);
96 CHECK_INT(peers_in(&hash), 2);
97
98 torrent = torrent_of(&hash);
99 CHECK(torrent != NULL);
100 step_clock_back(torrent, 5);
101
102 /* The pass that sees the step keeps everybody either way: unclamped it
103 writes a negative span into each peer's age byte, where it reads as 251
104 rather than as a removal. */
105 CHECK_INT(clean_single_torrent(torrent), 0);
106 CHECK_INT(peers_in(&hash), 2);
107
108 /* A minute later, and this is where a poisoned age byte took the swarm:
109 251 plus one minute is past any timeout. */
110 age_by_a_minute(torrent);
111 CHECK_INT(clean_single_torrent(torrent), 0);
112 CHECK_INT(peers_in(&hash), 2);
113
114 workstruct_deinit(&ws);
115}
116
117static void case_an_idle_swarm_still_ages_out(void) {
118 struct ot_workstruct ws;
119 ot_hash hash;
120 ot_torrent *torrent;
121
122 test_case("a swarm nobody touched is still cleaned away");
123 memset(hash, 0x32, sizeof(hash));
124 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
125
126 announce(&ws, &hash, 3, 1);
127 CHECK_INT(peers_in(&hash), 1);
128
129 torrent = torrent_of(&hash);
130 CHECK(torrent != NULL);
131 step_clock_back(torrent, -OT_PEER_TIMEOUT);
132
133 CHECK_INT(clean_single_torrent(torrent), 0);
134 CHECK_INT(peers_in(&hash), 0);
135
136 workstruct_deinit(&ws);
137}
138
139static void case_empty_torrent_timeout_bounds_a_counter_only_torrent(void) {
140 struct ot_workstruct ws;
141 ot_hash hash;
142 ot_torrent *torrent;
143 ot_time saved = g_empty_torrent_timeout;
144
145 test_case("the empty torrent timeout bounds a counter-only torrent's life");
146 memset(hash, 0x33, sizeof(hash));
147 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
148
149 announce(&ws, &hash, 7, 1);
150 torrent = torrent_of(&hash);
151 CHECK(torrent != NULL);
152 torrent->down_count = 1; /* one completed download to remember it by */
153
154 /* Age the only peer out: the torrent falls empty but keeps its count */
155 step_clock_back(torrent, -OT_PEER_TIMEOUT);
156 CHECK_INT(clean_single_torrent(torrent), 0);
157 CHECK_INT(peers_in(&hash), 0);
158
159 /* Carry it a little past a short empty-torrent timeout */
160 step_clock_back(torrent, -10);
161
162 /* The default, matching the torrent timeout, still holds it for the count */
163 g_empty_torrent_timeout = OT_TORRENT_TIMEOUT;
164 CHECK_INT(clean_single_torrent(torrent), 0);
165
166 /* A timeout it has now exceeded lets the next sweep drop it */
167 g_empty_torrent_timeout = OT_PEER_TIMEOUT + 5;
168 CHECK_INT(clean_single_torrent(torrent), 1);
169
170 g_empty_torrent_timeout = saved;
171 workstruct_deinit(&ws);
172}
173
174static void case_a_bucketed_swarm_survives_clean_and_serves(void) {
175 struct ot_workstruct ws;
176 ot_hash hash;
177 ot_torrent *torrent;
178 unsigned int i;
179 const unsigned int n = 600; /* past OT_PEER_BUCKET_MINCOUNT (512) */
180
181 test_case("a swarm large enough to be bucketed cleans, splits and serves without loss");
182 memset(hash, 0x34, sizeof(hash));
183 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
184
185 for (i = 0; i < n; ++i)
186 announce_wide(&ws, &hash, i, 0);
187 CHECK_INT(peers_in(&hash), n);
188
189 torrent = torrent_of(&hash);
190 CHECK(torrent != NULL);
191 CHECK(torrent->peer_list != NULL);
192
193 /* A clean with a minute elapsed splits the flat vector into buckets */
194 step_clock_back(torrent, -1);
195 CHECK_INT(clean_single_torrent(torrent), 0);
196 CHECK(torrent->peer_list != NULL);
197 CHECK_INT(OT_VECTOR_HASBUCKETS(&torrent->peer_list->peers4), 1);
198 CHECK_INT(peers_in(&hash), n);
199
200 /* Serve a selection back, which walks the bucket list */
201 CHECK(announce_wide(&ws, &hash, 1, 200) > 0);
202 CHECK_INT(peers_in(&hash), n);
203
204 workstruct_deinit(&ws);
205}
206
207void test_clean(void) {
208 sigset_t hup;
209
210 /* accesslist_deinit sends SIGHUP to its reader, trackerlogic_init starts
211 the accesslist, and the test process must not take it */
212 sigemptyset(&hup);
213 sigaddset(&hup, SIGHUP);
214 pthread_sigmask(SIG_BLOCK, &hup, NULL);
215
216 trackerlogic_init();
217 case_a_clock_that_went_back_keeps_the_swarm();
218 case_an_idle_swarm_still_ages_out();
219 case_empty_torrent_timeout_bounds_a_counter_only_torrent();
220 case_a_bucketed_swarm_survives_clean_and_serves();
221 trackerlogic_deinit();
222}
diff --git a/tests/t_event.c b/tests/t_event.c
new file mode 100644
index 0000000..5c45089
--- /dev/null
+++ b/tests/t_event.c
@@ -0,0 +1,289 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <fcntl.h>
6#include <string.h>
7#include <sys/socket.h>
8#include <sys/time.h>
9#include <unistd.h>
10
11/* Opentracker */
12#include "ot_event.h"
13#include "test.h"
14
15/* Against real socket pairs: only the kernel can say whether a descriptor is
16 ready, so there is nothing useful to mock here. */
17
18#define EVENTS 16
19
20static int sv[2];
21static ot_event ready[EVENTS];
22
23static void pair_open(void) {
24 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1)
25 sv[0] = sv[1] = -1;
26}
27
28static void pair_close(void) {
29 if (sv[0] != -1)
30 close(sv[0]);
31 if (sv[1] != -1)
32 close(sv[1]);
33 sv[0] = sv[1] = -1;
34}
35
36static int wait_for(int fd, int what, int timeout_ms, uint32_t *generation) {
37 int count = event_wait(ready, EVENTS, timeout_ms), i;
38
39 for (i = 0; i < count; ++i)
40 if (ready[i].fd == fd && (ready[i].what & what)) {
41 if (generation)
42 *generation = ready[i].generation;
43 return 1;
44 }
45 return 0;
46}
47
48static unsigned long elapsed_ms(struct timeval *since) {
49 struct timeval now;
50
51 gettimeofday(&now, NULL);
52 return (unsigned long)((now.tv_sec - since->tv_sec) * 1000 + (now.tv_usec - since->tv_usec) / 1000);
53}
54
55static void case_readable(void) {
56 uint32_t generation = 0;
57
58 test_case("a descriptor with something to read is reported, with its generation");
59 pair_open();
60 CHECK(sv[0] != -1);
61 CHECK_INT(event_add(sv[0], EVENT_IN, 4711), 0);
62 CHECK_INT(write(sv[1], "x", 1), 1);
63 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, &generation), 1);
64 CHECK_INT(generation, 4711);
65
66 test_case("and keeps being reported until it is read");
67 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, NULL), 1);
68 {
69 char scratch[4];
70 CHECK_INT(read(sv[0], scratch, sizeof(scratch)), 1);
71 }
72 CHECK_INT(wait_for(sv[0], EVENT_IN, 50, NULL), 0);
73
74 CHECK_INT(event_del(sv[0]), 0);
75 pair_close();
76}
77
78static void case_writable(void) {
79 test_case("a descriptor with room to write is reported");
80 pair_open();
81 CHECK(sv[0] != -1);
82 CHECK_INT(event_add(sv[0], EVENT_OUT, 1), 0);
83 CHECK_INT(wait_for(sv[0], EVENT_OUT, 1000, NULL), 1);
84
85 test_case("and is not, once we say we no longer care");
86 CHECK_INT(event_modify(sv[0], EVENT_IN, 1), 0);
87 CHECK_INT(wait_for(sv[0], EVENT_OUT, 50, NULL), 0);
88
89 CHECK_INT(event_del(sv[0]), 0);
90 pair_close();
91}
92
93static void case_interest_is_separate(void) {
94 test_case("asking only about writing does not report reading");
95 pair_open();
96 CHECK(sv[0] != -1);
97 CHECK_INT(event_add(sv[0], EVENT_OUT, 1), 0);
98 CHECK_INT(write(sv[1], "x", 1), 1);
99 CHECK_INT(wait_for(sv[0], EVENT_IN, 50, NULL), 0);
100
101 test_case("until we ask about it");
102 CHECK_INT(event_modify(sv[0], EVENT_IN | EVENT_OUT, 1), 0);
103 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, NULL), 1);
104
105 CHECK_INT(event_del(sv[0]), 0);
106 pair_close();
107}
108
109static void case_removed_is_silent(void) {
110 test_case("a removed descriptor is not reported again");
111 pair_open();
112 CHECK(sv[0] != -1);
113 CHECK_INT(event_add(sv[0], EVENT_IN, 1), 0);
114 CHECK_INT(write(sv[1], "x", 1), 1);
115 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, NULL), 1);
116 CHECK_INT(event_del(sv[0]), 0);
117 CHECK_INT(wait_for(sv[0], EVENT_IN, 50, NULL), 0);
118 pair_close();
119}
120
121static void case_generations_do_not_mix(void) {
122 int other[2];
123 uint32_t generation = 0;
124
125 test_case("two descriptors carry their own generations");
126 pair_open();
127 CHECK(sv[0] != -1);
128 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, other), 0);
129 CHECK_INT(event_add(sv[0], EVENT_IN, 100), 0);
130 CHECK_INT(event_add(other[0], EVENT_IN, 200), 0);
131 CHECK_INT(write(sv[1], "x", 1), 1);
132 CHECK_INT(write(other[1], "y", 1), 1);
133
134 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, &generation), 1);
135 CHECK_INT(generation, 100);
136 CHECK_INT(wait_for(other[0], EVENT_IN, 1000, &generation), 1);
137 CHECK_INT(generation, 200);
138
139 test_case("and re-registering one changes only its own");
140 CHECK_INT(event_modify(sv[0], EVENT_IN, 101), 0);
141 CHECK_INT(wait_for(sv[0], EVENT_IN, 1000, &generation), 1);
142 CHECK_INT(generation, 101);
143 CHECK_INT(wait_for(other[0], EVENT_IN, 1000, &generation), 1);
144 CHECK_INT(generation, 200);
145
146 event_del(sv[0]);
147 event_del(other[0]);
148 close(other[0]);
149 close(other[1]);
150 pair_close();
151}
152
153/* Removing one of several has to leave the rest addressable: a backend that
154 keeps its descriptors packed moves the last one into the gap, and has to
155 remember where it went. */
156static void case_delete_from_the_middle(void) {
157 int pair[3][2];
158 uint32_t generation = 0;
159 int i;
160
161 test_case("deleting one of three leaves the others reported correctly");
162 for (i = 0; i < 3; ++i) {
163 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, pair[i]), 0);
164 CHECK_INT(event_add(pair[i][0], EVENT_IN, (uint32_t)(10 + i)), 0);
165 }
166 CHECK_INT(event_del(pair[1][0]), 0);
167
168 for (i = 0; i < 3; i += 2) {
169 CHECK_INT(write(pair[i][1], "x", 1), 1);
170 CHECK_INT(wait_for(pair[i][0], EVENT_IN, 1000, &generation), 1);
171 CHECK_INT(generation, 10 + i);
172 }
173
174 test_case("and the survivors can still be changed and removed");
175 CHECK_INT(event_modify(pair[2][0], EVENT_IN, 99), 0);
176 CHECK_INT(wait_for(pair[2][0], EVENT_IN, 1000, &generation), 1);
177 CHECK_INT(generation, 99);
178 CHECK_INT(event_del(pair[0][0]), 0);
179 CHECK_INT(event_del(pair[2][0]), 0);
180 CHECK_INT(wait_for(pair[2][0], EVENT_IN, 50, NULL), 0);
181
182 for (i = 0; i < 3; ++i)
183 close(pair[i][0]), close(pair[i][1]);
184}
185
186static void case_timeout(void) {
187 struct timeval started;
188
189 test_case("waiting on nothing comes back empty when the time is up");
190 gettimeofday(&started, NULL);
191 CHECK_INT(event_wait(ready, EVENTS, 200), 0);
192 {
193 unsigned long took = elapsed_ms(&started);
194 /* Scheduling makes the upper bound generous. The point is that it waited
195 rather than returning at once, and that it came back at all */
196 CHECK(took >= 150);
197 CHECK(took < 5000);
198 }
199}
200
201static void case_unknown_descriptor(void) {
202 test_case("changing or removing one that was never added is refused");
203 CHECK_INT(event_modify(4096, EVENT_IN, 1), -1);
204 CHECK_INT(event_del(4096), -1);
205}
206
207/* event_close exists so that the mechanisms which drop a closed descriptor
208 by themselves are not asked to do it twice. The one that keeps its own
209 list has to be told, and forgetting would leave the entry there to be
210 reported for ever, so what is checked here is the silence afterwards. */
211static void case_close_takes_it_out(void) {
212 int other[2], closed, count, i, strays = 0;
213
214 test_case("a closed descriptor is gone from the set and really closed");
215 pair_open();
216 CHECK(sv[0] != -1);
217 CHECK_INT(socketpair(AF_UNIX, SOCK_STREAM, 0, other), 0);
218 CHECK_INT(event_add(sv[0], EVENT_IN, 1), 0);
219 CHECK_INT(event_add(other[0], EVENT_IN, 2), 0);
220
221 closed = sv[0];
222 CHECK_INT(event_close(closed), 0);
223 sv[0] = -1;
224 CHECK_INT(fcntl(closed, F_GETFD), -1);
225
226 /* The survivor is made ready so the wait has something to come back with,
227 and anything left over from the closed one shows up beside it */
228 CHECK_INT((int)write(other[1], "x", 1), 1);
229 count = event_wait(ready, EVENTS, 200);
230 CHECK(count >= 1);
231 for (i = 0; i < count; ++i)
232 if (ready[i].fd != other[0])
233 ++strays;
234 CHECK_INT(strays, 0);
235
236 event_del(other[0]);
237 close(other[0]);
238 close(other[1]);
239 pair_close();
240}
241
242/* A descriptor can be taken on before anybody waits for anything on it: the
243 full scrape parks a connection while a worker thread builds the reply. The
244 mechanisms disagree about what registering nothing means, so what is
245 checked is that asking for a filter afterwards still works. */
246static void case_add_nothing_then_ask(void) {
247 test_case("a descriptor added with no interest can be given some later");
248 pair_open();
249 CHECK(sv[0] != -1);
250 CHECK_INT(event_add(sv[0], 0, 7), 0);
251 CHECK_INT((int)write(sv[1], "x", 1), 1);
252 CHECK_INT(wait_for(sv[0], EVENT_IN, 200, NULL), 0);
253
254 CHECK_INT(event_modify(sv[0], EVENT_IN, 7), 0);
255 {
256 uint32_t generation = 0;
257 CHECK_INT(wait_for(sv[0], EVENT_IN, 500, &generation), 1);
258 CHECK_INT((int)generation, 7);
259 }
260 event_del(sv[0]);
261 pair_close();
262}
263
264/* Whether a worker thread may register a descriptor while this one waits
265 depends on who keeps the set. Tying the answer to the mechanism's name
266 here means a backend added later cannot quietly forget to say. */
267static void case_sharing_matches_the_mechanism(void) {
268 test_case("only a set the kernel keeps may be changed from another thread");
269 CHECK_INT(event_can_share(), strcmp(event_mechanism(), "poll") ? 1 : 0);
270}
271
272void test_event(void) {
273 CHECK_INT(event_init(), 0);
274 CHECK(event_mechanism() != NULL);
275 case_sharing_matches_the_mechanism();
276
277 case_readable();
278 case_writable();
279 case_interest_is_separate();
280 case_removed_is_silent();
281 case_generations_do_not_mix();
282 case_delete_from_the_middle();
283 case_timeout();
284 case_unknown_descriptor();
285 case_close_takes_it_out();
286 case_add_nothing_then_ask();
287
288 event_deinit();
289}
diff --git a/tests/t_fdstate.c b/tests/t_fdstate.c
new file mode 100644
index 0000000..c806dbe
--- /dev/null
+++ b/tests/t_fdstate.c
@@ -0,0 +1,230 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <pthread.h>
6#include <stdatomic.h>
7#include <stdint.h>
8#include <stdlib.h>
9#include <string.h>
10
11/* Opentracker */
12#include "ot_fdstate.h"
13#include "test.h"
14
15/* ------------------------------------------------------- one thread first */
16
17static void case_open_claim_release(void) {
18 char cookie[4];
19 uint32_t generation;
20
21 test_case("a descriptor taken into the table can be claimed and gives back its cookie");
22 generation = fdstate_open(7, cookie, 0);
23 CHECK_INT(fdstate_claim(7, generation), 1);
24 CHECK_PTR(fdstate_cookie(7), cookie);
25 fdstate_release(7);
26
27 test_case("and can be claimed again once released");
28 CHECK_INT(fdstate_claim(7, generation), 1);
29 fdstate_release(7);
30 fdstate_close(7);
31}
32
33static void case_one_holder_at_a_time(void) {
34 uint32_t generation = fdstate_open(8, NULL, 0);
35
36 test_case("a descriptor somebody holds cannot be claimed again");
37 CHECK_INT(fdstate_claim(8, generation), 1);
38 CHECK_INT(fdstate_claim(8, generation), 0);
39 fdstate_release(8);
40 CHECK_INT(fdstate_claim(8, generation), 1);
41 fdstate_release(8);
42 fdstate_close(8);
43}
44
45static void case_stale_generation_is_refused(void) {
46 char first[4], second[4];
47 uint32_t old, new;
48
49 test_case("a caller quoting the generation of a closed descriptor is turned away");
50 old = fdstate_open(9, first, 0);
51 fdstate_close(9);
52 new = fdstate_open(9, second, 0);
53 CHECK(old != new);
54 CHECK_INT(fdstate_claim(9, old), 0);
55
56 test_case("while the one quoting the new generation gets the new cookie");
57 CHECK_INT(fdstate_claim(9, new), 1);
58 CHECK_PTR(fdstate_cookie(9), second);
59 fdstate_release(9);
60 fdstate_close(9);
61}
62
63static void case_expiry(void) {
64 uint32_t generation = fdstate_open(10, NULL, 100);
65
66 test_case("a descriptor past its expiry is collected");
67 CHECK_INT(fdstate_claim_expired(10, 99), 0);
68 CHECK_INT(fdstate_claim_expired(10, 100), 1);
69 fdstate_close(10);
70
71 test_case("one that never expires is never collected");
72 generation = fdstate_open(10, NULL, 0);
73 CHECK_INT(fdstate_claim_expired(10, 1 << 30), 0);
74
75 test_case("and one somebody is working on is left alone");
76 fdstate_set_expiry(10, 1);
77 CHECK_INT(fdstate_claim(10, generation), 1);
78 CHECK_INT(fdstate_claim_expired(10, 1 << 30), 0);
79 fdstate_release(10);
80 CHECK_INT(fdstate_claim_expired(10, 1 << 30), 1);
81 fdstate_close(10);
82}
83
84static void case_out_of_range(void) {
85 test_case("a descriptor outside the table is refused rather than trusted");
86 CHECK_INT(fdstate_claim(-1, 0), 0);
87 CHECK_INT(fdstate_claim((int)fdstate_slots(), 0), 0);
88 CHECK_INT(fdstate_claim_expired(-1, 0), 0);
89 CHECK_PTR(fdstate_cookie(-1), NULL);
90}
91
92/* --------------------------------------------------------- then in anger */
93
94/* The race this is about only exists while a descriptor is being recycled,
95 so recycling is driven by work done rather than by a clock: every slot is
96 given up after RECYCLE_AFTER claims, whatever the machine's speed. */
97
98#define STRESS_SLOTS 64
99#define RECYCLE_AFTER 32
100#define STRESS_CLAIMS 200000
101#define STRESS_GIVEUP (STRESS_CLAIMS * 100)
102/* What the run has to reach for its result to mean anything */
103#define STRESS_CYCLES (STRESS_CLAIMS / (RECYCLE_AFTER * 4))
104
105static _Atomic long stress_claims, stress_recycles, stress_violations, stress_attempts;
106static _Atomic int stress_lives[STRESS_SLOTS];
107static _Atomic int stress_live[STRESS_SLOTS];
108
109/* Generation and cookie are published in one word so a worker can never read
110 a cookie that belongs to a different generation than the one it claimed
111 with. Each connection gets a cookie nobody else ever gets. */
112static _Atomic uint64_t stress_conn[STRESS_SLOTS];
113static _Atomic uint64_t stress_next_cookie;
114
115#define STRESS_CONN(cookie, gen) (((uint64_t)(cookie) << 32) | (uint32_t)(gen))
116#define STRESS_CONN_COOKIE(w) ((void *)(uintptr_t)((w) >> 32))
117#define STRESS_CONN_GEN(w) ((uint32_t)(w))
118
119/* The workers reach their claim target on their own, but the recycles that
120 make the run worth anything are the keeper's, and on a loaded machine the
121 keeper is the thread that loses. So the run goes on until both targets are
122 met rather than until the faster of the two is. */
123static int stress_running(void) {
124 if (atomic_load(&stress_attempts) >= STRESS_GIVEUP)
125 return 0;
126 return atomic_load(&stress_claims) < STRESS_CLAIMS || atomic_load(&stress_recycles) <= STRESS_CYCLES;
127}
128
129static void *stress_worker(void *arg) {
130 unsigned seed = (unsigned)(uintptr_t)arg;
131
132 while (stress_running()) {
133 int fd = (int)(rand_r(&seed) % STRESS_SLOTS);
134 uint64_t conn = atomic_load(&stress_conn[fd]);
135
136 atomic_fetch_add(&stress_attempts, 1);
137 if (!fdstate_claim(fd, STRESS_CONN_GEN(conn)))
138 continue;
139
140 if (fdstate_cookie(fd) != STRESS_CONN_COOKIE(conn))
141 atomic_fetch_add(&stress_violations, 1);
142 if (atomic_fetch_sub(&stress_lives[fd], 1) <= 1)
143 fdstate_set_expiry(fd, 1); /* retired by its holder, as a handler would */
144 if (fdstate_cookie(fd) != STRESS_CONN_COOKIE(conn))
145 atomic_fetch_add(&stress_violations, 1);
146
147 fdstate_release(fd);
148 atomic_fetch_add(&stress_claims, 1);
149 }
150 return NULL;
151}
152
153static void *stress_keeper(void *arg) {
154 (void)arg;
155 while (stress_running()) {
156 int fd;
157
158 for (fd = 0; fd < STRESS_SLOTS; ++fd) {
159 if (atomic_load(&stress_live[fd])) {
160 if (!fdstate_claim_expired(fd, 1))
161 continue; /* a worker has it, come back */
162 fdstate_close(fd);
163 atomic_store(&stress_live[fd], 0);
164 atomic_fetch_add(&stress_recycles, 1);
165 }
166 {
167 void *cookie = (void *)(uintptr_t)(atomic_fetch_add(&stress_next_cookie, 1) + 1);
168 uint32_t gen = fdstate_open(fd, cookie, 0);
169
170 atomic_store(&stress_lives[fd], RECYCLE_AFTER);
171 atomic_store(&stress_conn[fd], STRESS_CONN((uintptr_t)cookie, gen));
172 atomic_store(&stress_live[fd], 1);
173 }
174 }
175 }
176 return NULL;
177}
178
179static void case_recycling_under_load(void) {
180 pthread_t worker[4], keeper;
181 size_t i;
182
183 test_case("no worker is ever handed a connection from another generation");
184 atomic_store(&stress_claims, 0);
185 atomic_store(&stress_recycles, 0);
186 atomic_store(&stress_violations, 0);
187 atomic_store(&stress_attempts, 0);
188 atomic_store(&stress_next_cookie, 0);
189 /* Every slot is opened and published before any worker runs: a worker only
190 ever learns of a descriptor from whoever registered it, and never
191 invents a generation of its own. */
192 for (i = 0; i < STRESS_SLOTS; ++i) {
193 void *cookie = (void *)(uintptr_t)(atomic_fetch_add(&stress_next_cookie, 1) + 1);
194 uint32_t gen = fdstate_open((int)i, cookie, 0);
195
196 atomic_store(&stress_lives[i], RECYCLE_AFTER);
197 atomic_store(&stress_conn[i], STRESS_CONN((uintptr_t)cookie, gen));
198 atomic_store(&stress_live[i], 1);
199 }
200
201 pthread_create(&keeper, NULL, stress_keeper, NULL);
202 for (i = 0; i < sizeof(worker) / sizeof(worker[0]); ++i)
203 pthread_create(&worker[i], NULL, stress_worker, (void *)(uintptr_t)(i + 1));
204 for (i = 0; i < sizeof(worker) / sizeof(worker[0]); ++i)
205 pthread_join(worker[i], NULL);
206 pthread_join(keeper, NULL);
207
208 CHECK_INT(atomic_load(&stress_violations), 0);
209
210 test_case("and the run actually recycled descriptors, or it proved nothing");
211 CHECK(atomic_load(&stress_claims) >= STRESS_CLAIMS);
212 CHECK(atomic_load(&stress_recycles) > STRESS_CYCLES);
213
214 for (i = 0; i < STRESS_SLOTS; ++i)
215 fdstate_close((int)i);
216}
217
218void test_fdstate(void) {
219 CHECK_INT(fdstate_init(), 0);
220 CHECK(fdstate_slots() > STRESS_SLOTS);
221
222 case_open_claim_release();
223 case_one_holder_at_a_time();
224 case_stale_generation_is_refused();
225 case_expiry();
226 case_out_of_range();
227 case_recycling_under_load();
228
229 fdstate_deinit();
230}
diff --git a/tests/t_fmt.c b/tests/t_fmt.c
new file mode 100644
index 0000000..f94102d
--- /dev/null
+++ b/tests/t_fmt.c
@@ -0,0 +1,106 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <string.h>
6
7/* Opentracker */
8#include "ot_fmt.h"
9#include "test.h"
10
11static void case_appends_in_sequence(void) {
12 char buffer[64];
13 char *r = buffer, *re = buffer + sizeof(buffer);
14
15 test_case("appends follow each other and advance the cursor");
16 fmt_append(&r, re, "d8:completei%zde", (size_t)7);
17 fmt_append(&r, re, "ee");
18 *r = 0;
19 CHECK_STR(buffer, "d8:completei7eee");
20 CHECK_INT(r - buffer, 16);
21}
22
23static void case_truncation_stops_at_the_end(void) {
24 char buffer[16];
25 char *r = buffer, *re = buffer + 8; /* pretend the buffer ends early */
26
27 memset(buffer, '#', sizeof(buffer));
28 test_case("a value too long for the room left stops at the end");
29 fmt_append(&r, re, "%s", "0123456789");
30 CHECK_PTR(r, re);
31
32 test_case("and writes nothing past it");
33 CHECK_INT(buffer[8], '#');
34 CHECK_INT(buffer[15], '#');
35}
36
37static void case_a_full_buffer_takes_nothing_more(void) {
38 char buffer[16];
39 char *r = buffer + 8, *re = buffer + 8;
40
41 memset(buffer, '#', sizeof(buffer));
42 test_case("appending to a cursor already at the end changes nothing");
43 fmt_append(&r, re, "more");
44 CHECK_PTR(r, re);
45 CHECK_INT(buffer[8], '#');
46}
47
48static void case_an_append_that_just_fits(void) {
49 char buffer[8];
50 char *r = buffer, *re = buffer + 3;
51
52 memset(buffer, '#', sizeof(buffer));
53 test_case("three characters into three bytes of room still truncate");
54 fmt_append(&r, re, "abc");
55 CHECK_PTR(r, re);
56 CHECK_INT(buffer[0], 'a');
57 CHECK_INT(buffer[1], 'b');
58
59 test_case("because snprintf spends the last byte on its terminator");
60 CHECK_INT(buffer[2], 0);
61 CHECK_INT(buffer[3], '#');
62}
63
64static void case_bytes_are_all_or_nothing(void) {
65 char buffer[16];
66 char *r = buffer, *re = buffer + 8;
67
68 memset(buffer, '#', sizeof(buffer));
69 test_case("a run of bytes is written when it fits");
70 fmt_bytes(&r, re, "\0\1\2\3", 4);
71 CHECK_PTR(r, buffer + 4);
72 CHECK_MEM(buffer, "\0\1\2\3", 4);
73
74 test_case("a run that would not fit is refused whole");
75 fmt_bytes(&r, re, "abcde", 5);
76 CHECK_PTR(r, re);
77 CHECK_INT(buffer[4], '#');
78
79 test_case("a run of exactly the room left is written");
80 r = buffer + 4;
81 fmt_bytes(&r, re, "wxyz", 4);
82 CHECK_PTR(r, re);
83 CHECK_MEM(buffer + 4, "wxyz", 4);
84 CHECK_INT(buffer[8], '#');
85}
86
87static void case_bytes_do_not_terminate(void) {
88 char buffer[8];
89 char *r = buffer, *re = buffer + 4;
90
91 memset(buffer, '#', sizeof(buffer));
92 test_case("unlike an append, a run of bytes may fill the room exactly");
93 fmt_bytes(&r, re, "abcd", 4);
94 CHECK_PTR(r, re);
95 CHECK_MEM(buffer, "abcd", 4);
96 CHECK_INT(buffer[4], '#');
97}
98
99void test_fmt(void) {
100 case_appends_in_sequence();
101 case_truncation_stops_at_the_end();
102 case_a_full_buffer_takes_nothing_more();
103 case_an_append_that_just_fits();
104 case_bytes_are_all_or_nothing();
105 case_bytes_do_not_terminate();
106}
diff --git a/tests/t_hex.c b/tests/t_hex.c
new file mode 100644
index 0000000..84aeba2
--- /dev/null
+++ b/tests/t_hex.c
@@ -0,0 +1,126 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_hex.h"
10#include "test.h"
11
12static const uint8_t sample[20] = {0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0};
13
14static void case_encode(void) {
15 char dest[64];
16
17 test_case("a hash encodes to forty upper case digits and a terminator");
18 memset(dest, 0x7f, sizeof(dest));
19 CHECK_PTR(hex_from_hash(dest, sample), dest);
20 CHECK_STR(dest, "000123456789ABCDEFFF10203040506070809" "0A0");
21 CHECK_INT(strlen(dest), 40);
22 CHECK_INT((unsigned char)dest[41], 0x7f);
23}
24
25static void case_decode(void) {
26 ot_hash hash;
27
28 test_case("forty digits decode back to the hash");
29 CHECK(hex_to_hash(hash, "000123456789ABCDEFFF10203040506070809" "0A0"));
30 CHECK_MEM(hash, sample, sizeof(sample));
31}
32
33static void case_round_trip(void) {
34 ot_hash hash;
35 char text[64];
36 size_t i;
37
38 test_case("encode and decode are inverses over every byte value");
39 for (i = 0; i < 256; ++i) {
40 uint8_t probe[20];
41 memset(probe, (uint8_t)i, sizeof(probe));
42 hex_from_hash(text, probe);
43 if (!hex_to_hash(hash, text) || memcmp(hash, probe, sizeof(probe))) {
44 test_failf(__FILE__, __LINE__, "round trip failed for byte value %zu", i);
45 return;
46 }
47 }
48 ++test_checks;
49}
50
51static void case_decode_is_case_insensitive(void) {
52 ot_hash upper, lower;
53
54 test_case("lower case digits decode the same as upper case");
55 CHECK(hex_to_hash(upper, "ABCDEF0123456789ABCDEF0123456789ABCDEF01"));
56 CHECK(hex_to_hash(lower, "abcdef0123456789abcdef0123456789abcdef01"));
57 CHECK_MEM(lower, upper, sizeof(ot_hash));
58}
59
60static void case_rejects_non_digits(void) {
61 ot_hash hash;
62
63 test_case("a non hex character anywhere rejects the whole string");
64 CHECK_INT(hex_to_hash(hash, "g00123456789ABCDEFFF102030405060708090A0"), 0);
65 CHECK_INT(hex_to_hash(hash, "000123456789ABCDEFFF102030405060708090Ag"), 0);
66 CHECK_INT(hex_to_hash(hash, "000123456789ABCDEF:F102030405060708090A"), 0);
67}
68
69static void case_rejects_short_input(void) {
70 ot_hash hash;
71
72 test_case("a string shorter than forty digits is rejected");
73 CHECK_INT(hex_to_hash(hash, ""), 0);
74 CHECK_INT(hex_to_hash(hash, "00"), 0);
75 CHECK_INT(hex_to_hash(hash, "000123456789ABCDEFFF102030405060708090A"), 0);
76}
77
78static void case_leaves_hash_untouched_on_failure(void) {
79 ot_hash hash;
80
81 test_case("a rejected string leaves the destination untouched");
82 memset(hash, 0x5a, sizeof(hash));
83 CHECK_INT(hex_to_hash(hash, "000123456789ABCDEFFF10203040506070809XX0"), 0);
84 CHECK_MEM(hash, "\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a\x5a", sizeof(hash));
85}
86
87static void case_stops_at_the_terminator(void) {
88 /* The saved state parser hands this whole buffers that may end early. The
89 decoder must not read past the zero that stopped it. */
90 char guarded[8];
91 ot_hash hash;
92
93 test_case("decoding stops at a terminator rather than running past it");
94 memcpy(guarded, "0012", 4);
95 guarded[4] = 0;
96 memset(guarded + 5, 'f', 3);
97 CHECK_INT(hex_to_hash(hash, guarded), 0);
98}
99
100static void case_isdigit(void) {
101 test_case("hex_isdigit accepts exactly the hex digits");
102 CHECK(hex_isdigit('0'));
103 CHECK(hex_isdigit('9'));
104 CHECK(hex_isdigit('a'));
105 CHECK(hex_isdigit('f'));
106 CHECK(hex_isdigit('A'));
107 CHECK(hex_isdigit('F'));
108 CHECK_INT(hex_isdigit('g'), 0);
109 CHECK_INT(hex_isdigit('G'), 0);
110 CHECK_INT(hex_isdigit(':'), 0);
111 CHECK_INT(hex_isdigit('\n'), 0);
112 CHECK_INT(hex_isdigit(0), 0);
113 CHECK_INT(hex_isdigit(0x80), 0);
114}
115
116void test_hex(void) {
117 case_encode();
118 case_decode();
119 case_round_trip();
120 case_decode_is_case_insensitive();
121 case_rejects_non_digits();
122 case_rejects_short_input();
123 case_leaves_hash_untouched_on_failure();
124 case_stops_at_the_terminator();
125 case_isdigit();
126}
diff --git a/tests/t_iovec.c b/tests/t_iovec.c
new file mode 100644
index 0000000..1e8206d
--- /dev/null
+++ b/tests/t_iovec.c
@@ -0,0 +1,122 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdlib.h>
6#include <string.h>
7#include <sys/uio.h>
8
9/* Opentracker */
10#include "ot_iovec.h"
11#include "test.h"
12
13static void case_increase_and_length(void) {
14 size_t entries = 0;
15 struct iovec *vector = NULL;
16 void *first, *second;
17
18 test_case("increase appends an entry and length is their sum");
19 first = iovec_new_chunk(&entries, &vector, 100);
20 CHECK(first != NULL);
21 CHECK_INT(entries, 1);
22 CHECK_INT(vector[0].iov_len, 100);
23 CHECK_PTR(vector[0].iov_base, first);
24
25 second = iovec_new_chunk(&entries, &vector, 50);
26 CHECK(second != NULL);
27 CHECK_INT(entries, 2);
28 CHECK_INT(vector[1].iov_len, 50);
29 CHECK_INT(iovec_length(&entries, (const struct iovec **)&vector), 150);
30
31 iovec_free(&entries, &vector);
32}
33
34static void case_free_resets(void) {
35 size_t entries = 0;
36 struct iovec *vector = NULL;
37
38 test_case("free releases the entries and resets the vector");
39 CHECK(iovec_new_chunk(&entries, &vector, 10) != NULL);
40 CHECK(iovec_new_chunk(&entries, &vector, 10) != NULL);
41 iovec_free(&entries, &vector);
42 CHECK_INT(entries, 0);
43 CHECK_PTR(vector, NULL);
44 CHECK_INT(iovec_length(&entries, (const struct iovec **)&vector), 0);
45}
46
47static void case_fixlast_shrinks(void) {
48 size_t entries = 0;
49 struct iovec *vector = NULL;
50 char *block;
51
52 test_case("fixlast trims the last entry to the bytes actually used");
53 CHECK(iovec_new_chunk(&entries, &vector, 64) != NULL);
54 block = iovec_new_chunk(&entries, &vector, 1000);
55 CHECK(block != NULL);
56 memset(block, 'x', 20);
57
58 iovec_trim_last(&entries, &vector, block + 20);
59 CHECK_INT(entries, 2);
60 CHECK_INT(vector[1].iov_len, 20);
61 CHECK_INT(iovec_length(&entries, (const struct iovec **)&vector), 84);
62 CHECK_MEM(vector[1].iov_base, "xxxxxxxxxxxxxxxxxxxx", 20);
63
64 iovec_free(&entries, &vector);
65}
66
67static void case_fixlast_on_empty(void) {
68 size_t entries = 0;
69 struct iovec *vector = NULL;
70
71 test_case("fixlast on an empty vector does nothing");
72 iovec_trim_last(&entries, &vector, NULL);
73 CHECK_INT(entries, 0);
74 CHECK_PTR(vector, NULL);
75}
76
77static void case_append_takes_ownership(void) {
78 size_t entries = 0;
79 struct iovec *vector = NULL;
80 struct iovec source;
81
82 test_case("append moves the buffer and clears the source");
83 source.iov_base = malloc(10);
84 CHECK(source.iov_base != NULL);
85 memcpy(source.iov_base, "0123456789", 10);
86 source.iov_len = 10;
87
88 CHECK(iovec_append(&entries, &vector, &source) != NULL);
89 CHECK_INT(entries, 1);
90 CHECK_INT(vector[0].iov_len, 10);
91 CHECK_MEM(vector[0].iov_base, "0123456789", 10);
92 CHECK_PTR(source.iov_base, NULL);
93 CHECK_INT(source.iov_len, 0);
94
95 iovec_free(&entries, &vector);
96}
97
98static void case_fix_increase(void) {
99 size_t entries = 0;
100 struct iovec *vector = NULL;
101 char *block;
102
103 test_case("fix_increase trims the previous entry and adds a new one");
104 block = iovec_new_chunk(&entries, &vector, 500);
105 CHECK(block != NULL);
106 block = iovec_next_chunk(&entries, &vector, block + 30, 200);
107 CHECK(block != NULL);
108 CHECK_INT(entries, 2);
109 CHECK_INT(vector[0].iov_len, 30);
110 CHECK_INT(vector[1].iov_len, 200);
111
112 iovec_free(&entries, &vector);
113}
114
115void test_iovec(void) {
116 case_increase_and_length();
117 case_free_resets();
118 case_fixlast_shrinks();
119 case_fixlast_on_empty();
120 case_append_takes_ownership();
121 case_fix_increase();
122}
diff --git a/tests/t_ip.c b/tests/t_ip.c
new file mode 100644
index 0000000..218d3ff
--- /dev/null
+++ b/tests/t_ip.c
@@ -0,0 +1,215 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_ip.h"
10#include "test.h"
11
12static char text[64];
13
14static const char *formatted(const char *ip) {
15 text[ip_format(text, ip)] = 0;
16 return text;
17}
18
19/* ------------------------------------------------------------------ IPv4 */
20
21/* ------------------------------------------------------- RFC 5952 output */
22
23static void case_format_rfc5952(void) {
24 test_case("4.1 leading zeros in a group are suppressed");
25 CHECK_STR(formatted("\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"), "2001:db8::1");
26
27 test_case("4.2.1 the longest run of zero groups becomes ::");
28 CHECK_STR(formatted("\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x01"), "2001:db8::2:1");
29
30 test_case("4.2.2 a single zero group is never shortened");
31 CHECK_STR(formatted("\x20\x01\x0d\xb8\x00\x00\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01"), "2001:db8:0:1:1:1:1:1");
32
33 test_case("4.2.1 a longer run wins over an earlier shorter one");
34 CHECK_STR(formatted("\x20\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x01"), "2001:0:0:1::1");
35
36 test_case("4.2.3 of two runs of equal length the first is shortened");
37 CHECK_STR(formatted("\x20\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x01\x00\x01"), "2001::1:0:0:1:1");
38
39 test_case("4.3 hexadecimal digits are lower case");
40 CHECK_STR(formatted("\xab\xcd\xef\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"), "abcd:ef01::1");
41
42 test_case("the unspecified and loopback addresses");
43 CHECK_STR(formatted("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), "::");
44 CHECK_STR(formatted("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"), "::1");
45
46 test_case("a full address with no zero group");
47 CHECK_STR(formatted("\x11\x11\x22\x22\x33\x33\x44\x44\x55\x55\x66\x66\x77\x77\x88\x88"), "1111:2222:3333:4444:5555:6666:7777:8888");
48}
49
50static void case_format_trailing_zero_group(void) {
51 /* libowfat's formatter looked two bytes past the address to decide this
52 one, so a peer address ending in a zero group came out as "::" whenever
53 the bytes that happened to follow were not themselves zero. In
54 ot_stats.c those bytes are the peer's port. */
55 const char ip[] = "\x20\x01\x0d\xb8\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x00";
56
57 test_case("a single trailing zero group is written out, not shortened");
58 CHECK_STR(formatted(ip), "2001:db8:1:2:3:4:5:0");
59
60 test_case("and nothing beyond the sixteen bytes is consulted");
61 {
62 char padded[20];
63 memcpy(padded, ip, 16);
64 memset(padded + 16, 0xff, 4); /* a port and flags, as a peer record has */
65 CHECK_STR(formatted(padded), "2001:db8:1:2:3:4:5:0");
66 memset(padded + 16, 0x00, 4);
67 CHECK_STR(formatted(padded), "2001:db8:1:2:3:4:5:0");
68 }
69}
70
71static void case_v4mapped(void) {
72 const char mapped[] = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x0a\x00\x00\x01";
73 const char unmapped[] = "\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01";
74
75 test_case("a v4 mapped address is recognised");
76 CHECK(ip_is_v4mapped(mapped));
77 CHECK_INT(ip_is_v4mapped(unmapped), 0);
78
79 /* The tracker has only ever shown the plain quad, so that is the one
80 form the formatter produces; "::ffff:10.0.0.1" is not written anywhere */
81 test_case("a mapped address is written as the plain dotted quad");
82 CHECK_STR(formatted(mapped), "10.0.0.1");
83 CHECK_STR(formatted("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x00\x00"), "0.0.0.0");
84 CHECK_STR(formatted("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff"), "255.255.255.255");
85
86 test_case("anything else follows RFC 5952");
87 CHECK_STR(formatted(unmapped), "2001:db8::1");
88}
89
90/* -------------------------------------------------------- RFC 4291 input */
91
92static void case_scan_forms(void) {
93 char ip[16];
94
95 test_case("2.2 form 1, every group spelled out");
96 CHECK_INT(ip_parse("1111:2222:3333:4444:5555:6666:7777:8888", ip), 39);
97 CHECK_MEM(ip, "\x11\x11\x22\x22\x33\x33\x44\x44\x55\x55\x66\x66\x77\x77\x88\x88", 16);
98
99 test_case("2.2 form 2, zero groups abbreviated");
100 CHECK_INT(ip_parse("2001:db8::1", ip), 11);
101 CHECK_MEM(ip, "\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", 16);
102 CHECK_INT(ip_parse("::1", ip), 3);
103 CHECK_MEM(ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", 16);
104 CHECK_INT(ip_parse("::", ip), 2);
105 CHECK_MEM(ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16);
106 CHECK_INT(ip_parse("1::", ip), 3);
107 CHECK_MEM(ip, "\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16);
108
109 test_case("2.2 form 3, a dotted quad in the last two groups");
110 CHECK_INT(ip_parse("::ffff:1.2.3.4", ip), 14);
111 CHECK_MEM(ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x01\x02\x03\x04", 16);
112 CHECK_INT(ip_parse("1:2:3:4:5:6:1.2.3.4", ip), 19);
113 CHECK_MEM(ip, "\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x01\x02\x03\x04", 16);
114
115 test_case("upper case input is accepted");
116 CHECK_INT(ip_parse("2001:DB8::1", ip), 11);
117 CHECK_MEM(ip, "\x20\x01\x0d\xb8\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", 16);
118}
119
120static void case_scan_accepts_bare_ipv4(void) {
121 char ip[16];
122
123 /* Every address opentracker holds is sixteen bytes, so an operator writing
124 a plain IPv4 address in the config has to land as the v4 mapped form */
125 test_case("a bare IPv4 address is stored v4 mapped");
126 CHECK_INT(ip_parse("10.0.0.1", ip), 8);
127 CHECK_MEM(ip, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\x0a\x00\x00\x01", 16);
128 CHECK(ip_is_v4mapped(ip));
129}
130
131static void case_scan_reports_length(void) {
132 char ip[16];
133
134 /* The config parser continues from where the address ended, which is how
135 "address:port" and "address/bits" are read */
136 test_case("scanning stops at the character after the address");
137 CHECK_INT(ip_parse("10.0.0.1:6969", ip), 8);
138 CHECK_INT(ip_parse("2001:db8::1/64", ip), 11);
139 CHECK_INT(ip_parse("::1]", ip), 3);
140 CHECK_INT(ip_parse("1:2:3:4:5:6:7:8 trailing", ip), 15);
141}
142
143static void case_scan_rejects(void) {
144 char ip[16];
145
146 test_case("an empty or junk string is refused");
147 CHECK_INT(ip_parse("", ip), 0);
148 CHECK_INT(ip_parse("x", ip), 0);
149 CHECK_INT(ip_parse(":", ip), 0);
150 CHECK_INT(ip_parse(":1:2", ip), 0);
151
152 test_case("too few groups without :: are refused");
153 CHECK_INT(ip_parse("1:2:3:4:5:6:7", ip), 0);
154 CHECK_INT(ip_parse("2001:db8:1", ip), 0);
155
156 /* libowfat accepted a prefix of each of these and carried on. Taking only
157 part of a malformed address is worse than refusing it, especially where
158 the text comes from a config file or an X-Forwarded-For header. */
159 test_case("a second :: is refused rather than truncated");
160 CHECK_INT(ip_parse("1::2::3", ip), 0);
161 CHECK_INT(ip_parse("::1::", ip), 0);
162 CHECK_INT(ip_parse("::::", ip), 0);
163
164 test_case("more than eight groups is refused");
165 CHECK_INT(ip_parse("1:2:3:4:5:6:7:8:9", ip), 0);
166
167 test_case("a group of more than four digits is refused, not truncated");
168 CHECK_INT(ip_parse("12345::1", ip), 0);
169 CHECK_INT(ip_parse("fffff::1", ip), 0);
170}
171
172static void case_round_trip(void) {
173 /* Whatever the formatter writes, the scanner has to read back */
174 static const char *const samples[] = {"::",
175 "::1",
176 "1::",
177 "2001:db8::1",
178 "2001:db8:1:2:3:4:5:0",
179 "1111:2222:3333:4444:5555:6666:7777:8888",
180 "2001::1:0:0:1",
181 "abcd:ef01::1",
182 NULL};
183 char ip[16], again[16];
184 size_t i;
185
186 test_case("every formatted address scans back to the same bytes");
187 for (i = 0; samples[i]; ++i) {
188 size_t n = ip_parse(samples[i], ip);
189 if (n != strlen(samples[i])) {
190 test_failf(__FILE__, __LINE__, "\"%s\" consumed %zu of %zu", samples[i], n, strlen(samples[i]));
191 return;
192 }
193 text[ip_format(text, ip)] = 0;
194 if (strcmp(text, samples[i])) {
195 test_failf(__FILE__, __LINE__, "\"%s\" formatted back as \"%s\"", samples[i], text);
196 return;
197 }
198 if (!ip_parse(text, again) || memcmp(ip, again, 16)) {
199 test_failf(__FILE__, __LINE__, "\"%s\" did not survive a second pass", samples[i]);
200 return;
201 }
202 }
203 ++test_checks;
204}
205
206void test_ip(void) {
207 case_format_rfc5952();
208 case_format_trailing_zero_group();
209 case_v4mapped();
210 case_scan_forms();
211 case_scan_accepts_bare_ipv4();
212 case_scan_reports_length();
213 case_scan_rejects();
214 case_round_trip();
215}
diff --git a/tests/t_mutex.c b/tests/t_mutex.c
new file mode 100644
index 0000000..c0c41cc
--- /dev/null
+++ b/tests/t_mutex.c
@@ -0,0 +1,136 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <pthread.h>
6#include <stdatomic.h>
7#include <string.h>
8#include <unistd.h>
9
10/* Opentracker */
11#include "ot_mutex.h"
12#include "test.h"
13
14/* Every announce passes through here, and what it has to get right is which
15 bucket a hash belongs to and that two threads never hold one bucket at
16 once. Both are checked against real mutexes rather than a stand-in. */
17
18/* A hash that lands in a chosen bucket: the bucket is the top
19 OT_BUCKET_COUNT_BITS of the first four bytes, read in network order */
20static void hash_for_bucket(ot_hash hash, int bucket) {
21 memset(hash, 0, sizeof(ot_hash));
22 hash[0] = (uint8_t)(bucket >> (OT_BUCKET_COUNT_BITS - 8));
23 hash[1] = (uint8_t)((bucket << (16 - OT_BUCKET_COUNT_BITS)) & 0xff);
24}
25
26static void case_a_hash_names_its_bucket(void) {
27 static const int buckets[] = {0, 1, 2, 17, OT_BUCKET_COUNT / 2 - 1, OT_BUCKET_COUNT / 2, OT_BUCKET_COUNT - 1};
28 size_t i;
29
30 test_case("a hash is served by the bucket its leading bits name");
31 for (i = 0; i < sizeof(buckets) / sizeof(buckets[0]); ++i) {
32 ot_hash hash;
33 ot_vector *by_hash, *by_number;
34
35 hash_for_bucket(hash, buckets[i]);
36 by_hash = mutex_bucket_lock_by_hash(hash);
37 mutex_bucket_unlock_by_hash(hash, 0);
38
39 by_number = mutex_bucket_lock(buckets[i]);
40 mutex_bucket_unlock(buckets[i], 0);
41
42 CHECK(by_hash == by_number);
43 }
44}
45
46static void case_every_bucket_is_its_own(void) {
47 ot_vector *first, *last, *middle;
48
49 test_case("no two buckets are the same one");
50 first = mutex_bucket_lock(0);
51 mutex_bucket_unlock(0, 0);
52 middle = mutex_bucket_lock(OT_BUCKET_COUNT / 2);
53 mutex_bucket_unlock(OT_BUCKET_COUNT / 2, 0);
54 last = mutex_bucket_lock(OT_BUCKET_COUNT - 1);
55 mutex_bucket_unlock(OT_BUCKET_COUNT - 1, 0);
56
57 CHECK(first != middle);
58 CHECK(middle != last);
59 CHECK(first != last);
60}
61
62static void case_the_count_follows_what_unlock_is_told(void) {
63 size_t before = mutex_get_torrent_count();
64
65 test_case("the torrent count moves by what unlocking reports, and not otherwise");
66 mutex_bucket_lock(3);
67 mutex_bucket_unlock(3, 0);
68 CHECK_INT((int)(mutex_get_torrent_count() - before), 0);
69
70 mutex_bucket_lock(3);
71 mutex_bucket_unlock(3, 5);
72 CHECK_INT((int)(mutex_get_torrent_count() - before), 5);
73
74 mutex_bucket_lock(3);
75 mutex_bucket_unlock(3, -2);
76 CHECK_INT((int)(mutex_get_torrent_count() - before), 3);
77}
78
79static _Atomic int g_other_got_in;
80
81static void *take_a_bucket(void *args) {
82 int bucket = (int)(intptr_t)args;
83
84 mutex_bucket_lock(bucket);
85 atomic_store(&g_other_got_in, 1);
86 mutex_bucket_unlock(bucket, 0);
87 return NULL;
88}
89
90static int waited_for_entry(int patience_ms) {
91 int waited;
92
93 for (waited = 0; waited < patience_ms && !atomic_load(&g_other_got_in); ++waited)
94 usleep(1000);
95 return atomic_load(&g_other_got_in);
96}
97
98static void case_a_held_bucket_keeps_others_out(void) {
99 pthread_t other;
100
101 test_case("a second thread waits for the bucket this one holds");
102 atomic_store(&g_other_got_in, 0);
103 mutex_bucket_lock(9);
104 CHECK_INT(pthread_create(&other, NULL, take_a_bucket, (void *)(intptr_t)9), 0);
105
106 CHECK_INT(waited_for_entry(200), 0);
107
108 mutex_bucket_unlock(9, 0);
109 CHECK_INT(waited_for_entry(2000), 1);
110 pthread_join(other, NULL);
111}
112
113static void case_another_bucket_is_free_meanwhile(void) {
114 pthread_t other;
115
116 test_case("and a different bucket is not held up by it");
117 atomic_store(&g_other_got_in, 0);
118 mutex_bucket_lock(9);
119 CHECK_INT(pthread_create(&other, NULL, take_a_bucket, (void *)(intptr_t)10), 0);
120
121 CHECK_INT(waited_for_entry(2000), 1);
122 pthread_join(other, NULL);
123 mutex_bucket_unlock(9, 0);
124}
125
126void test_mutex(void) {
127 mutex_init();
128
129 case_a_hash_names_its_bucket();
130 case_every_bucket_is_its_own();
131 case_the_count_follows_what_unlock_is_told();
132 case_a_held_bucket_keeps_others_out();
133 case_another_bucket_is_free_meanwhile();
134
135 mutex_deinit();
136}
diff --git a/tests/t_random.c b/tests/t_random.c
new file mode 100644
index 0000000..b070c3f
--- /dev/null
+++ b/tests/t_random.c
@@ -0,0 +1,112 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_random.h"
10#include "test.h"
11
12/* Nothing here can test that the bytes are unpredictable, which is a property
13 of the generator the build selected. What these cases do pin is that the
14 wrapper hands the whole buffer to it, writes nothing beyond the length it
15 was given, and is actually wired to something that varies. The first of
16 those matters: the fallback this module replaced filled only the first
17 sixteen bytes of the sixty-four byte key buffer in ot_udp.c. */
18
19#define DRAWS 32
20#define BUFLEN 64
21
22static void case_every_byte_varies(void) {
23 unsigned char first[BUFLEN], draw[BUFLEN];
24 unsigned char varied[BUFLEN];
25 size_t i, n;
26
27 test_case("every byte of the buffer comes from the generator");
28 memset(varied, 0, sizeof(varied));
29 random_bytes(first, sizeof(first));
30
31 for (n = 0; n < DRAWS; ++n) {
32 random_bytes(draw, sizeof(draw));
33 for (i = 0; i < BUFLEN; ++i)
34 if (draw[i] != first[i])
35 varied[i] = 1;
36 }
37
38 /* A byte position that never moved across 32 draws is not being written.
39 A false alarm needs all 32 draws to agree by chance, around 256^-31. */
40 for (i = 0; i < BUFLEN; ++i)
41 if (!varied[i]) {
42 test_failf(__FILE__, __LINE__, "byte %zu never changed over %d draws", i, DRAWS);
43 return;
44 }
45 ++test_checks;
46}
47
48static void case_respects_length(void) {
49 unsigned char buf[32];
50 size_t i;
51
52 test_case("nothing is written past the requested length");
53 memset(buf, 0xA5, sizeof(buf));
54 random_bytes(buf, 8);
55 for (i = 8; i < sizeof(buf); ++i)
56 if (buf[i] != 0xA5) {
57 test_failf(__FILE__, __LINE__, "byte %zu past the end was overwritten", i);
58 return;
59 }
60 ++test_checks;
61}
62
63static void case_zero_length(void) {
64 unsigned char buf[4];
65
66 test_case("a zero length request writes nothing");
67 memset(buf, 0x5A, sizeof(buf));
68 random_bytes(buf, 0);
69 CHECK_MEM(buf, "\x5a\x5a\x5a\x5a", 4);
70}
71
72static void case_successive_draws_differ(void) {
73 unsigned char a[32], b[32];
74
75 test_case("two draws differ");
76 random_bytes(a, sizeof(a));
77 random_bytes(b, sizeof(b));
78 CHECK(memcmp(a, b, sizeof(a)) != 0);
79}
80
81static void case_uint32_varies(void) {
82 uint32_t first = random_uint32();
83 int differs = 0;
84 size_t n;
85
86 test_case("random_uint32 does not return a constant");
87 for (n = 0; n < DRAWS; ++n)
88 if (random_uint32() != first)
89 differs = 1;
90 CHECK(differs);
91}
92
93static void case_uint32_uses_the_top_bit(void) {
94 uint32_t seen = 0;
95 size_t n;
96
97 test_case("random_uint32 spans the full 32 bits");
98 /* random() never sets bit 31, so a build that returned it unmixed would
99 fail this. Over 64 draws the chance of a false alarm is 2^-64. */
100 for (n = 0; n < 64; ++n)
101 seen |= random_uint32();
102 CHECK_INT(seen & 0x80000000u, 0x80000000u);
103}
104
105void test_random(void) {
106 case_every_byte_varies();
107 case_respects_length();
108 case_zero_length();
109 case_successive_draws_differ();
110 case_uint32_varies();
111 case_uint32_uses_the_top_bit();
112}
diff --git a/tests/t_scan.c b/tests/t_scan.c
new file mode 100644
index 0000000..05c4a67
--- /dev/null
+++ b/tests/t_scan.c
@@ -0,0 +1,210 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_scan.h"
10#include "test.h"
11
12static void case_plain_numbers(void) {
13 uint64_t value;
14
15 test_case("a decimal number is read and its length reported");
16 CHECK_INT(scan_uint("0", &value, 65535), 1);
17 CHECK_INT(value, 0);
18 CHECK_INT(scan_uint("7", &value, 65535), 1);
19 CHECK_INT(value, 7);
20 CHECK_INT(scan_uint("6969", &value, 65535), 4);
21 CHECK_INT(value, 6969);
22 CHECK_INT(scan_uint("65535", &value, 65535), 5);
23 CHECK_INT(value, 65535);
24}
25
26static void case_stops_at_non_digit(void) {
27 uint64_t value;
28
29 test_case("scanning stops at the first character that is not a digit");
30 CHECK_INT(scan_uint("6969:rest", &value, 65535), 4);
31 CHECK_INT(value, 6969);
32 CHECK_INT(scan_uint("128/8", &value, 65535), 3);
33 CHECK_INT(value, 128);
34 CHECK_INT(scan_uint("42\n", &value, 65535), 2);
35 CHECK_INT(value, 42);
36}
37
38static void case_rejects_whitespace(void) {
39 uint64_t value = 0xdead;
40
41 test_case("leading whitespace is not skipped");
42 CHECK_INT(scan_uint(" 1", &value, 65535), 0);
43 CHECK_INT(scan_uint("\t1", &value, 65535), 0);
44 CHECK_INT(scan_uint("\n1", &value, 65535), 0);
45 CHECK_INT(value, 0xdead);
46}
47
48static void case_rejects_sign(void) {
49 uint64_t value = 0xdead;
50
51 test_case("a sign is not accepted");
52 CHECK_INT(scan_uint("+1", &value, 65535), 0);
53 CHECK_INT(scan_uint("-1", &value, 65535), 0);
54 CHECK_INT(scan_uint("-0", &value, 65535), 0);
55 CHECK_INT(value, 0xdead);
56}
57
58static void case_rejects_empty_and_junk(void) {
59 uint64_t value = 0xdead;
60
61 test_case("a string with no leading digit yields nothing");
62 CHECK_INT(scan_uint("", &value, 65535), 0);
63 CHECK_INT(scan_uint("x", &value, 65535), 0);
64 CHECK_INT(scan_uint(":80", &value, 65535), 0);
65 CHECK_INT(value, 0xdead);
66}
67
68static void case_no_alternative_bases(void) {
69 uint64_t value;
70
71 test_case("hexadecimal and octal notations are read as plain decimal");
72 CHECK_INT(scan_uint("0x10", &value, 65535), 1);
73 CHECK_INT(value, 0);
74 CHECK_INT(scan_uint("010", &value, 65535), 3);
75 CHECK_INT(value, 10);
76}
77
78static void case_refuses_out_of_range(void) {
79 uint64_t value = 0xdead;
80
81 test_case("a value above max is refused, not truncated");
82 CHECK_INT(scan_uint("65536", &value, 65535), 0);
83 CHECK_INT(scan_uint("99999", &value, 65535), 0);
84 CHECK_INT(scan_uint("129", &value, 128), 0);
85 CHECK_INT(value, 0xdead);
86
87 test_case("the boundary itself is accepted");
88 CHECK_INT(scan_uint("128", &value, 128), 3);
89 CHECK_INT(value, 128);
90}
91
92static void case_sixty_four_bit_range(void) {
93 uint64_t value;
94
95 test_case("the full unsigned 64 bit range is available");
96 CHECK_INT(scan_uint("18446744073709551615", &value, UINT64_MAX), 20);
97 CHECK(value == UINT64_MAX);
98
99 test_case("a number too large for 64 bits is refused");
100 CHECK_INT(scan_uint("18446744073709551616", &value, UINT64_MAX), 0);
101 CHECK_INT(scan_uint("99999999999999999999999999", &value, UINT64_MAX), 0);
102}
103
104static void case_leading_zeros_allowed(void) {
105 uint64_t value;
106
107 test_case("leading zeros are accepted outside bencode");
108 CHECK_INT(scan_uint("007", &value, 65535), 3);
109 CHECK_INT(value, 7);
110 CHECK_INT(scan_uint("0000", &value, 65535), 4);
111 CHECK_INT(value, 0);
112}
113
114static void case_bencode_rejects_leading_zeros(void) {
115 uint64_t value = 0xdead;
116
117 test_case("bencode refuses a leading zero on anything but zero");
118 CHECK_INT(scan_uint_bencode("007", &value, 65535), 0);
119 CHECK_INT(scan_uint_bencode("0000", &value, 65535), 0);
120 CHECK_INT(scan_uint_bencode("01", &value, 65535), 0);
121 CHECK_INT(value, 0xdead);
122}
123
124static void case_bencode_accepts_canonical(void) {
125 uint64_t value;
126
127 test_case("bencode accepts a canonically written number");
128 CHECK_INT(scan_uint_bencode("0", &value, 65535), 1);
129 CHECK_INT(value, 0);
130 CHECK_INT(scan_uint_bencode("0:", &value, 65535), 1);
131 CHECK_INT(value, 0);
132 CHECK_INT(scan_uint_bencode("160:", &value, 65535), 3);
133 CHECK_INT(value, 160);
134}
135
136static void case_bencode_inherits_the_rest(void) {
137 uint64_t value = 0xdead;
138
139 test_case("bencode is no laxer than the plain scanner");
140 CHECK_INT(scan_uint_bencode(" 1", &value, 65535), 0);
141 CHECK_INT(scan_uint_bencode("-1", &value, 65535), 0);
142 CHECK_INT(scan_uint_bencode("+1", &value, 65535), 0);
143 CHECK_INT(scan_uint_bencode("65536", &value, 65535), 0);
144 CHECK_INT(value, 0xdead);
145}
146
147/* ------------------------------------------- fixed width signed integers */
148
149/* A value lifted out of a query string arrives as a pointer and a length
150 with nothing terminating it, and the whole of it has to be the number. */
151
152static void case_int_whole_field(void) {
153 int64_t value = 0;
154
155 test_case("the whole field is read, sign and all");
156 CHECK_INT(scan_int("123", 3, &value), 0);
157 CHECK_INT(value, 123);
158 CHECK_INT(scan_int("-45", 3, &value), 0);
159 CHECK_INT(value, -45);
160
161 test_case("and only as far as the length given");
162 CHECK_INT(scan_int("12345", 3, &value), 0);
163 CHECK_INT(value, 123);
164}
165
166static void case_int_rejects_the_rest(void) {
167 int64_t value = 4711;
168
169 test_case("anything that is not all digits is refused");
170 CHECK_INT(scan_int("12a", 3, &value), -1);
171 CHECK_INT(scan_int("", 0, &value), -1);
172 CHECK_INT(scan_int("-", 1, &value), -1);
173 CHECK_INT(scan_int(" 12", 3, &value), -1);
174 CHECK_INT(scan_int("+12", 3, &value), -1);
175
176 test_case("and a refused field leaves the number alone");
177 CHECK_INT(value, 4711);
178}
179
180static void case_int_overflow(void) {
181 int64_t value = 0;
182
183 test_case("a field too long to fit is refused rather than wrapped");
184 CHECK_INT(scan_int("9223372036854775807", 19, &value), 0);
185 CHECK_INT(value, INT64_MAX);
186 CHECK_INT(scan_int("9223372036854775808", 19, &value), -1);
187 CHECK_INT(scan_int("99999999999999999999", 20, &value), -1);
188
189 test_case("including the negative side");
190 CHECK_INT(scan_int("-9223372036854775807", 20, &value), 0);
191 CHECK_INT(value, -INT64_MAX);
192}
193
194void test_scan(void) {
195 case_int_whole_field();
196 case_int_rejects_the_rest();
197 case_int_overflow();
198 case_plain_numbers();
199 case_stops_at_non_digit();
200 case_rejects_whitespace();
201 case_rejects_sign();
202 case_rejects_empty_and_junk();
203 case_no_alternative_bases();
204 case_refuses_out_of_range();
205 case_sixty_four_bit_range();
206 case_leading_zeros_allowed();
207 case_bencode_rejects_leading_zeros();
208 case_bencode_accepts_canonical();
209 case_bencode_inherits_the_rest();
210}
diff --git a/tests/t_socket.c b/tests/t_socket.c
new file mode 100644
index 0000000..6f07f95
--- /dev/null
+++ b/tests/t_socket.c
@@ -0,0 +1,416 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <errno.h>
6#include <fcntl.h>
7#include <netinet/in.h>
8#include <poll.h>
9#include <pthread.h>
10#include <signal.h>
11#include <stdatomic.h>
12#include <string.h>
13#include <sys/socket.h>
14#include <sys/time.h>
15#include <unistd.h>
16
17/* Opentracker */
18#include "ot_ip.h"
19#include "ot_socket.h"
20#include "trackerlogic.h"
21#include "test.h"
22
23/* These cases talk to the loopback interface rather than to a mock, because
24 what is worth pinning down here is the behaviour of the socket options the
25 rest of the tracker relies on, and only the kernel can report that. */
26
27static const char ip_any[16] = {0};
28static const char ip_loopback[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
29static const char ip_v4_loopback[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1};
30/* RFC 3849 reserves 2001:db8::/32 for documentation, so no host carries it */
31static const char ip_unassigned[16] = {0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
32
33/* What a socket ended up bound to, which is not always what was asked for: a
34 FreeBSD jail, for one, rewrites a loopback bind to the address it was given.
35 A datagram a socket sends to itself must come back carrying this, so the
36 cases below compare against it rather than against the address they passed
37 to the bind. */
38static void bound_address(int s, char ip[16], uint16_t *port) {
39 struct sockaddr_storage ss;
40 socklen_t len = sizeof(ss);
41
42 memset(&ss, 0, sizeof(ss));
43 memset(ip, 0, 16);
44 *port = 0;
45 if (getsockname(s, (struct sockaddr *)&ss, &len) == -1)
46 return;
47
48 /* Spelled out here rather than borrowed from ot_socket.c, so that a wrong
49 idea about how a kernel reports an address cannot hide in both at once */
50 if (ss.ss_family == AF_INET) {
51 const struct sockaddr_in *sa = (const struct sockaddr_in *)&ss;
52
53 memcpy(ip, ip_v4mapped_prefix, sizeof(ip_v4mapped_prefix));
54 memcpy(ip + sizeof(ip_v4mapped_prefix), &sa->sin_addr, 4);
55 *port = ntohs(sa->sin_port);
56 } else {
57 const struct sockaddr_in6 *sa = (const struct sockaddr_in6 *)&ss;
58
59 memcpy(ip, &sa->sin6_addr, 16);
60 *port = ntohs(sa->sin6_port);
61 }
62}
63
64static int is_nonblocking(int s) {
65 int flags = fcntl(s, F_GETFL, 0);
66 return flags != -1 && (flags & O_NONBLOCK) != 0;
67}
68
69static int sock_flag(int s, int level, int option) {
70 int value = -1;
71 socklen_t len = sizeof(value);
72
73 if (getsockopt(s, level, option, &value, &len) == -1)
74 return -1;
75 return value != 0;
76}
77
78/* Wait for one event, so a test never blocks forever on a lost packet */
79static int wait_for_ms(int s, short events, int timeout_ms) {
80 struct pollfd pfd;
81
82 pfd.fd = s;
83 pfd.events = events;
84 pfd.revents = 0;
85 return poll(&pfd, 1, timeout_ms) == 1;
86}
87
88static int wait_for(int s, short events) { return wait_for_ms(s, events, 2000); }
89
90/* ------------------------------------------------------------ invariants */
91
92/* Asked for the wildcard address, because a socket bound to one specific
93 IPv6 address cannot carry IPv4 traffic anyway and Linux turns IPV6_V6ONLY
94 back on in that case. The tracker's own default is the wildcard. */
95static void case_socket_options(void) {
96 int udp, tcp;
97
98 test_case("a bound udp socket is non blocking and serves both families");
99 udp = socket_udp_bind(ip_any, 0, SOCKET_EXCLUSIVE);
100 CHECK(udp != -1);
101 CHECK_INT(is_nonblocking(udp), 1);
102 CHECK_INT(sock_flag(udp, IPPROTO_IPV6, IPV6_V6ONLY), 0);
103 close(udp);
104
105 test_case("a listening tcp socket is non blocking and serves both families");
106 tcp = socket_tcp_listen(ip_any, 0, SOCKET_EXCLUSIVE);
107 CHECK(tcp != -1);
108 CHECK_INT(is_nonblocking(tcp), 1);
109 CHECK_INT(sock_flag(tcp, IPPROTO_IPV6, IPV6_V6ONLY), 0);
110 close(tcp);
111}
112
113#ifdef SO_REUSEPORT
114static void case_sharing_is_opt_in(void) {
115 int s;
116
117 test_case("an address is exclusive unless sharing is asked for");
118 s = socket_udp_bind(ip_loopback, 0, SOCKET_EXCLUSIVE);
119 CHECK(s != -1);
120 CHECK_INT(sock_flag(s, SOL_SOCKET, SO_REUSEPORT), 0);
121 close(s);
122
123 test_case("and shared when it is");
124 s = socket_udp_bind(ip_loopback, 0, SOCKET_SHARED);
125 CHECK(s != -1);
126 CHECK_INT(sock_flag(s, SOL_SOCKET, SO_REUSEPORT), 1);
127 close(s);
128}
129#endif
130
131/* ------------------------------------------------------------------- udp */
132
133static void case_udp_roundtrip(void) {
134 char buf[32], ip[16], own_ip[16];
135 uint16_t port = 0, own_port = 0;
136 int s;
137
138 test_case("a datagram comes back with the sender's address and port");
139 s = socket_udp_bind(ip_loopback, 0, SOCKET_EXCLUSIVE);
140 CHECK(s != -1);
141 bound_address(s, own_ip, &own_port);
142 CHECK(own_port != 0);
143 CHECK_INT(socket_send(s, "opentracker", 11, own_ip, own_port), 11);
144 CHECK_INT(wait_for(s, POLLIN), 1);
145 CHECK_INT(socket_recv(s, buf, sizeof(buf), ip, &port), 11);
146 CHECK_MEM(buf, "opentracker", 11);
147 CHECK_MEM(ip, own_ip, 16);
148 CHECK_INT(port, own_port);
149 close(s);
150}
151
152/* udp_workers_deinit and livesync_deinit end a read another thread is parked
153 in by signalling that thread. Which mechanisms wake a blocked reader
154 differs between kernels -- shutting the socket down does so on Linux and
155 FreeBSD but not on Darwin, closing it does so on Darwin but not on Linux --
156 so the one the tracker relies on is checked rather than assumed. The
157 watchdog is the test's own: where a reader is not woken this fails with a
158 figure to look at instead of hanging the suite. */
159static _Atomic int reader_returned;
160static int reader_socket;
161
162static void reader_wake(int s) { (void)s; }
163
164static void *blocked_reader(void *args) {
165 char buf[32], ip[16];
166 uint16_t port = 0;
167
168 (void)args;
169 socket_recv(reader_socket, buf, sizeof(buf), ip, &port);
170 atomic_store(&reader_returned, 1);
171 return NULL;
172}
173
174static void case_a_signal_ends_a_blocking_read(void) {
175 struct sigaction sa;
176 struct timeval watchdog = {2, 0};
177 pthread_t thread;
178 int waited;
179
180 test_case("a signal ends a read another thread is parked in");
181 memset(&sa, 0, sizeof(sa));
182 sa.sa_handler = reader_wake;
183 sa.sa_flags = 0; /* SA_RESTART would resume the read instead of ending it */
184 CHECK_INT(sigaction(OT_SIGNAL_WAKE, &sa, NULL), 0);
185
186 atomic_store(&reader_returned, 0);
187 reader_socket = socket_udp_bind(ip_loopback, 0, SOCKET_EXCLUSIVE);
188 CHECK(reader_socket != -1);
189 CHECK_INT(socket_set_blocking(reader_socket, 1), 0);
190 CHECK_INT(setsockopt(reader_socket, SOL_SOCKET, SO_RCVTIMEO, &watchdog, sizeof(watchdog)), 0);
191
192 CHECK_INT(pthread_create(&thread, NULL, blocked_reader, NULL), 0);
193 usleep(100000); /* long enough to be sure it reached the read */
194 CHECK_INT(pthread_kill(thread, OT_SIGNAL_WAKE), 0);
195
196 for (waited = 0; waited < 1000 && !atomic_load(&reader_returned); ++waited)
197 usleep(1000);
198 CHECK(waited < 1000);
199 pthread_join(thread, NULL);
200 close(reader_socket);
201}
202
203/* What a deferred accept is for is a descriptor that already has the request
204 in it, so what is checked is the silence before: a client that has
205 connected but said nothing must not make the listener readable. Kernels
206 that cannot do this say so, and then there is nothing to check. */
207static void case_deferred_accept(void) {
208 struct sockaddr_in6 address;
209 char ip[16];
210 uint16_t port = 0;
211 int listener, client;
212
213 test_case("a connection that has sent nothing is held back from accept");
214 listener = socket_tcp_listen(ip_loopback, 0, SOCKET_EXCLUSIVE);
215 CHECK(listener != -1);
216 if (socket_defer_accept(listener) == -1) {
217 close(listener);
218 return;
219 }
220 bound_address(listener, ip, &port);
221
222 client = socket(AF_INET6, SOCK_STREAM, 0);
223 CHECK(client != -1);
224 memset(&address, 0, sizeof(address));
225 address.sin6_family = AF_INET6;
226 address.sin6_port = htons(port);
227 memcpy(&address.sin6_addr, ip_loopback, 16);
228 CHECK_INT(connect(client, (struct sockaddr *)&address, sizeof(address)), 0);
229
230 CHECK_INT(wait_for_ms(listener, POLLIN, 300), 0);
231
232 CHECK_INT((int)write(client, "GET / HTTP/1.0\r\n\r\n", 18), 18);
233 CHECK_INT(wait_for(listener, POLLIN), 1);
234
235 close(client);
236 close(listener);
237}
238
239/* An IPv4 peer must arrive in the v4 mapped form opentracker stores, however
240 the kernel chose to report it. Linux fills a v4 mapped sockaddr_in6 here
241 and the BSDs fill a plain sockaddr_in, so this is the case that tells the
242 two apart. */
243static void case_udp_v4mapped(void) {
244 char buf[32], ip[16], receiver_ip[16], sender_ip[16];
245 uint16_t port = 0, receiver_port = 0, sender_port = 0;
246 int receiver, sender;
247
248 test_case("an IPv4 sender is reported in its v4 mapped form");
249 receiver = socket_udp_bind(ip_v4_loopback, 0, SOCKET_EXCLUSIVE);
250 CHECK(receiver != -1);
251 sender = socket_udp_bind(ip_v4_loopback, 0, SOCKET_EXCLUSIVE);
252 CHECK(sender != -1);
253 bound_address(receiver, receiver_ip, &receiver_port);
254 bound_address(sender, sender_ip, &sender_port);
255 CHECK_INT(ip_is_v4mapped(sender_ip), 1);
256
257 CHECK_INT(socket_send(sender, "v4", 2, receiver_ip, receiver_port), 2);
258 CHECK_INT(wait_for(receiver, POLLIN), 1);
259 CHECK_INT(socket_recv(receiver, buf, sizeof(buf), ip, &port), 2);
260 CHECK_INT(ip_is_v4mapped(ip), 1);
261 CHECK_MEM(ip, sender_ip, 16);
262 CHECK_INT(port, sender_port);
263 close(sender);
264 close(receiver);
265}
266
267/* ------------------------------------------------------------------- tcp */
268
269static void case_tcp_roundtrip(void) {
270 char ip[16], listener_ip[16], client_ip[16];
271 uint16_t port = 0, listener_port = 0, client_port = 0;
272 int listener, client, accepted;
273
274 test_case("a connection is accepted and carries the caller's address");
275 listener = socket_tcp_listen(ip_loopback, 0, SOCKET_EXCLUSIVE);
276 CHECK(listener != -1);
277 bound_address(listener, listener_ip, &listener_port);
278 CHECK(listener_port != 0);
279
280 client = socket_tcp_connect(ip_loopback, 0, listener_ip, listener_port);
281 CHECK(client != -1);
282 CHECK_INT(wait_for(client, POLLOUT), 1);
283 CHECK_INT(socket_is_connected(client), 1);
284 bound_address(client, client_ip, &client_port);
285
286 CHECK_INT(wait_for(listener, POLLIN), 1);
287 accepted = socket_accept(listener, ip, &port);
288 CHECK(accepted != -1);
289 CHECK_MEM(ip, client_ip, 16);
290 CHECK_INT(port, client_port);
291
292 test_case("the accepted socket is handed over non blocking");
293 CHECK_INT(is_nonblocking(accepted), 1);
294
295 close(accepted);
296 close(client);
297 close(listener);
298}
299
300static void case_connect_refused(void) {
301 char listener_ip[16];
302 int listener, client;
303 uint16_t port;
304
305 test_case("a refused connection is reported by socket_is_connected");
306 /* Take a port, then drop it, so nothing is listening on it any more */
307 listener = socket_tcp_listen(ip_loopback, 0, SOCKET_EXCLUSIVE);
308 CHECK(listener != -1);
309 bound_address(listener, listener_ip, &port);
310 close(listener);
311
312 client = socket_tcp_connect(ip_loopback, 0, listener_ip, port);
313 CHECK(client != -1);
314 CHECK_INT(wait_for(client, POLLOUT), 1);
315 CHECK_INT(socket_is_connected(client), 0);
316 CHECK_INT(errno, ECONNREFUSED);
317 close(client);
318}
319
320/* --------------------------------------------------------- failed binds */
321
322/* The lowest free descriptor is handed out first, so a number that stays put
323 across a failing call shows the call did not keep a socket behind. */
324static int next_descriptor(void) {
325 int fd = dup(0);
326
327 if (fd != -1)
328 close(fd);
329 return fd;
330}
331
332static void case_bind_failure(void) {
333 int before;
334
335 test_case("binding an address no interface carries fails");
336 before = next_descriptor();
337 CHECK(before != -1);
338 CHECK_INT(socket_tcp_listen(ip_unassigned, 0, SOCKET_EXCLUSIVE), -1);
339 CHECK_INT(socket_udp_bind(ip_unassigned, 0, SOCKET_EXCLUSIVE), -1);
340
341 test_case("a failed bind leaves no socket behind");
342 CHECK_INT(next_descriptor(), before);
343}
344
345/* The holder binds the way the tracker does, which lets a second socket in
346 beside it, and that is what the probe is there to see through. */
347static void case_a_taken_udp_address_is_noticed(void) {
348 char ip[16];
349 uint16_t port;
350 int holder;
351
352 test_case("a udp address somebody holds is reported as taken");
353 holder = socket_udp_bind(ip_loopback, 0, SOCKET_SHARED);
354 CHECK(holder != -1);
355 bound_address(holder, ip, &port);
356 CHECK_INT(socket_udp_is_taken(ip_loopback, port), 1);
357
358 test_case("and as free again once it is let go");
359 close(holder);
360 CHECK_INT(socket_udp_is_taken(ip_loopback, port), 0);
361}
362
363#ifdef WANT_SYNC_LIVE
364/* Reading an IPv4 multicast option back: Linux answers with an int, the BSDs
365 with a single byte, so ask how much was written. */
366static int mcast_option(int s, int option) {
367 int value = 0;
368 socklen_t len = sizeof(value);
369
370 if (getsockopt(s, IPPROTO_IP, option, &value, &len) == -1)
371 return -1;
372 if (len == 1)
373 return *(unsigned char *)&value;
374 return value;
375}
376
377static void case_mcast_sender(void) {
378 int s;
379
380 test_case("the sending socket keeps its traffic on the local network");
381 s = socket_mcast_bind(ip_v4_loopback, 0, 0);
382 CHECK(s != -1);
383 CHECK_INT(mcast_option(s, IP_MULTICAST_TTL), 1);
384
385 test_case("and does not hear itself unless it is asked to");
386 CHECK_INT(mcast_option(s, IP_MULTICAST_LOOP), 0);
387
388 test_case("whoever sends from it is serving clients too, so it cannot block");
389 CHECK_INT(is_nonblocking(s), 1);
390 close(s);
391
392 test_case("the proxy asks to hear itself and gets it");
393 s = socket_mcast_bind(ip_v4_loopback, 0, 1);
394 CHECK(s != -1);
395 CHECK_INT(mcast_option(s, IP_MULTICAST_LOOP), 1);
396 close(s);
397}
398#endif
399
400void test_socket(void) {
401 case_socket_options();
402#ifdef SO_REUSEPORT
403 case_sharing_is_opt_in();
404#endif
405 case_udp_roundtrip();
406 case_a_signal_ends_a_blocking_read();
407 case_udp_v4mapped();
408 case_tcp_roundtrip();
409 case_deferred_accept();
410 case_connect_refused();
411 case_bind_failure();
412 case_a_taken_udp_address_is_noticed();
413#ifdef WANT_SYNC_LIVE
414 case_mcast_sender();
415#endif
416}
diff --git a/tests/t_trackerlogic.c b/tests/t_trackerlogic.c
new file mode 100644
index 0000000..1cf9141
--- /dev/null
+++ b/tests/t_trackerlogic.c
@@ -0,0 +1,241 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <arpa/inet.h>
6#include <signal.h>
7#include <pthread.h>
8#include <string.h>
9
10/* Opentracker */
11#include "ot_mutex.h"
12#include "trackerlogic.h"
13#include "test.h"
14
15/* The swarm itself: what an announce does to a torrent, and what a scrape
16 says about it afterwards. The counts are read back through the udp scrape
17 because that is the one reply the tracker builds as plain numbers. */
18
19static struct ot_workstruct ws;
20
21static void hash_named(ot_hash hash, const char *name) {
22 memset(hash, 0, sizeof(ot_hash));
23 memcpy(hash, name, strlen(name) < sizeof(ot_hash) ? strlen(name) : sizeof(ot_hash));
24}
25
26/* An IPv4 peer arrives as the v4 mapped form the tracker stores */
27static void peer_v4(ot_peer6 peer, uint8_t last, uint16_t port) {
28 ot_ip6 ip = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 10, 0, 0, 0};
29 uint16_t net_port = htons(port);
30
31 ip[15] = last;
32 memset(peer, 0, sizeof(ot_peer6));
33 OT_SETIP(peer, ip);
34 OT_SETPORT(peer, &net_port);
35 OT_PEERFLAG(peer) = 0;
36}
37
38static void peer_v6(ot_peer6 peer, uint8_t last, uint16_t port) {
39 ot_ip6 ip = {0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
40 uint16_t net_port = htons(port);
41
42 ip[15] = last;
43 memset(peer, 0, sizeof(ot_peer6));
44 OT_SETIP(peer, ip);
45 OT_SETPORT(peer, &net_port);
46 OT_PEERFLAG(peer) = 0;
47}
48
49static void announce(ot_hash *hash, ot_peer6 peer) {
50 ws.hash = hash;
51 memcpy(ws.peer, peer, sizeof(ot_peer6));
52 ws.reply = ws.outbuf;
53 add_peer_to_torrent_and_return_peers(FLAG_TCP, &ws, 50);
54}
55
56/* seeders, downloads completed, leechers */
57static void scrape(ot_hash hash, uint32_t counts[3]) {
58 char reply[12];
59
60 return_udp_scrape_for_torrent(hash, reply);
61 counts[0] = ntohl(((uint32_t *)reply)[0]);
62 counts[1] = ntohl(((uint32_t *)reply)[1]);
63 counts[2] = ntohl(((uint32_t *)reply)[2]);
64}
65
66static void case_an_announce_makes_a_torrent(void) {
67 ot_hash hash;
68 ot_peer6 peer;
69 uint32_t counts[3];
70 size_t before = mutex_get_torrent_count();
71
72 test_case("the first announce for a hash creates its torrent");
73 hash_named(hash, "first-announce");
74 peer_v4(peer, 1, 6881);
75 announce(&hash, peer);
76
77 CHECK_INT((int)(mutex_get_torrent_count() - before), 1);
78 scrape(hash, counts);
79 CHECK_INT((int)counts[2], 1); /* one leecher */
80 CHECK_INT((int)counts[0], 0);
81}
82
83static void case_the_same_peer_twice_is_one_peer(void) {
84 ot_hash hash;
85 ot_peer6 peer;
86 uint32_t counts[3];
87
88 test_case("announcing twice renews a peer rather than adding another");
89 hash_named(hash, "renewing");
90 peer_v4(peer, 2, 6881);
91 announce(&hash, peer);
92 announce(&hash, peer);
93
94 scrape(hash, counts);
95 CHECK_INT((int)counts[2], 1);
96}
97
98static void case_a_port_makes_a_different_peer(void) {
99 ot_hash hash;
100 ot_peer6 peer;
101 uint32_t counts[3];
102
103 test_case("the same address on another port is another peer");
104 hash_named(hash, "two-ports");
105 peer_v4(peer, 3, 6881);
106 announce(&hash, peer);
107 peer_v4(peer, 3, 6882);
108 announce(&hash, peer);
109
110 scrape(hash, counts);
111 CHECK_INT((int)counts[2], 2);
112}
113
114static void case_seeding_is_counted_apart(void) {
115 ot_hash hash;
116 ot_peer6 peer;
117 uint32_t counts[3];
118
119 test_case("a seeder counts as complete, a leecher as incomplete");
120 hash_named(hash, "seed-and-leech");
121 peer_v4(peer, 4, 6881);
122 OT_PEERFLAG(peer) |= PEER_FLAG_SEEDING;
123 announce(&hash, peer);
124 peer_v4(peer, 5, 6881);
125 announce(&hash, peer);
126
127 scrape(hash, counts);
128 CHECK_INT((int)counts[0], 1);
129 CHECK_INT((int)counts[2], 1);
130}
131
132static void case_completion_without_seeding_is_not_believed(void) {
133 ot_hash hash;
134 ot_peer6 peer;
135 uint32_t counts[3];
136
137 test_case("a peer that claims to have completed but is still leeching is not counted");
138 hash_named(hash, "claiming");
139 peer_v4(peer, 6, 6881);
140 OT_PEERFLAG(peer) |= PEER_FLAG_COMPLETED;
141 announce(&hash, peer);
142
143 scrape(hash, counts);
144 CHECK_INT((int)counts[1], 0);
145 CHECK_INT((int)counts[2], 1); /* still a leecher */
146}
147
148static void case_completing_is_counted_once(void) {
149 ot_hash hash;
150 ot_peer6 peer;
151 uint32_t counts[3];
152
153 test_case("a seeder reporting completion is counted once, however often it says so");
154 hash_named(hash, "completing");
155 peer_v4(peer, 7, 6881);
156 OT_PEERFLAG(peer) |= PEER_FLAG_COMPLETED | PEER_FLAG_SEEDING;
157 announce(&hash, peer);
158 announce(&hash, peer);
159 announce(&hash, peer);
160
161 scrape(hash, counts);
162 CHECK_INT((int)counts[1], 1);
163 CHECK_INT((int)counts[0], 1);
164}
165
166static void case_a_peer_can_leave(void) {
167 ot_hash hash;
168 ot_peer6 peer;
169 uint32_t counts[3];
170
171 test_case("a peer that stops is gone from the swarm");
172 hash_named(hash, "leaving");
173 peer_v4(peer, 7, 6881);
174 announce(&hash, peer);
175 peer_v4(peer, 8, 6881);
176 announce(&hash, peer);
177 scrape(hash, counts);
178 CHECK_INT((int)counts[2], 2);
179
180 ws.hash = &hash;
181 memcpy(ws.peer, peer, sizeof(ot_peer6));
182 remove_peer_from_torrent(FLAG_TCP, &ws);
183
184 scrape(hash, counts);
185 CHECK_INT((int)counts[2], 1);
186}
187
188static void case_the_families_are_kept_apart(void) {
189 ot_hash hash;
190 ot_peer6 peer;
191 uint32_t counts[3];
192
193 test_case("a v4 and a v6 peer of one swarm are both counted");
194 hash_named(hash, "dual-stack");
195 peer_v4(peer, 9, 6881);
196 announce(&hash, peer);
197 peer_v6(peer, 9, 6881);
198 announce(&hash, peer);
199
200 scrape(hash, counts);
201 CHECK_INT((int)counts[2], 2);
202}
203
204static void case_a_hash_nobody_announced(void) {
205 ot_hash hash;
206 uint32_t counts[3];
207
208 test_case("a hash nobody has announced scrapes as nothing at all");
209 hash_named(hash, "never-seen");
210 scrape(hash, counts);
211 CHECK_INT((int)counts[0], 0);
212 CHECK_INT((int)counts[1], 0);
213 CHECK_INT((int)counts[2], 0);
214}
215
216void test_trackerlogic(void) {
217 sigset_t signal_mask;
218
219 /* accesslist_init starts a thread that waits for SIGHUP and is stopped by
220 being sent one, so the signal has to be blocked here as the tracker
221 blocks it, or stopping the tracker logic ends this process instead */
222 sigemptyset(&signal_mask);
223 sigaddset(&signal_mask, SIGHUP);
224 pthread_sigmask(SIG_BLOCK, &signal_mask, NULL);
225
226 trackerlogic_init();
227 CHECK_INT(workstruct_init(&ws, G_INBUF_SIZE), 0);
228
229 case_an_announce_makes_a_torrent();
230 case_the_same_peer_twice_is_one_peer();
231 case_a_port_makes_a_different_peer();
232 case_seeding_is_counted_apart();
233 case_completion_without_seeding_is_not_believed();
234 case_completing_is_counted_once();
235 case_a_peer_can_leave();
236 case_the_families_are_kept_apart();
237 case_a_hash_nobody_announced();
238
239 workstruct_deinit(&ws);
240 trackerlogic_deinit();
241}
diff --git a/tests/t_urlencoded.c b/tests/t_urlencoded.c
new file mode 100644
index 0000000..9935c1c
--- /dev/null
+++ b/tests/t_urlencoded.c
@@ -0,0 +1,363 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <string.h>
6
7/* Opentracker */
8#include "ot_urlencoded.h"
9#include "test.h"
10
11/* The scanner returns the number of bytes written to the destination, or
12 -1 for a parse error and -2 for a hard terminator encountered before any
13 output was produced. It advances the source pointer past the separator it
14 stopped on, except for hard terminators and the '&' ending a parameter,
15 which it leaves for the next call to see. */
16
17static void case_path(void) {
18 char query[] = "/announce?info_hash=A";
19 char dest[64];
20 char *p = query;
21 ssize_t n;
22
23 test_case("path stops at the question mark");
24 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_PATH);
25 CHECK_INT(n, 9);
26 dest[n] = 0;
27 CHECK_STR(dest, "/announce");
28 CHECK_INT(*p, 'i');
29}
30
31static void case_param_and_value(void) {
32 char query[] = "info_hash=abc&port=80";
33 char dest[64];
34 char *p = query;
35 ssize_t n;
36
37 test_case("parameter stops at '=', value stops at '&'");
38 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
39 CHECK_INT(n, 9);
40 dest[n] = 0;
41 CHECK_STR(dest, "info_hash");
42
43 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
44 CHECK_INT(n, 3);
45 dest[n] = 0;
46 CHECK_STR(dest, "abc");
47
48 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
49 CHECK_INT(n, 4);
50 dest[n] = 0;
51 CHECK_STR(dest, "port");
52
53 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
54 CHECK_INT(n, 2);
55 dest[n] = 0;
56 CHECK_STR(dest, "80");
57}
58
59static void case_percent_decoding(void) {
60 char query[] = "%41%42%43&x=1";
61 char dest[64];
62 char *p = query;
63 ssize_t n;
64
65 test_case("percent escapes decode");
66 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
67 CHECK_INT(n, 3);
68 CHECK_MEM(dest, "ABC", 3);
69}
70
71static void case_binary_info_hash(void) {
72 /* The twenty byte info_hash is what the announce path really decodes */
73 char query[] = "%00%01%02%ff%fe%7f%80ABCDEFGHIJKLM&x=1";
74 unsigned char want[] = {0x00, 0x01, 0x02, 0xff, 0xfe, 0x7f, 0x80, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'};
75 char dest[64];
76 char *p = query;
77 ssize_t n;
78
79 test_case("twenty byte binary value survives decoding");
80 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
81 CHECK_INT(n, 20);
82 CHECK_MEM(dest, want, 20);
83}
84
85static void case_in_place(void) {
86 char query[] = "%41%42&x=1";
87 char *p = query;
88 ssize_t n;
89
90 test_case("decoding in place over the source is safe");
91 n = urlencoded_parse(&p, query, query + sizeof(query), SCAN_SEARCHPATH_VALUE);
92 CHECK_INT(n, 2);
93 CHECK_MEM(query, "AB", 2);
94}
95
96static void case_bad_escape(void) {
97 char query[] = "%zz";
98 char dest[64];
99 char *p = query;
100 ssize_t n;
101
102 test_case("a non hexadecimal escape is a parse error");
103 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
104 CHECK_INT(n, -1);
105}
106
107static void case_truncated_escape(void) {
108 char query[] = "%4";
109 char dest[64];
110 char *p = query;
111 ssize_t n;
112
113 test_case("an escape cut short by the terminator is a parse error");
114 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
115 CHECK_INT(n, -1);
116}
117
118static void case_terminator(void) {
119 char empty[] = "";
120 char space[] = " rest";
121 char dest[64];
122 char *p = empty;
123 ssize_t n;
124
125 test_case("a hard terminator before any output reports end of input");
126 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
127 CHECK_INT(n, -2);
128
129 p = space;
130 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_PARAM);
131 CHECK_INT(n, -2);
132}
133
134static void case_terminator_after_output(void) {
135 char query[] = "abc";
136 char dest[64];
137 char *p = query;
138 ssize_t n;
139
140 test_case("a hard terminator after output is left for the next call");
141 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
142 CHECK_INT(n, 3);
143 CHECK_INT(*p, 0);
144 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
145 CHECK_INT(n, -2);
146}
147
148/* The character matrix makes '?' terminate a path only, and '=' terminate a
149 path or a parameter only. Both are ordinary characters inside a value, so a
150 value is free to contain a nested query string. */
151
152static void case_separators_are_contextual(void) {
153 char question[] = "a?b&x=1";
154 char equals[] = "a=b&x=1";
155 char dest[64];
156 char *p = question;
157 ssize_t n;
158
159 test_case("a question mark is literal inside a value");
160 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
161 CHECK_INT(n, 3);
162 dest[n] = 0;
163 CHECK_STR(dest, "a?b");
164
165 test_case("an equals sign is literal inside a value");
166 p = equals;
167 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
168 CHECK_INT(n, 3);
169 dest[n] = 0;
170 CHECK_STR(dest, "a=b");
171}
172
173static void case_ampersand_in_path(void) {
174 char query[] = "/path&x";
175 char dest[64];
176 char *p = query;
177 ssize_t n;
178
179 test_case("an ampersand in a path is a parse error");
180 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_PATH);
181 CHECK_INT(n, -1);
182}
183
184static void case_raw_high_byte(void) {
185 char query[] = {'a', 'b', (char)0x80, 0};
186 char dest[64];
187 char *p = query;
188 ssize_t n;
189
190 test_case("an undecoded byte above ASCII is a parse error");
191 n = urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE);
192 CHECK_INT(n, -1);
193}
194
195static void case_skipvalue(void) {
196 char query[] = "abc&next=1";
197 char bare[] = "abc";
198 char *p = query;
199
200 test_case("skipvalue steps over the value and its separator");
201 urlencoded_skip_value(&p);
202 CHECK_STR(p, "next=1");
203
204 test_case("skipvalue leaves a hard terminator in place");
205 p = bare;
206 urlencoded_skip_value(&p);
207 CHECK_INT(*p, 0);
208}
209
210static void case_find_keywords(void) {
211 static const ot_keywords keywords[] = {{"port", 1}, {"left", 2}, {"compact", 3}, {NULL, -3}};
212 char match[] = "left=0";
213 char nomatch[] = "bogus=1";
214 char prefix[] = "por=1";
215 char *p = match;
216
217 test_case("a known keyword returns its value");
218 CHECK_INT(urlencoded_match_keyword(keywords, &p, match + sizeof(match), SCAN_SEARCHPATH_PARAM), 2);
219
220 test_case("an unknown keyword returns -3");
221 p = nomatch;
222 CHECK_INT(urlencoded_match_keyword(keywords, &p, nomatch + sizeof(nomatch), SCAN_SEARCHPATH_PARAM), -3);
223
224 test_case("a prefix of a keyword does not match it");
225 p = prefix;
226 CHECK_INT(urlencoded_match_keyword(keywords, &p, prefix + sizeof(prefix), SCAN_SEARCHPATH_PARAM), -3);
227}
228
229/* The encoding direction. Which bytes survive unescaped is fixed by what
230 existing parsers of the urlencoded full scrape expect, so these cases pin
231 the set rather than describe a preference. */
232
233static void case_fmt_passes_safe_bytes(void) {
234 const uint8_t src[] = "aZ09$-./=_~";
235 char dest[64];
236 size_t n;
237
238 test_case("alphanumerics and the safe punctuation pass through");
239 n = urlencoded_format(dest, src, 11);
240 dest[n] = 0;
241 CHECK_INT(n, 11);
242 CHECK_STR(dest, "aZ09$-./=_~");
243}
244
245static void case_fmt_escapes_the_rest(void) {
246 const uint8_t src[] = {' ', '%', '&', '+', ':', '?'};
247 char dest[64];
248 size_t n;
249
250 test_case("everything else becomes a percent escape");
251 n = urlencoded_format(dest, src, sizeof(src));
252 dest[n] = 0;
253 CHECK_INT(n, 18);
254 CHECK_STR(dest, "%20%25%26%2b%3a%3f");
255}
256
257static void case_fmt_hex_is_lower_case(void) {
258 const uint8_t src[] = {0x00, 0xab, 0xff};
259 char dest[64];
260 size_t n;
261
262 test_case("escapes use lower case hex digits");
263 n = urlencoded_format(dest, src, sizeof(src));
264 dest[n] = 0;
265 CHECK_INT(n, 9);
266 CHECK_STR(dest, "%00%ab%ff");
267}
268
269static void case_fmt_zero_length(void) {
270 char dest[4];
271
272 test_case("a zero length input writes nothing");
273 memset(dest, 0x5a, sizeof(dest));
274 CHECK_INT(urlencoded_format(dest, (const uint8_t *)"abc", 0), 0);
275 CHECK_MEM(dest, "\x5a\x5a\x5a\x5a", 4);
276}
277
278static void case_fmt_worst_case_fits(void) {
279 uint8_t src[20];
280 char dest[61];
281 size_t i, n;
282
283 test_case("a hash of entirely unsafe bytes needs three times its length");
284 for (i = 0; i < sizeof(src); ++i)
285 src[i] = 0xff;
286 n = urlencoded_format(dest, src, sizeof(src));
287 dest[n] = 0;
288 CHECK_INT(n, 60);
289 for (i = 0; i < 20; ++i)
290 if (memcmp(dest + 3 * i, "%ff", 3)) {
291 test_failf(__FILE__, __LINE__, "escape %zu is wrong", i);
292 return;
293 }
294 ++test_checks;
295}
296
297static void case_fmt_decoder_disagrees_on_dollar(void) {
298 /* Documenting a known asymmetry rather than a wish. Of the bytes the
299 encoder passes through unescaped, '$' is the only one the decoder then
300 refuses, and it refuses the whole string rather than stopping short.
301 Output of the urlencoded full scrape therefore does not round trip
302 through urlencoded_parse when a hash contains 0x24. Harmless today
303 because only third party tooling reads that output. */
304 const uint8_t src[] = {'a', '$', 'b'};
305 char dest[16];
306 char scanned[16];
307 char *p = dest;
308 size_t n;
309 ssize_t got;
310
311 test_case("the encoder passes '$' but the decoder rejects it");
312 n = urlencoded_format(dest, src, sizeof(src));
313 dest[n] = 0;
314 CHECK_STR(dest, "a$b");
315
316 got = urlencoded_parse(&p, scanned, scanned + sizeof(scanned), SCAN_SEARCHPATH_VALUE);
317 CHECK_INT(got, -1);
318}
319
320static void case_value_stops_at_dest_end(void) {
321 /* A value that decodes to more than the destination holds is a parse error,
322 not a write past the buffer. (ip= used to overflow ws->outbuf this way.) */
323 char query[] = "AAAAAAAAAA&x=1"; /* ten A's then a terminator */
324 char dest[4];
325 char *p = query;
326 test_case("a value longer than the destination returns -1");
327 CHECK_INT((int)urlencoded_parse(&p, dest, dest + sizeof(dest), SCAN_SEARCHPATH_VALUE), -1);
328}
329
330static void case_keyword_with_decoded_nul_does_not_match(void) {
331 /* A percent-encoded NUL used to make a value match a shorter keyword and
332 then index the keyword past its end. */
333 static const ot_keywords keywords[] = {{"port", 1}, {NULL, -3}};
334 char query[] = "port%00xxxx=1";
335 char *p = query;
336 test_case("a keyword followed by a decoded NUL does not match the keyword");
337 CHECK_INT(urlencoded_match_keyword(keywords, &p, query + sizeof(query), SCAN_SEARCHPATH_PARAM), -3);
338}
339
340void test_urlencoded(void) {
341 case_path();
342 case_param_and_value();
343 case_percent_decoding();
344 case_binary_info_hash();
345 case_in_place();
346 case_bad_escape();
347 case_truncated_escape();
348 case_terminator();
349 case_terminator_after_output();
350 case_separators_are_contextual();
351 case_ampersand_in_path();
352 case_raw_high_byte();
353 case_skipvalue();
354 case_find_keywords();
355 case_value_stops_at_dest_end();
356 case_keyword_with_decoded_nul_does_not_match();
357 case_fmt_passes_safe_bytes();
358 case_fmt_escapes_the_rest();
359 case_fmt_hex_is_lower_case();
360 case_fmt_zero_length();
361 case_fmt_worst_case_fits();
362 case_fmt_decoder_disagrees_on_dollar();
363}
diff --git a/tests/t_vector.c b/tests/t_vector.c
new file mode 100644
index 0000000..42ce31a
--- /dev/null
+++ b/tests/t_vector.c
@@ -0,0 +1,308 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <stdlib.h>
7#include <string.h>
8
9/* Opentracker */
10#include "ot_vector.h"
11#include "trackerlogic.h"
12#include "test.h"
13
14/* vector_binary_search returns the matching member when there is one, and otherwise
15 the position at which the key would have to be inserted to keep the vector
16 sorted. exactmatch distinguishes the two. */
17
18static const unsigned char sorted[5][4] = {{0, 0, 0, 1}, {0, 0, 0, 3}, {0, 0, 0, 5}, {0, 0, 0, 7}, {0, 0, 0, 9}};
19
20static void case_search_finds_member(void) {
21 const unsigned char key[4] = {0, 0, 0, 5};
22 int exactmatch;
23 void *found;
24
25 test_case("an existing key is found");
26 found = vector_binary_search(key, sorted, 5, 4, 4, &exactmatch);
27 CHECK(exactmatch != 0);
28 CHECK_PTR(found, sorted[2]);
29}
30
31static void case_search_finds_first_and_last(void) {
32 const unsigned char first[4] = {0, 0, 0, 1};
33 const unsigned char last[4] = {0, 0, 0, 9};
34 int exactmatch;
35
36 test_case("the first and last members are found");
37 CHECK_PTR(vector_binary_search(first, sorted, 5, 4, 4, &exactmatch), sorted[0]);
38 CHECK(exactmatch != 0);
39 CHECK_PTR(vector_binary_search(last, sorted, 5, 4, 4, &exactmatch), sorted[4]);
40 CHECK(exactmatch != 0);
41}
42
43static void case_search_insert_position(void) {
44 const unsigned char middle[4] = {0, 0, 0, 4};
45 const unsigned char before[4] = {0, 0, 0, 0};
46 int exactmatch;
47 void *slot;
48
49 test_case("a missing key yields its insert position");
50 slot = vector_binary_search(middle, sorted, 5, 4, 4, &exactmatch);
51 CHECK_INT(exactmatch, 0);
52 CHECK_PTR(slot, sorted[2]);
53
54 slot = vector_binary_search(before, sorted, 5, 4, 4, &exactmatch);
55 CHECK_INT(exactmatch, 0);
56 CHECK_PTR(slot, sorted[0]);
57}
58
59static void case_search_past_the_end(void) {
60 const unsigned char beyond[4] = {0, 0, 0, 0xff};
61 int exactmatch;
62 void *slot;
63
64 test_case("a key above every member yields the position past the end");
65 slot = vector_binary_search(beyond, sorted, 5, 4, 4, &exactmatch);
66 CHECK_INT(exactmatch, 0);
67 CHECK_PTR(slot, sorted[5]);
68}
69
70static void case_search_empty(void) {
71 int exactmatch;
72 void *base = (void *)sorted;
73
74 test_case("searching an empty vector reports no match at the base");
75 CHECK_PTR(vector_binary_search(sorted[0], base, 0, 4, 4, &exactmatch), base);
76 CHECK_INT(exactmatch, 0);
77}
78
79static void case_insert_keeps_order(void) {
80 ot_vector vector = {NULL, 0, 0};
81 const unsigned char five[4] = {0, 0, 0, 5};
82 const unsigned char one[4] = {0, 0, 0, 1};
83 const unsigned char nine[4] = {0, 0, 0, 9};
84 int exactmatch;
85 void *slot;
86
87 test_case("inserts land in sorted order and grow the vector");
88 slot = vector_find_or_insert(&vector, (void *)five, 4, 4, &exactmatch);
89 CHECK(slot != NULL);
90 CHECK_INT(exactmatch, 0);
91 memcpy(slot, five, 4);
92 CHECK_INT(vector.size, 1);
93 CHECK_INT(vector.space, OT_VECTOR_MIN_MEMBERS);
94
95 slot = vector_find_or_insert(&vector, (void *)one, 4, 4, &exactmatch);
96 CHECK(slot != NULL);
97 CHECK_INT(exactmatch, 0);
98 memcpy(slot, one, 4);
99 CHECK_INT(vector.size, 2);
100
101 slot = vector_find_or_insert(&vector, (void *)nine, 4, 4, &exactmatch);
102 CHECK(slot != NULL);
103 CHECK_INT(exactmatch, 0);
104 memcpy(slot, nine, 4);
105 CHECK_INT(vector.size, 3);
106 CHECK_INT(vector.space, OT_VECTOR_MIN_MEMBERS * OT_VECTOR_GROW_RATIO);
107
108 CHECK_MEM(vector.data, "\0\0\0\1\0\0\0\5\0\0\0\11", 12);
109
110 free(vector.data);
111}
112
113/* The peer variant is reached with an empty vector on every first announce
114 for a torrent, and again whenever a swarm empties and refills, because
115 vector_fixup_peers drops the allocation and nulls the data pointer. */
116
117static void case_insert_peer_into_empty_vector(void) {
118 ot_vector vector = {NULL, 0, 0};
119 ot_peer6 low, high;
120 int exactmatch;
121 ot_peer *slot;
122
123 memset(low, 0x11, sizeof(low));
124 memset(high, 0x99, sizeof(high));
125
126 test_case("the first peer goes into a vector that has no allocation yet");
127 slot = vector_find_or_insert_peer(&vector, low, OT_PEER_SIZE6, &exactmatch);
128 CHECK(slot != NULL);
129 CHECK_INT(exactmatch, 0);
130 memcpy(slot, low, OT_PEER_SIZE6);
131 CHECK_INT(vector.size, 1);
132 CHECK_INT(vector.space, OT_VECTOR_MIN_MEMBERS);
133 CHECK_PTR(slot, vector.data);
134
135 test_case("a second peer keeps the order");
136 slot = vector_find_or_insert_peer(&vector, high, OT_PEER_SIZE6, &exactmatch);
137 CHECK(slot != NULL);
138 CHECK_INT(exactmatch, 0);
139 memcpy(slot, high, OT_PEER_SIZE6);
140 CHECK_INT(vector.size, 2);
141 CHECK_MEM((char *)vector.data, low, OT_PEER_COMPARE_SIZE6);
142 CHECK_MEM((char *)vector.data + OT_PEER_SIZE6, high, OT_PEER_COMPARE_SIZE6);
143
144 test_case("and emptying the vector hands the allocation back");
145 CHECK(vector_remove_peer(&vector, low, OT_PEER_SIZE6) != 0);
146 CHECK(vector_remove_peer(&vector, high, OT_PEER_SIZE6) != 0);
147 CHECK_INT(vector.size, 0);
148 CHECK_PTR(vector.data, NULL);
149
150 test_case("so the next peer starts from no allocation again");
151 slot = vector_find_or_insert_peer(&vector, low, OT_PEER_SIZE6, &exactmatch);
152 CHECK(slot != NULL);
153 CHECK_INT(vector.size, 1);
154
155 free(vector.data);
156}
157
158static void case_insert_finds_existing(void) {
159 ot_vector vector = {NULL, 0, 0};
160 const unsigned char five[4] = {0, 0, 0, 5};
161 int exactmatch;
162 void *slot, *again;
163
164 test_case("a second insert of the same key returns the existing member");
165 slot = vector_find_or_insert(&vector, (void *)five, 4, 4, &exactmatch);
166 CHECK(slot != NULL);
167 memcpy(slot, five, 4);
168
169 again = vector_find_or_insert(&vector, (void *)five, 4, 4, &exactmatch);
170 CHECK(exactmatch != 0);
171 CHECK_PTR(again, vector.data);
172 CHECK_INT(vector.size, 1);
173
174 free(vector.data);
175}
176
177static void case_insert_compare_prefix(void) {
178 ot_vector vector = {NULL, 0, 0};
179 unsigned char first[6] = {1, 2, 3, 0xaa, 0xaa, 0xaa};
180 unsigned char second[6] = {1, 2, 3, 0xbb, 0xbb, 0xbb};
181 int exactmatch;
182 void *slot;
183
184 test_case("only the compare prefix decides identity");
185 slot = vector_find_or_insert(&vector, first, 6, 3, &exactmatch);
186 CHECK(slot != NULL);
187 memcpy(slot, first, 6);
188
189 slot = vector_find_or_insert(&vector, second, 6, 3, &exactmatch);
190 CHECK(exactmatch != 0);
191 CHECK_INT(vector.size, 1);
192 CHECK_MEM(slot, first, 6);
193
194 free(vector.data);
195}
196
197/* ------------------------------------------------- bucket redistribution */
198
199/* A flat peer list of count distinct v4 peers. The low byte of the index goes
200 into the first address byte, so the peers are distinct but arrive in no
201 particular order: a list generated in ascending order would come back
202 sorted whether or not vector_redistribute_buckets sorted it. */
203static void build_flat_vector(ot_vector *peers, size_t count) {
204 size_t i;
205
206 memset(peers, 0, sizeof(*peers));
207 peers->data = malloc(count * OT_PEER_SIZE4);
208 peers->size = count;
209 peers->space = count;
210
211 for (i = 0; i < count; ++i) {
212 uint8_t *peer = (uint8_t *)peers->data + i * OT_PEER_SIZE4;
213
214 memset(peer, 0, OT_PEER_SIZE4);
215 peer[0] = (uint8_t)i;
216 peer[1] = (uint8_t)(i >> 8);
217 peer[2] = (uint8_t)(i >> 16);
218 peer[3] = 1;
219 }
220}
221
222static void case_redistribute_holds_every_peer(void) {
223 const size_t count = 513;
224 ot_vector peers;
225 size_t bucket, total_size = 0, empty = 0, largest = 0;
226 ot_vector *buckets;
227
228 test_case("a peer list past the threshold is split into buckets");
229 build_flat_vector(&peers, count);
230 CHECK(peers.data != NULL);
231 vector_redistribute_buckets(&peers, OT_PEER_SIZE4, count);
232 CHECK_INT(OT_VECTOR_HASBUCKETS(&peers), 1);
233 CHECK_INT(peers.size, 16);
234
235 buckets = peers.data;
236 for (bucket = 0; bucket < peers.size; ++bucket) {
237 total_size += buckets[bucket].size;
238 if (!buckets[bucket].size)
239 ++empty;
240 if (buckets[bucket].size > largest)
241 largest = buckets[bucket].size;
242 }
243
244 test_case("no peer is lost on the way");
245 CHECK_INT(total_size, count);
246
247 /* The point of the exercise is that a lookup only searches one bucket, so
248 a hash that piled everything into one would defeat it. The input and the
249 hash are both fixed, so this is not a matter of luck. */
250 test_case("and they are spread over the buckets rather than piled up");
251 CHECK_INT(empty, 0);
252 CHECK(largest < count / 2);
253
254 vector_clean_list(peers.data, peers.size);
255}
256
257static void case_redistribute_sorts_each_bucket(void) {
258 const size_t count = 1000;
259 ot_vector peers;
260 size_t bucket, i, out_of_order = 0;
261 ot_vector *buckets;
262
263 test_case("every bucket comes back sorted, so bsearch can be used on it");
264 build_flat_vector(&peers, count);
265 CHECK(peers.data != NULL);
266 vector_redistribute_buckets(&peers, OT_PEER_SIZE4, count);
267 CHECK_INT(OT_VECTOR_HASBUCKETS(&peers), 1);
268
269 buckets = peers.data;
270 for (bucket = 0; bucket < peers.size; ++bucket)
271 for (i = 1; i < buckets[bucket].size; ++i) {
272 const uint8_t *prev = (uint8_t *)buckets[bucket].data + (i - 1) * OT_PEER_SIZE4;
273 const uint8_t *next = (uint8_t *)buckets[bucket].data + i * OT_PEER_SIZE4;
274
275 if (memcmp(prev, next, OT_PEER_COMPARE_SIZE4) >= 0)
276 ++out_of_order;
277 }
278 CHECK_INT(out_of_order, 0);
279
280 vector_clean_list(peers.data, peers.size);
281}
282
283static void case_redistribute_below_threshold(void) {
284 ot_vector peers;
285
286 test_case("a small peer list is left flat");
287 build_flat_vector(&peers, 100);
288 CHECK(peers.data != NULL);
289 vector_redistribute_buckets(&peers, OT_PEER_SIZE4, 100);
290 CHECK_INT(OT_VECTOR_HASBUCKETS(&peers), 0);
291 CHECK_INT(peers.size, 100);
292 free(peers.data);
293}
294
295void test_vector(void) {
296 case_search_finds_member();
297 case_search_finds_first_and_last();
298 case_search_insert_position();
299 case_search_past_the_end();
300 case_search_empty();
301 case_insert_keeps_order();
302 case_insert_peer_into_empty_vector();
303 case_insert_finds_existing();
304 case_insert_compare_prefix();
305 case_redistribute_holds_every_peer();
306 case_redistribute_sorts_each_bucket();
307 case_redistribute_below_threshold();
308}
diff --git a/tests/t_workqueue.c b/tests/t_workqueue.c
new file mode 100644
index 0000000..660d882
--- /dev/null
+++ b/tests/t_workqueue.c
@@ -0,0 +1,157 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdlib.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_fdstate.h"
10#include "ot_workqueue.h"
11#include "test.h"
12
13/* A worker asks for a class of task and blocks until one turns up, so a task
14 whose class matches no worker is never claimed and whoever is waiting for
15 its answer waits forever. These cases pin the matching. */
16
17static void case_task_goes_to_its_own_class(void) {
18 ot_tasktype asked;
19 ot_taskid taskid;
20
21 test_case("a worker is handed the task of the class it asked for");
22 CHECK_INT(workqueue_pushtask(41, TASK_FULLSCRAPE_TPB_ASCII), 0);
23 asked = TASK_FULLSCRAPE;
24 taskid = workqueue_poptask(&asked);
25 CHECK(taskid != 0);
26
27 test_case("and the full task type, not just its class");
28 CHECK_INT(asked, TASK_FULLSCRAPE_TPB_ASCII);
29 workqueue_canceltask(41);
30}
31
32static void case_flags_survive_the_queue(void) {
33 ot_tasktype asked;
34
35 test_case("flags outside the class mask are carried through");
36 CHECK_INT(workqueue_pushtask(42, TASK_FULLSCRAPE_TPB_URLENCODED | TASK_FLAG_GZIP), 0);
37 asked = TASK_FULLSCRAPE;
38 CHECK(workqueue_poptask(&asked) != 0);
39 CHECK_INT(asked, TASK_FULLSCRAPE_TPB_URLENCODED | TASK_FLAG_GZIP);
40 workqueue_canceltask(42);
41}
42
43static void case_classes_do_not_cross(void) {
44 ot_tasktype asked;
45 ot_taskid taskid;
46
47 test_case("a stats worker passes over a fullscrape task");
48 CHECK_INT(workqueue_pushtask(43, TASK_FULLSCRAPE_TPB_BINARY), 0);
49 CHECK_INT(workqueue_pushtask(44, TASK_STATS_PEERS), 0);
50
51 asked = TASK_STATS;
52 taskid = workqueue_poptask(&asked);
53 CHECK(taskid != 0);
54 CHECK_INT(asked, TASK_STATS_PEERS);
55
56 test_case("and leaves it for the one that wants it");
57 asked = TASK_FULLSCRAPE;
58 taskid = workqueue_poptask(&asked);
59 CHECK(taskid != 0);
60 CHECK_INT(asked, TASK_FULLSCRAPE_TPB_BINARY);
61
62 workqueue_canceltask(43);
63 workqueue_canceltask(44);
64}
65
66static void case_every_task_gets_its_own_id(void) {
67 ot_tasktype asked;
68 ot_taskid first, second;
69
70 test_case("two queued tasks are handed out under different ids");
71 CHECK_INT(workqueue_pushtask(45, TASK_FULLSCRAPE), 0);
72 CHECK_INT(workqueue_pushtask(46, TASK_FULLSCRAPE), 0);
73
74 asked = TASK_FULLSCRAPE;
75 first = workqueue_poptask(&asked);
76 asked = TASK_FULLSCRAPE;
77 second = workqueue_poptask(&asked);
78 CHECK(first != 0);
79 CHECK(second != 0);
80 CHECK(first != second);
81
82 workqueue_canceltask(45);
83 workqueue_canceltask(46);
84}
85
86static void case_cancelled_task_is_not_handed_out(void) {
87 ot_tasktype asked;
88
89 test_case("a cancelled task is gone before any worker sees it");
90 CHECK_INT(workqueue_pushtask(47, TASK_FULLSCRAPE_TPB_ASCII_PLUS), 0);
91 CHECK_INT(workqueue_pushtask(48, TASK_FULLSCRAPE), 0);
92 workqueue_canceltask(47);
93
94 asked = TASK_FULLSCRAPE;
95 CHECK(workqueue_poptask(&asked) != 0);
96 CHECK_INT(asked, TASK_FULLSCRAPE);
97 workqueue_canceltask(48);
98}
99
100/* Tasks are filed under a descriptor number, and the number is handed to the
101 next connection the moment this one closes. */
102
103static void case_cancel_takes_every_task_of_the_socket(void) {
104 ot_tasktype asked;
105
106 test_case("cancelling a socket leaves none of its tasks behind");
107 CHECK_INT(workqueue_pushtask(49, TASK_FULLSCRAPE_TPB_ASCII), 0);
108 CHECK_INT(workqueue_pushtask(49, TASK_FULLSCRAPE_TPB_BINARY), 0);
109 CHECK_INT(workqueue_pushtask(50, TASK_FULLSCRAPE), 0);
110 workqueue_canceltask(49);
111
112 asked = TASK_FULLSCRAPE;
113 CHECK(workqueue_poptask(&asked) != 0);
114 CHECK_INT(asked, TASK_FULLSCRAPE);
115 workqueue_canceltask(50);
116}
117
118static void case_result_names_the_connection_that_asked(void) {
119 ot_tasktype asked = TASK_STATS;
120 ot_taskid taskid;
121 struct iovec *iovector;
122 size_t iovec_entries;
123 int is_partial;
124 uint32_t asked_under, answered_under = ~0u;
125
126 CHECK_INT(fdstate_init(), 0);
127 asked_under = fdstate_open(51, NULL, 0);
128
129 test_case("a result comes back with the generation its task was pushed under");
130 CHECK_INT(workqueue_pushtask(51, TASK_STATS_PEERS), 0);
131 taskid = workqueue_poptask(&asked);
132 CHECK(taskid != 0);
133
134 /* The connection goes away without cancelling and the number is reused */
135 fdstate_close(51);
136 fdstate_open(51, NULL, 0);
137
138 CHECK_INT(workqueue_pushresult(taskid, 0, NULL), 0);
139 CHECK_INT(workqueue_popresult(&iovec_entries, &iovector, &is_partial, &answered_under), 51);
140 CHECK_INT(answered_under, asked_under);
141
142 test_case("which is no longer the one the descriptor carries");
143 CHECK(fdstate_generation(51) != answered_under);
144
145 fdstate_close(51);
146 fdstate_deinit();
147}
148
149void test_workqueue(void) {
150 case_task_goes_to_its_own_class();
151 case_flags_survive_the_queue();
152 case_classes_do_not_cross();
153 case_every_task_gets_its_own_id();
154 case_cancelled_task_is_not_handed_out();
155 case_cancel_takes_every_task_of_the_socket();
156 case_result_names_the_connection_that_asked();
157}
diff --git a/tests/test.c b/tests/test.c
new file mode 100644
index 0000000..33f77bd
--- /dev/null
+++ b/tests/test.c
@@ -0,0 +1,56 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdarg.h>
6#include <stdio.h>
7
8/* Opentracker */
9#include "test.h"
10
11unsigned long test_checks;
12unsigned long test_failures;
13
14static const char *current_module = "";
15static const char *current_case = "";
16
17void test_module(const char *name) {
18 current_module = name;
19 current_case = "";
20 printf("%s\n", name);
21}
22
23void test_case(const char *name) { current_case = name; }
24
25static void test_where(const char *file, int line) {
26 ++test_failures;
27 printf(" FAIL %s/%s (%s:%d)\n ", current_module, current_case, file, line);
28}
29
30void test_failf(const char *file, int line, const char *fmt, ...) {
31 va_list ap;
32 test_where(file, line);
33 va_start(ap, fmt);
34 vprintf(fmt, ap);
35 va_end(ap);
36 printf("\n");
37}
38
39void test_failmem(const char *file, int line, const char *what, const void *got, const void *want, size_t len) {
40 const unsigned char *g = got, *w = want;
41 size_t i;
42
43 test_where(file, line);
44 printf("%s: %zu bytes differ\n got ", what, len);
45 for (i = 0; i < len; ++i)
46 printf("%02x", g[i]);
47 printf("\n want ");
48 for (i = 0; i < len; ++i)
49 printf("%02x", w[i]);
50 printf("\n");
51}
52
53int test_summary(void) {
54 printf("\n%lu checks, %lu failures\n", test_checks, test_failures);
55 return test_failures != 0;
56}
diff --git a/tests/test.h b/tests/test.h
new file mode 100644
index 0000000..9b569c7
--- /dev/null
+++ b/tests/test.h
@@ -0,0 +1,96 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4#ifndef OT_TEST_H__
5#define OT_TEST_H__
6
7#include <stddef.h>
8#include <string.h>
9
10/* Minimal scaffolding for opentracker's unit tests. No external dependencies.
11
12 Tests are grouped into modules, one per source file under test. A module is
13 a list of small case functions, each pinning one behaviour. A failing CHECK
14 reports file, line and the offending values, then returns from the case it
15 is in, so a single run reports as many independent problems as it can.
16 Because the macros return, they may only be used in functions returning
17 void. */
18
19void test_module(const char *name);
20void test_case(const char *name);
21void test_failf(const char *file, int line, const char *fmt, ...);
22void test_failmem(const char *file, int line, const char *what, const void *got, const void *want, size_t len);
23int test_summary(void);
24
25extern unsigned long test_checks;
26extern unsigned long test_failures;
27
28#define CHECK(cond) \
29 do { \
30 ++test_checks; \
31 if (!(cond)) { \
32 test_failf(__FILE__, __LINE__, "expected %s", #cond); \
33 return; \
34 } \
35 } while (0)
36
37#define CHECK_INT(got, want) \
38 do { \
39 long long got_ = (long long)(got), want_ = (long long)(want); \
40 ++test_checks; \
41 if (got_ != want_) { \
42 test_failf(__FILE__, __LINE__, "%s: got %lld, want %lld", #got, got_, want_); \
43 return; \
44 } \
45 } while (0)
46
47#define CHECK_PTR(got, want) \
48 do { \
49 const void *got_ = (const void *)(got), *want_ = (const void *)(want); \
50 ++test_checks; \
51 if (got_ != want_) { \
52 test_failf(__FILE__, __LINE__, "%s: got %p, want %p", #got, got_, want_); \
53 return; \
54 } \
55 } while (0)
56
57#define CHECK_MEM(got, want, len) \
58 do { \
59 ++test_checks; \
60 if (memcmp((got), (want), (len))) { \
61 test_failmem(__FILE__, __LINE__, #got, (got), (want), (len)); \
62 return; \
63 } \
64 } while (0)
65
66#define CHECK_STR(got, want) \
67 do { \
68 const char *got_ = (got), *want_ = (want); \
69 ++test_checks; \
70 if (strcmp(got_, want_)) { \
71 test_failf(__FILE__, __LINE__, "%s: got \"%s\", want \"%s\"", #got, got_, want_); \
72 return; \
73 } \
74 } while (0)
75
76/* One entry point per module under test */
77void test_urlencoded(void);
78void test_iovec(void);
79void test_vector(void);
80void test_random(void);
81void test_hex(void);
82void test_accesslist(void);
83void test_scan(void);
84void test_buf(void);
85void test_ip(void);
86void test_socket(void);
87void test_mutex(void);
88void test_trackerlogic(void);
89void test_clean(void);
90void test_workqueue(void);
91void test_batch(void);
92void test_fdstate(void);
93void test_event(void);
94void test_fmt(void);
95
96#endif
diff --git a/tests/testsuite2.sh b/tests/testsuite2.sh
index c9a5a6a..da5181b 100644
--- a/tests/testsuite2.sh
+++ b/tests/testsuite2.sh
@@ -2,13 +2,21 @@
2 2
3while true; do 3while true; do
4 request_string="GET /announce?info_hash=012345678901234567\ 4 request_string="GET /announce?info_hash=012345678901234567\
5%$(printf %02X $(( $RANDOM & 0xff )) )\ 5$(printf %02X $(( $RANDOM & 0xff )) )\
6%$(printf %02X $(( $RANDOM & 0xff )) )\ 6&ip=$(( $RANDOM & 0xff )).17.13.15&port=$(( $RANDOM & 0xff )) HTTP/1.0"
7&ip=$(( $RANDOM & 0xff )).17.13.15&port=$(( $RANDOM & 0xff )) HTTP/1.0\n"
8 7
9 echo $request_string 8# echo $request_string
10 echo 9# echo
11 echo $request_string | nc 23.23.23.237 6969 >/dev/null 10 printf "%s\n\n" "$request_string" | nc 84.200.61.9 6969 | hexdump -C
12 echo 11
12 request_string="GET /announce?info_hash=012345678901234567\
13$(printf %02X $(( $RANDOM & 0xff )) )\
14&ip=2001:1608:6:27::$(( $RANDOM & 0xff ))&port=$(( $RANDOM & 0xff )) HTTP/1.0"
15 printf "%s\n\n" "$request_string" | nc 2001:1608:6:27::9 6969 | hexdump -C
16 printf "%s\n\n" "$request_string"
17
18 request_string="GET /scrape?info_hash=012345678901234567\
19$(printf %02X $(( $RANDOM & 0xff )) ) HTTP/1.0"
20 printf "%s\n\n" "$request_string" | nc 2001:1608:6:27::9 6969 | hexdump -C
13 21
14done 22done
diff --git a/tests/udp_load.c b/tests/udp_load.c
new file mode 100644
index 0000000..d86c157
--- /dev/null
+++ b/tests/udp_load.c
@@ -0,0 +1,202 @@
1/* A UDP load generator speaking the tracker's own protocol.
2
3 Each thread keeps a socket of its own, does the BEP 15 connect handshake
4 once and then announces in a loop, counting replies. Separate sockets
5 matter: the kernel spreads datagrams across a SO_REUSEPORT group by a hash
6 of the four tuple, so a generator sending everything from one source port
7 would pile every packet onto one of the tracker's workers and measure the
8 wrong thing.
9
10 cc -O2 -pthread -o udp_load tests/udp_load.c
11 ./udp_load 127.0.0.1 6969 4 5 10000 64
12
13 The last argument is how many announces each thread keeps in flight. With
14 one, a thread sends and waits, so the offered load is threads divided by
15 the round trip and the figure says more about scheduling than about the
16 tracker: measured here, a tracker answering 60k/s that way was using
17 three quarters of one core. Raising the window offers load without
18 needing a thread per outstanding request, which is what lets the tracker
19 be pushed to the point where it is actually the limit.
20
21 The last argument is how many distinct torrents to announce. It is what
22 keeps the figure honest: a fresh info hash every time measures how fast
23 the tracker can insert a million torrents into sorted vectors, which is
24 not what a tracker spends its life doing, and which punishes whichever
25 configuration is quickest because it reaches the expensive end of the run
26 soonest. Cycling a fixed set reaches a steady state where almost every
27 announce renews a peer that is already there. */
28
29#include <arpa/inet.h>
30#include <netinet/in.h>
31#include <pthread.h>
32#include <stdatomic.h>
33#include <stdint.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37#include <sys/socket.h>
38#include <sys/time.h>
39#include <time.h>
40#include <unistd.h>
41
42#define CONNECT_MAGIC 0x41727101980ULL
43
44static struct sockaddr_in g_tracker;
45static long g_torrents = 10000;
46static long g_window = 64;
47static _Atomic long long g_sent = 0;
48static _Atomic int g_running = 1;
49static _Atomic long long g_replies = 0;
50static _Atomic long long g_timeouts = 0;
51
52static double seconds(void) {
53 struct timespec now;
54 clock_gettime(CLOCK_MONOTONIC, &now);
55 return now.tv_sec + now.tv_nsec / 1e9;
56}
57
58static void put64(unsigned char *at, uint64_t value) {
59 int i;
60 for (i = 0; i < 8; ++i)
61 at[i] = (unsigned char)(value >> (56 - 8 * i));
62}
63static void put32(unsigned char *at, uint32_t value) {
64 at[0] = (unsigned char)(value >> 24);
65 at[1] = (unsigned char)(value >> 16);
66 at[2] = (unsigned char)(value >> 8);
67 at[3] = (unsigned char)value;
68}
69static uint64_t get64(const unsigned char *at) {
70 uint64_t value = 0;
71 int i;
72 for (i = 0; i < 8; ++i)
73 value = (value << 8) | at[i];
74 return value;
75}
76
77static void *loader(void *args) {
78 long index = (long)args;
79 unsigned char request[98], reply[1500];
80 uint64_t connection_id = 0;
81 int sock = socket(AF_INET, SOCK_DGRAM, 0);
82 struct timeval patience = {0, 50000}; /* 50 ms */
83 unsigned seed = (unsigned)index * 2654435761u + 1;
84
85 if (sock < 0)
86 return NULL;
87 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &patience, sizeof(patience));
88
89 /* connect handshake */
90 memset(request, 0, sizeof(request));
91 put64(request, CONNECT_MAGIC);
92 put32(request + 8, 0);
93 put32(request + 12, (uint32_t)index);
94 if (sendto(sock, request, 16, 0, (struct sockaddr *)&g_tracker, sizeof(g_tracker)) != 16) {
95 close(sock);
96 return NULL;
97 }
98 if (recvfrom(sock, reply, sizeof(reply), 0, NULL, NULL) < 16) {
99 fprintf(stderr, " thread %ld: no answer to connect\n", index);
100 close(sock);
101 return NULL;
102 }
103 connection_id = get64(reply + 8);
104
105 /* Keep g_window announces outstanding: send that many, then drain what has
106 come back, rather than waiting for each reply in turn */
107 while (atomic_load_explicit(&g_running, memory_order_relaxed)) {
108 ssize_t got;
109 int i;
110 long outstanding;
111
112 for (outstanding = 0; outstanding < g_window; ++outstanding) {
113 memset(request, 0, sizeof(request));
114 put64(request, connection_id);
115 put32(request + 8, 1); /* announce */
116 put32(request + 12, (uint32_t)index);
117 /* One of a fixed set, so that after the first pass almost every announce
118 renews a peer rather than creating a torrent. The index is hashed into
119 all twenty bytes so the buckets, which key off the first four, are
120 spread rather than walked in order. */
121 {
122 unsigned which = (unsigned)((seed = seed * 1103515245u + 12345u) >> 8) % (unsigned)g_torrents;
123 unsigned spread;
124 for (i = 0; i < 20; ++i) {
125 spread = which * 2654435761u + (unsigned)i * 40503u;
126 spread ^= spread >> 13;
127 request[16 + i] = (unsigned char)(spread >> 11);
128 }
129 }
130 for (i = 0; i < 20; ++i)
131 request[36 + i] = (unsigned char)('a' + (i % 26));
132 put64(request + 56, 0); /* downloaded */
133 put64(request + 64, 0); /* left: a seeder */
134 put64(request + 72, 0); /* uploaded */
135 put32(request + 80, 0); /* event */
136 put32(request + 84, 0); /* ip */
137 put32(request + 88, (uint32_t)index); /* key */
138 put32(request + 92, (uint32_t)-1); /* num_want */
139 /* A port of this thread's own, so each thread is a distinct peer and the
140 swarms hold more than one */
141 request[96] = (unsigned char)((6881 + index) >> 8);
142 request[97] = (unsigned char)((6881 + index) & 0xff);
143
144 if (sendto(sock, request, 98, 0, (struct sockaddr *)&g_tracker, sizeof(g_tracker)) != 98)
145 break;
146 atomic_fetch_add_explicit(&g_sent, 1, memory_order_relaxed);
147 }
148
149 for (outstanding = 0; outstanding < g_window; ++outstanding) {
150 got = recvfrom(sock, reply, sizeof(reply), 0, NULL, NULL);
151 if (got >= 20)
152 atomic_fetch_add_explicit(&g_replies, 1, memory_order_relaxed);
153 else {
154 atomic_fetch_add_explicit(&g_timeouts, 1, memory_order_relaxed);
155 break; /* nothing more is coming; go round and send again */
156 }
157 }
158 }
159
160 close(sock);
161 return NULL;
162}
163
164int main(int argc, char **argv) {
165 const char *host = argc > 1 ? argv[1] : "127.0.0.1";
166 int port = argc > 2 ? atoi(argv[2]) : 6969;
167 long threads = argc > 3 ? atol(argv[3]) : 16;
168 double run_for = argc > 4 ? atof(argv[4]) : 5.0;
169 long torrents = argc > 5 ? atol(argv[5]) : 10000;
170 long window = argc > 6 ? atol(argv[6]) : 64;
171 pthread_t *ids = calloc((size_t)threads, sizeof(pthread_t));
172 long i;
173 double started, elapsed;
174
175 g_torrents = torrents > 0 ? torrents : 1;
176 g_window = window > 0 ? window : 1;
177
178 memset(&g_tracker, 0, sizeof(g_tracker));
179 g_tracker.sin_family = AF_INET;
180 g_tracker.sin_port = htons((uint16_t)port);
181 if (inet_pton(AF_INET, host, &g_tracker.sin_addr) != 1) {
182 fprintf(stderr, "cannot parse address %s\n", host);
183 return 1;
184 }
185
186 for (i = 0; i < threads; ++i)
187 pthread_create(ids + i, NULL, loader, (void *)i);
188
189 started = seconds();
190 usleep((useconds_t)(run_for * 1e6));
191 atomic_store(&g_running, 0);
192 elapsed = seconds() - started;
193
194 for (i = 0; i < threads; ++i)
195 pthread_join(ids[i], NULL);
196
197 printf("%.0f replies/s (%.0f sent/s, %lld replies, %lld lost, %ld threads x %ld in flight, %.1f s)\n",
198 (double)atomic_load(&g_replies) / elapsed, (double)atomic_load(&g_sent) / elapsed,
199 (long long)atomic_load(&g_replies), (long long)atomic_load(&g_timeouts), threads, g_window, elapsed);
200 free(ids);
201 return 0;
202}
diff --git a/tests/udp_modes.c b/tests/udp_modes.c
new file mode 100644
index 0000000..654cfd8
--- /dev/null
+++ b/tests/udp_modes.c
@@ -0,0 +1,240 @@
1/* A receiver with the udp arrangements we are choosing between, so they can
2 be compared without any of them being built into the tracker first.
3
4 It echoes what it is sent, so tests/udp_load.c drives it unchanged. There
5 is no tracker work here on purpose: with nothing else happening, whatever
6 the kernel's receive path costs is the whole figure, which is the clearest
7 view of it. Pass a work time to dilute that back towards realism.
8
9 cc -O2 -pthread -o udp_modes tests/udp_modes.c
10 ./udp_modes 6969 4 shared 1
11 ./udp_modes 6969 4 shared 32
12 ./udp_modes 6969 4 per-thread 1
13 ./udp_modes 6969 4 per-thread 32
14
15 Arguments: port, threads, shared|per-thread, datagrams per syscall,
16 and optionally nanoseconds of pretend work per datagram. */
17
18#define _GNU_SOURCE /* struct mmsghdr on glibc */
19
20#include <errno.h>
21#include <netinet/in.h>
22#include <pthread.h>
23#include <signal.h>
24#include <stdatomic.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
28#include <sys/socket.h>
29#include <time.h>
30#include <unistd.h>
31
32#if defined(__linux__) || defined(__FreeBSD__)
33#define HAVE_MMSG 1
34#endif
35
36#define MAX_BATCH 256
37#define BUFFER_SIZE 2048
38
39static int g_port;
40static long g_threads;
41static long g_batch;
42static long g_work_ns;
43static int g_shared_socket = -1; /* -1 means one socket per thread */
44static _Atomic int g_running = 1;
45
46static void stop(int sig) {
47 (void)sig;
48 atomic_store(&g_running, 0);
49}
50
51/* Which option the platform offers for spreading datagrams over a group of
52 sockets bound to one address. They are not the same thing: FreeBSD's plain
53 SO_REUSEPORT permits the bind without spreading anything, and Darwin's
54 hands every datagram to whichever socket bound last. */
55static const char *share_the_port(int sock) {
56 int one = 1;
57
58 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
59#ifdef SO_REUSEPORT_LB
60 if (!setsockopt(sock, SOL_SOCKET, SO_REUSEPORT_LB, &one, sizeof(one)))
61 return "SO_REUSEPORT_LB";
62#endif
63#ifdef SO_REUSEPORT
64 if (!setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one)))
65 return "SO_REUSEPORT";
66#endif
67 return "neither";
68}
69
70static int bind_one(int share, const char **option) {
71 struct sockaddr_in address;
72 int sock = socket(AF_INET, SOCK_DGRAM, 0);
73
74 if (sock < 0)
75 return -1;
76 *option = share ? share_the_port(sock) : "exclusive";
77
78 memset(&address, 0, sizeof(address));
79 address.sin_family = AF_INET;
80 address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
81 address.sin_port = htons((uint16_t)g_port);
82 if (bind(sock, (struct sockaddr *)&address, sizeof(address)) < 0) {
83 close(sock);
84 return -1;
85 }
86 return sock;
87}
88
89static void pretend_to_work(void) {
90 struct timespec started, now;
91 long waited = 0;
92
93 if (!g_work_ns)
94 return;
95 clock_gettime(CLOCK_MONOTONIC, &started);
96 while (waited < g_work_ns) {
97 clock_gettime(CLOCK_MONOTONIC, &now);
98 waited = (now.tv_sec - started.tv_sec) * 1000000000L + (now.tv_nsec - started.tv_nsec);
99 }
100}
101
102static void one_at_a_time(int sock) {
103 char buffer[BUFFER_SIZE];
104 struct sockaddr_in from;
105 socklen_t length;
106 ssize_t got;
107
108 while (atomic_load_explicit(&g_running, memory_order_relaxed)) {
109 length = sizeof(from);
110 got = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&from, &length);
111 if (got < 0) {
112 if (errno == EINTR || errno == EAGAIN)
113 continue;
114 return;
115 }
116 pretend_to_work();
117 sendto(sock, buffer, (size_t)got, 0, (struct sockaddr *)&from, length);
118 }
119}
120
121#ifdef HAVE_MMSG
122static void in_batches(int sock) {
123 static _Thread_local char buffers[MAX_BATCH][BUFFER_SIZE];
124 static _Thread_local struct sockaddr_in froms[MAX_BATCH];
125 static _Thread_local struct iovec iovecs[MAX_BATCH];
126 static _Thread_local struct mmsghdr messages[MAX_BATCH];
127 int got, i;
128
129 while (atomic_load_explicit(&g_running, memory_order_relaxed)) {
130 for (i = 0; i < g_batch; ++i) {
131 iovecs[i].iov_base = buffers[i];
132 iovecs[i].iov_len = BUFFER_SIZE;
133 memset(messages + i, 0, sizeof(messages[i]));
134 messages[i].msg_hdr.msg_name = froms + i;
135 messages[i].msg_hdr.msg_namelen = sizeof(froms[i]);
136 messages[i].msg_hdr.msg_iov = iovecs + i;
137 messages[i].msg_hdr.msg_iovlen = 1;
138 }
139
140 /* WAITFORONE so a quiet receiver behaves like the unbatched one rather
141 than holding the first datagram until the batch fills */
142 got = recvmmsg(sock, messages, (unsigned)g_batch, MSG_WAITFORONE, NULL);
143 if (got < 0) {
144 if (errno == EINTR || errno == EAGAIN)
145 continue;
146 return;
147 }
148
149 for (i = 0; i < got; ++i) {
150 pretend_to_work();
151 iovecs[i].iov_len = messages[i].msg_len;
152 messages[i].msg_hdr.msg_namelen = sizeof(froms[i]);
153 }
154 sendmmsg(sock, messages, (unsigned)got, 0);
155 }
156}
157#endif
158
159static void *worker(void *args) {
160 const char *option = "";
161 int sock = g_shared_socket;
162
163 (void)args;
164 if (sock < 0) {
165 sock = bind_one(1, &option);
166 if (sock < 0) {
167 fprintf(stderr, " a worker could not bind: %s\n", strerror(errno));
168 return NULL;
169 }
170 }
171
172#ifdef HAVE_MMSG
173 if (g_batch > 1)
174 in_batches(sock);
175 else
176#endif
177 one_at_a_time(sock);
178
179 if (g_shared_socket < 0)
180 close(sock);
181 return NULL;
182}
183
184int main(int argc, char **argv) {
185 const char *how = argc > 3 ? argv[3] : "shared";
186 const char *option = "";
187 pthread_t *threads;
188 long i;
189
190 g_port = argc > 1 ? atoi(argv[1]) : 6969;
191 g_threads = argc > 2 ? atol(argv[2]) : 1;
192 g_batch = argc > 4 ? atol(argv[4]) : 1;
193 g_work_ns = argc > 5 ? atol(argv[5]) : 0;
194 if (g_batch < 1)
195 g_batch = 1;
196 if (g_batch > MAX_BATCH)
197 g_batch = MAX_BATCH;
198
199#ifndef HAVE_MMSG
200 if (g_batch > 1) {
201 fprintf(stderr, " no recvmmsg on this platform; batching unavailable\n");
202 return 2;
203 }
204#endif
205
206 signal(SIGINT, stop);
207 signal(SIGTERM, stop);
208
209 if (!strcmp(how, "shared")) {
210 g_shared_socket = bind_one(0, &option);
211 if (g_shared_socket < 0) {
212 fprintf(stderr, " bind failed: %s\n", strerror(errno));
213 return 1;
214 }
215 } else {
216 /* Probe once so the mode line can say what the platform gave us */
217 int probe = bind_one(1, &option);
218 if (probe < 0) {
219 fprintf(stderr, " bind failed: %s\n", strerror(errno));
220 return 1;
221 }
222 close(probe);
223 }
224
225 printf(" port %d, %ld threads, %s socket%s (%s), %ld per syscall, %ld ns work\n",
226 g_port, g_threads, strcmp(how, "shared") ? "one per thread" : "one shared",
227 strcmp(how, "shared") ? "s" : "", option, g_batch, g_work_ns);
228 fflush(stdout);
229
230 threads = calloc((size_t)g_threads, sizeof(pthread_t));
231 for (i = 0; i < g_threads; ++i)
232 pthread_create(threads + i, NULL, worker, NULL);
233 for (i = 0; i < g_threads; ++i)
234 pthread_join(threads[i], NULL);
235
236 if (g_shared_socket >= 0)
237 close(g_shared_socket);
238 free(threads);
239 return 0;
240}
diff --git a/tests/udp_modes.py b/tests/udp_modes.py
new file mode 100644
index 0000000..19cd264
--- /dev/null
+++ b/tests/udp_modes.py
@@ -0,0 +1,139 @@
1"""The four udp arrangements, side by side.
2
3 cc -O2 -pthread -o /tmp/udp_modes tests/udp_modes.c
4 cc -O2 -pthread -o /tmp/udp_load tests/udp_load.c
5 python3 tests/udp_modes.py
6
7Two questions at once. Down the table: does a shared socket stop scaling as
8threads are added? Across it: does taking several datagrams per syscall make
9that better, or only cheaper?
10
11The receiver does no tracker work by default, so the figure is the kernel's
12receive path and nothing else. WORK_NS=1500 dilutes it back towards what the
13tracker actually costs per announce.
14
15The number reported is cpu microseconds the receiver spent per datagram
16answered, not throughput. Throughput here says more about the load generator
17than the receiver, because both run on the same machine and an echo costs so
18little that the generator runs out of cores first. Cpu per datagram does not
19care: it is what the receive path costs, whoever is the bottleneck.
20"""
21import os
22import signal
23import socket
24import subprocess
25import sys
26import time
27
28MODES = os.environ.get("MODES", "shared per-thread").split()
29BATCHES = [int(n) for n in os.environ.get("BATCHES", "1 8 32").split()]
30THREAD_COUNTS = [int(n) for n in os.environ.get("THREADS", "1 2 4 8").split()]
31LOAD_THREADS = int(os.environ.get("LOAD_THREADS", "4"))
32WINDOW = int(os.environ.get("WINDOW", "32"))
33SECONDS = float(os.environ.get("SECONDS", "3"))
34REPEATS = int(os.environ.get("REPEATS", "2"))
35WORK_NS = int(os.environ.get("WORK_NS", "0"))
36RECEIVER = os.environ.get("UDP_MODES", "/tmp/udp_modes")
37LOADER = os.environ.get("UDP_LOAD", "/tmp/udp_load")
38PORT_BASE = int(os.environ.get("PORT_BASE", "20100"))
39
40
41def cpu_seconds(pid):
42 try:
43 out = subprocess.run(["ps", "-o", "time=", "-p", str(pid)], capture_output=True, text=True).stdout.strip()
44 except OSError:
45 return None
46 if not out:
47 return None
48 total = 0.0
49 for part in out.replace("-", ":").split(":"):
50 total = total * 60 + float(part)
51 return total
52
53
54def one_run(port, threads, mode, batch):
55 receiver = subprocess.Popen(
56 [RECEIVER, str(port), str(threads), mode, str(batch), str(WORK_NS)],
57 stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,
58 )
59 for _ in range(200):
60 if receiver.poll() is not None:
61 return None, None
62 probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
63 probe.settimeout(0.1)
64 try:
65 probe.sendto(b"\x00" * 16, ("127.0.0.1", port))
66 probe.recv(64)
67 probe.close()
68 break
69 except OSError:
70 probe.close()
71 time.sleep(0.02)
72 else:
73 receiver.send_signal(signal.SIGINT)
74 receiver.wait()
75 return None, None
76
77 try:
78 subprocess.run([LOADER, "127.0.0.1", str(port), str(LOAD_THREADS), "1", "10000", str(WINDOW)],
79 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
80 spent, wall = cpu_seconds(receiver.pid), time.time()
81 out = subprocess.run(
82 [LOADER, "127.0.0.1", str(port), str(LOAD_THREADS), str(SECONDS), "10000", str(WINDOW)],
83 capture_output=True, text=True,
84 ).stdout.strip()
85 used = cpu_seconds(receiver.pid)
86 finally:
87 receiver.send_signal(signal.SIGINT)
88 try:
89 receiver.wait(timeout=5)
90 except subprocess.TimeoutExpired:
91 receiver.kill()
92 receiver.wait()
93
94 head = out.split()
95 if not head or not head[0].replace(".", "").isdigit():
96 return None, None
97 cores = (used - spent) / max(time.time() - wall, 1e-9) if (used is not None and spent is not None) else None
98 return float(head[0]), cores
99
100
101def main():
102 for binary in (RECEIVER, LOADER):
103 if not os.path.exists(binary):
104 raise SystemExit("missing %s; see the comment at the top of tests/udp_modes.c" % binary)
105
106 print(" %d load threads x %d in flight, %.0f s x %d runs, %d ns work per datagram"
107 % (LOAD_THREADS, WINDOW, SECONDS, REPEATS, WORK_NS))
108 print(" cpu microseconds per datagram, and the throughput it was measured at")
109 header = " %-14s %-8s" % ("sockets", "threads")
110 for batch in BATCHES:
111 header += "%20s" % ("%d per syscall" % batch)
112 print(header)
113
114 port = PORT_BASE
115 for mode in MODES:
116 for threads in THREAD_COUNTS:
117 row = " %-14s %-8d" % (mode, threads)
118 for batch in BATCHES:
119 results = []
120 for _ in range(REPEATS):
121 port += 1
122 rate, cores = one_run(port, threads, mode, batch)
123 if rate:
124 results.append((rate, cores))
125 if not results:
126 row += "%18s" % "-"
127 continue
128 results.sort()
129 rate, cores = results[len(results) // 2]
130 if cores:
131 row += "%9.2f us %6.0fk/s" % (cores * 1e6 / rate, rate / 1000.0)
132 else:
133 row += "%20s" % ("%.0fk/s" % (rate / 1000.0))
134 print(row)
135 sys.stdout.flush()
136
137
138if __name__ == "__main__":
139 main()
diff --git a/tests/udp_scaling.py b/tests/udp_scaling.py
new file mode 100644
index 0000000..7691fcb
--- /dev/null
+++ b/tests/udp_scaling.py
@@ -0,0 +1,159 @@
1"""Does listen.udp.workers help or hurt, on this platform, with this tracker?
2
3Starts a tracker once per worker count and drives it with tests/udp_load.c,
4which speaks the real protocol, so what comes out is the tracker's own
5throughput rather than an echo server's.
6
7 cc -O2 -pthread -o /tmp/udp_load tests/udp_load.c
8 make opentracker
9 python3 tests/udp_scaling.py
10
11Worker count 0 means no dedicated workers: udp is served from the main event
12loop, which is what a default build does.
13
14LOAD_THREADS and WINDOW decide how much load is offered. Both matter. Too
15little and the tracker idles while the figure measures round trips; too much
16and the kernel drops datagrams, every lost reply costs the generator a
17timeout, and the figure collapses.
18
19Three columns say which side the number came from. "cores" is the tracker's
20cpu, "load" the generator's. Whichever is near its machine's core count is
21the one being measured. "lost" counts datagrams that went unanswered: once
22it leaves zero the throughput figure is timeouts, not service, and the run
23needs a smaller WINDOW.
24"""
25import os
26import resource
27import signal
28import socket
29import subprocess
30import sys
31import tempfile
32import time
33
34TRACKER = os.environ.get("OPENTRACKER", "./opentracker")
35LOADER = os.environ.get("UDP_LOAD", "/tmp/udp_load")
36WORKER_COUNTS = [int(n) for n in os.environ.get("WORKERS", "0 1 2 4 8").split()]
37LOAD_THREADS = int(os.environ.get("LOAD_THREADS", "4"))
38SECONDS = float(os.environ.get("SECONDS", "5"))
39TORRENTS = int(os.environ.get("TORRENTS", "10000"))
40WINDOW = int(os.environ.get("WINDOW", "32"))
41REPEATS = int(os.environ.get("REPEATS", "3"))
42PORT_BASE = int(os.environ.get("PORT_BASE", "19960"))
43
44
45def start(port, workers):
46 directory = tempfile.mkdtemp(prefix="ot-udpscale-")
47 config = "listen.tcp 127.0.0.1:%d\nlisten.udp 127.0.0.1:%d\n" % (port, port)
48 if workers:
49 config += "listen.udp.workers %d\n" % workers
50 with open(os.path.join(directory, "conf"), "w") as handle:
51 handle.write(config)
52 log = open(os.path.join(directory, "log"), "w+b")
53 tracker = subprocess.Popen([TRACKER, "-f", os.path.join(directory, "conf")], stdout=log, stderr=log)
54 for _ in range(300):
55 if tracker.poll() is not None:
56 log.seek(0)
57 raise SystemExit("tracker exited at once on port %d with %d workers:\n%s"
58 % (port, workers, log.read().decode("utf-8", "replace")))
59 try:
60 socket.create_connection(("127.0.0.1", port), timeout=0.2).close()
61 return tracker, log
62 except OSError:
63 time.sleep(0.02)
64 tracker.kill()
65 raise SystemExit("tracker never listened on %d" % port)
66
67
68def cpu_seconds(pid):
69 """Cumulative cpu time of a process, the one spelling ps has everywhere."""
70 try:
71 out = subprocess.run(["ps", "-o", "time=", "-p", str(pid)], capture_output=True, text=True).stdout.strip()
72 except OSError:
73 return None
74 if not out:
75 return None
76 total, parts = 0.0, out.replace("-", ":").split(":")
77 for part in parts:
78 total = total * 60 + float(part)
79 return total
80
81
82def reaped_cpu_seconds():
83 """Cpu of every child already waited for. The generator is the only one
84 that starts and finishes inside a measured run."""
85 spent = resource.getrusage(resource.RUSAGE_CHILDREN)
86 return spent.ru_utime + spent.ru_stime
87
88
89def stop(tracker):
90 tracker.send_signal(signal.SIGINT)
91 try:
92 tracker.wait(timeout=10)
93 except subprocess.TimeoutExpired:
94 tracker.kill()
95 tracker.wait()
96
97
98def parse(line):
99 """replies/s and the count of announces that were never answered"""
100 words = line.split()
101 if not words or not words[0].replace(".", "").isdigit():
102 return None, None
103 lost = 0
104 if "lost," in words:
105 lost = int(words[words.index("lost,") - 1])
106 return float(words[0]), lost
107
108
109def main():
110 if not os.path.exists(LOADER):
111 raise SystemExit("build the generator first: cc -O2 -pthread -o %s tests/udp_load.c" % LOADER)
112
113 print(" tracker %s, %d load threads x %d in flight, %d torrents, %.0f s x %d runs"
114 % (TRACKER, LOAD_THREADS, WINDOW, TORRENTS, SECONDS, REPEATS))
115 print(" %-8s %12s %7s %7s %7s %10s %s"
116 % ("workers", "median/s", "spread", "cores", "load", "lost", "vs 0 workers"))
117 baseline = None
118 for index, workers in enumerate(WORKER_COUNTS):
119 results = []
120 for repeat in range(REPEATS):
121 port = PORT_BASE + index * 16 + repeat
122 tracker, log = start(port, workers)
123 try:
124 # Warm up until the torrent set exists and the peers are in
125 # place, so the measured run is renewals rather than insertions
126 subprocess.run([LOADER, "127.0.0.1", str(port), str(LOAD_THREADS), "2", str(TORRENTS), str(WINDOW)],
127 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
128 spent, offered, wall = cpu_seconds(tracker.pid), reaped_cpu_seconds(), time.time()
129 result = subprocess.run(
130 [LOADER, "127.0.0.1", str(port), str(LOAD_THREADS), str(SECONDS), str(TORRENTS), str(WINDOW)],
131 capture_output=True, text=True,
132 )
133 used, drove, elapsed = cpu_seconds(tracker.pid), reaped_cpu_seconds(), max(time.time() - wall, 1e-9)
134 finally:
135 stop(tracker)
136 log.close()
137 rate, lost = parse(result.stdout.strip())
138 if rate is None:
139 continue
140 cores = (used - spent) / elapsed if (used is not None and spent is not None) else None
141 results.append((rate, cores, (drove - offered) / elapsed, lost))
142
143 if not results:
144 print(" %-8s no result" % workers)
145 continue
146 results.sort()
147 rate, cores, load, lost = results[len(results) // 2]
148 if baseline is None:
149 baseline = rate
150 # A spread wider than the differences between rows means the rows are
151 # not telling you anything
152 spread = 100.0 * (results[-1][0] - results[0][0]) / rate
153 print(" %-8s %12.0f %6.0f%% %7s %7.2f %10d %.2fx"
154 % (workers, rate, spread, ("%.2f" % cores) if cores else "?", load, lost, rate / baseline))
155 sys.stdout.flush()
156
157
158if __name__ == "__main__":
159 main()
diff --git a/tests/udp_wake_probe.c b/tests/udp_wake_probe.c
new file mode 100644
index 0000000..e948c34
--- /dev/null
+++ b/tests/udp_wake_probe.c
@@ -0,0 +1,121 @@
1/* Four ways to get a thread out of a blocking recvfrom, tested rather than
2 assumed: close the socket, shut it down, give it a receive timeout, or
3 send it a signal.
4
5 This decides how udp workers are stopped. The sockets of a SO_REUSEPORT
6 group all share one address, so a worker cannot be singled out by sending
7 it a datagram, and the two mechanisms differ in what they cost while the
8 tracker is running: a receive timeout wakes every worker on every tick
9 forever, a signal and a shutdown cost nothing until the one moment they
10 are used.
11
12 cc -O2 -pthread -o /tmp/wake tests/udp_wake_probe.c && /tmp/wake
13
14 On Linux 6.1: close does not wake it, the other three do. */
15#include <errno.h>
16#include <netinet/in.h>
17#include <pthread.h>
18#include <stdatomic.h>
19#include <stdio.h>
20#include <string.h>
21#include <sys/socket.h>
22#include <signal.h>
23#include <sys/time.h>
24#include <unistd.h>
25
26#define WAKE_SIGNAL SIGUSR1
27
28static _Atomic int returned;
29static _Atomic int saved_errno;
30static int sock;
31
32static void *reader(void *args) {
33 char buffer[64];
34 (void)args;
35 if (recvfrom(sock, buffer, sizeof(buffer), 0, NULL, NULL) < 0)
36 atomic_store(&saved_errno, errno);
37 atomic_store(&returned, 1);
38 return NULL;
39}
40
41/* A handler that does nothing is all it takes: the point is the return from
42 recvfrom with EINTR, not anything the handler does. SA_RESTART must stay
43 off or the kernel resumes the call instead of reporting it. */
44static void noop(int s) { (void)s; }
45
46static int bind_udp(int timeout_ms) {
47 struct sockaddr_in address;
48 int s = socket(AF_INET, SOCK_DGRAM, 0);
49
50 memset(&address, 0, sizeof(address));
51 address.sin_family = AF_INET;
52 address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
53 address.sin_port = 0;
54 bind(s, (struct sockaddr *)&address, sizeof(address));
55
56 if (timeout_ms) {
57 struct timeval how_long;
58 how_long.tv_sec = timeout_ms / 1000;
59 how_long.tv_usec = (timeout_ms % 1000) * 1000;
60 setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &how_long, sizeof(how_long));
61 }
62 return s;
63}
64
65static void try_it(const char *name, int timeout_ms, int do_close, int do_shutdown, int do_signal) {
66 pthread_t thread;
67 int waited;
68
69 atomic_store(&returned, 0);
70 atomic_store(&saved_errno, 0);
71 sock = bind_udp(timeout_ms);
72 pthread_create(&thread, NULL, reader, NULL);
73 usleep(300000); /* let it reach recvfrom */
74
75 if (do_shutdown)
76 shutdown(sock, SHUT_RD);
77 if (do_signal)
78 pthread_kill(thread, WAKE_SIGNAL);
79 if (do_close)
80 close(sock);
81
82 for (waited = 0; waited < 2000 && !atomic_load(&returned); ++waited)
83 usleep(1000);
84
85 if (atomic_load(&returned)) {
86 printf(" %-24s returned after %4d ms, errno %s\n", name, waited,
87 atomic_load(&saved_errno) ? strerror(atomic_load(&saved_errno)) : "none");
88 pthread_join(thread, NULL);
89 } else {
90 printf(" %-24s STILL BLOCKED after 2000 ms\n", name);
91 /* unblock it so the probe can finish */
92 struct sockaddr_in to;
93 socklen_t length = sizeof(to);
94 int poke = socket(AF_INET, SOCK_DGRAM, 0);
95 if (!getsockname(sock, (struct sockaddr *)&to, &length))
96 sendto(poke, "x", 1, 0, (struct sockaddr *)&to, length);
97 close(poke);
98 usleep(200000);
99 if (atomic_load(&returned))
100 pthread_join(thread, NULL);
101 else
102 pthread_detach(thread);
103 }
104 if (!do_close)
105 close(sock);
106}
107
108int main(void) {
109 struct sigaction sa;
110
111 memset(&sa, 0, sizeof(sa));
112 sa.sa_handler = noop;
113 sa.sa_flags = 0;
114 sigaction(WAKE_SIGNAL, &sa, NULL);
115
116 try_it("close() the socket", 0, 1, 0, 0);
117 try_it("shutdown(SHUT_RD)", 0, 0, 1, 0);
118 try_it("SO_RCVTIMEO 500 ms", 500, 0, 0, 0);
119 try_it("pthread_kill(SIGUSR1)", 0, 0, 0, 1);
120 return 0;
121}