diff options
Diffstat (limited to 'tests/integration')
| -rw-r--r-- | tests/integration/.gitignore | 2 | ||||
| -rw-r--r-- | tests/integration/harness.py | 366 | ||||
| -rw-r--r-- | tests/integration/test_accesslist.py | 128 | ||||
| -rw-r--r-- | tests/integration/test_announce.py | 144 | ||||
| -rw-r--r-- | tests/integration/test_concurrency.py | 209 | ||||
| -rw-r--r-- | tests/integration/test_config.py | 72 | ||||
| -rw-r--r-- | tests/integration/test_dualstack.py | 89 | ||||
| -rw-r--r-- | tests/integration/test_dynamic_accesslist.py | 68 | ||||
| -rw-r--r-- | tests/integration/test_expiry.py | 44 | ||||
| -rw-r--r-- | tests/integration/test_fullscrape.py | 148 | ||||
| -rw-r--r-- | tests/integration/test_keepalive.py | 146 | ||||
| -rw-r--r-- | tests/integration/test_livesync.py | 240 | ||||
| -rw-r--r-- | tests/integration/test_shutdown.py | 58 | ||||
| -rw-r--r-- | tests/integration/test_statefile.py | 97 | ||||
| -rw-r--r-- | tests/integration/test_stats.py | 146 | ||||
| -rw-r--r-- | tests/integration/test_tcpworkers.py | 67 | ||||
| -rw-r--r-- | tests/integration/test_udp.py | 218 | ||||
| -rw-r--r-- | tests/integration/test_version.py | 36 |
18 files changed, 2278 insertions, 0 deletions
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 | |||
| 3 | Everything here drives the binary rather than the code, so these tests cover | ||
| 4 | what the unit suite cannot reach: the event loop, the HTTP parser and the | ||
| 5 | torrent store working together. Run against a sanitizer build and the tracker | ||
| 6 | reports its own memory errors, which the teardown turns into test failures. | ||
| 7 | """ | ||
| 8 | |||
| 9 | import os | ||
| 10 | import shutil | ||
| 11 | import signal | ||
| 12 | import socket | ||
| 13 | import struct | ||
| 14 | import subprocess | ||
| 15 | import sys | ||
| 16 | import tempfile | ||
| 17 | import time | ||
| 18 | import unittest | ||
| 19 | import urllib.error | ||
| 20 | import urllib.parse | ||
| 21 | import urllib.request | ||
| 22 | |||
| 23 | # groupip_1 in src/ot_livesync.c | ||
| 24 | LIVESYNC_GROUP = "224.0.23.5" | ||
| 25 | |||
| 26 | TRACKER = os.environ.get("OPENTRACKER", os.path.join(os.path.dirname(__file__), "..", "..", "opentracker.debug")) | ||
| 27 | |||
| 28 | |||
| 29 | def 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 | |||
| 55 | def 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 | |||
| 77 | class 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 | |||
| 277 | class 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 | |||
| 344 | class 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 | |||
| 3 | A blacklisted info hash must be refused at both the announce and the scrape | ||
| 4 | entry, and the file parser has to cope with the shapes an operator actually | ||
| 5 | produces: an empty file, and a last line with no newline after it. | ||
| 6 | """ | ||
| 7 | |||
| 8 | import os | ||
| 9 | import struct | ||
| 10 | import time | ||
| 11 | import unittest | ||
| 12 | |||
| 13 | from harness import Tracker, TrackerTestCase | ||
| 14 | |||
| 15 | BLOCKED = b"\xb1" * 20 | ||
| 16 | ALLOWED = b"\xa1" * 20 | ||
| 17 | |||
| 18 | |||
| 19 | def listing(*hashes): | ||
| 20 | return b"".join(h.hex().upper().encode() + b"\n" for h in hashes) | ||
| 21 | |||
| 22 | |||
| 23 | class 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 | |||
| 71 | class 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 | |||
| 86 | class 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 | |||
| 95 | class 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 | |||
| 105 | class 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 | |||
| 127 | if __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 | |||
| 3 | import os | ||
| 4 | import socket | ||
| 5 | import sys | ||
| 6 | import unittest | ||
| 7 | |||
| 8 | sys.path.insert(0, os.path.dirname(__file__)) | ||
| 9 | from harness import TrackerTestCase | ||
| 10 | |||
| 11 | |||
| 12 | def 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 | |||
| 23 | class 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 | |||
| 98 | class 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 | |||
| 143 | if __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 | |||
| 3 | The rest of the suite talks to the tracker one request at a time, which | ||
| 4 | leaves the worker threads and the bucket locks almost untouched. These reach | ||
| 5 | them. | ||
| 6 | |||
| 7 | What they assert is weak on purpose. A lost update needs two threads inside | ||
| 8 | the same few instructions, which is rare enough that these tests pass | ||
| 9 | against code that has the race: measured, eight runs in a row. Their worth | ||
| 10 | is that they make the racing code run at all, so that "make check-tsan" | ||
| 11 | has something to report. Reaching the code and judging it are two jobs, and | ||
| 12 | these only do the first. | ||
| 13 | """ | ||
| 14 | |||
| 15 | import struct | ||
| 16 | import threading | ||
| 17 | import unittest | ||
| 18 | |||
| 19 | from harness import TrackerTestCase, bdecode | ||
| 20 | |||
| 21 | THREADS = 8 | ||
| 22 | PER_THREAD = 40 | ||
| 23 | |||
| 24 | |||
| 25 | def 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 | |||
| 42 | class 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 | |||
| 86 | class 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 | |||
| 117 | class 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 | |||
| 164 | class 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 | |||
| 208 | if __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 | |||
| 3 | An unrecognised key only warns, so coming up proves nothing on its own and a | ||
| 4 | test that cares has to look at what the tracker said. A key that is | ||
| 5 | recognised but cannot be parsed is another matter, and for the listen | ||
| 6 | statements it stops the tracker. | ||
| 7 | """ | ||
| 8 | |||
| 9 | import unittest | ||
| 10 | |||
| 11 | from harness import Tracker, TrackerTestCase, free_port | ||
| 12 | |||
| 13 | |||
| 14 | class 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 | |||
| 22 | class 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 | |||
| 35 | class 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 | |||
| 54 | class 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 | |||
| 63 | class 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 | |||
| 3 | These need WANT_IP_FROM_QUERY_STRING so a peer's address can be dictated | ||
| 4 | rather than being whatever loopback the test happened to come from. | ||
| 5 | """ | ||
| 6 | |||
| 7 | import os | ||
| 8 | import socket | ||
| 9 | import sys | ||
| 10 | import unittest | ||
| 11 | |||
| 12 | sys.path.insert(0, os.path.dirname(__file__)) | ||
| 13 | from harness import TrackerTestCase | ||
| 14 | |||
| 15 | |||
| 16 | def 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 | |||
| 25 | class 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 | |||
| 88 | if __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 | |||
| 3 | The two FIFOs are read by threads of their own, which is also what makes | ||
| 4 | this the test that drives those threads through a shutdown. | ||
| 5 | """ | ||
| 6 | |||
| 7 | import os | ||
| 8 | import time | ||
| 9 | import unittest | ||
| 10 | |||
| 11 | from harness import TrackerTestCase | ||
| 12 | |||
| 13 | BLOCKED = bytes(range(1, 21)) | ||
| 14 | |||
| 15 | |||
| 16 | def as_hex(info_hash): | ||
| 17 | return "".join("%02x" % b for b in info_hash) | ||
| 18 | |||
| 19 | |||
| 20 | class 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 | |||
| 3 | A plain request is answered and the connection closed by http_close, not by | ||
| 4 | the sweep. If that path left the descriptor's slot behind, the sweep would | ||
| 5 | walk into it once the client timeout had passed and free a cookie that is | ||
| 6 | already gone; the sanitizer build reports that and teardown turns it into a | ||
| 7 | failure. | ||
| 8 | |||
| 9 | Both halves share one tracker and one wait, because the wait is the whole | ||
| 10 | cost of the test. | ||
| 11 | |||
| 12 | The two numbers below mirror OT_CLIENT_TIMEOUT and | ||
| 13 | OT_CLIENT_TIMEOUT_CHECKINTERVAL in FEATURES_integration. | ||
| 14 | """ | ||
| 15 | |||
| 16 | import socket | ||
| 17 | import time | ||
| 18 | import unittest | ||
| 19 | |||
| 20 | from harness import TrackerTestCase | ||
| 21 | |||
| 22 | CLIENT_TIMEOUT = 5 | ||
| 23 | CHECK_INTERVAL = 1 | ||
| 24 | |||
| 25 | |||
| 26 | class 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 | |||
| 3 | Each format is a separate writer, and they differ in more than cosmetics: | ||
| 4 | one is binary, one is bencoded, three are line based and one dumps the | ||
| 5 | tracker's own state for a restart. A worker thread produces them in chunks, | ||
| 6 | so these also exercise the chunked transfer the ordinary replies never take. | ||
| 7 | """ | ||
| 8 | |||
| 9 | import gzip | ||
| 10 | import struct | ||
| 11 | import time | ||
| 12 | import unittest | ||
| 13 | |||
| 14 | from harness import TrackerTestCase, bdecode | ||
| 15 | |||
| 16 | HEX = b"0123456789ABCDEF" | ||
| 17 | |||
| 18 | |||
| 19 | class 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 | |||
| 105 | class 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 | |||
| 115 | if __name__ == "__main__": | ||
| 116 | unittest.main() | ||
| 117 | |||
| 118 | |||
| 119 | class 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 | |||
| 3 | The reply path has two shapes. A small answer goes out in one write and the | ||
| 4 | connection is done with immediately. A large one is queued and finishes on a | ||
| 5 | later pass through the event loop, by which time the workstruct that served | ||
| 6 | the request has moved on, so whether to keep the connection has to be | ||
| 7 | remembered on the connection itself. | ||
| 8 | """ | ||
| 9 | |||
| 10 | import time | ||
| 11 | import unittest | ||
| 12 | import urllib.parse | ||
| 13 | |||
| 14 | from harness import TrackerTestCase, bdecode | ||
| 15 | |||
| 16 | |||
| 17 | class 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 | |||
| 145 | if __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 | |||
| 3 | Live sync sits behind WANT_SYNC_LIVE, so these only run against a binary | ||
| 4 | built with it: make check-livesync. Against any other build they skip, which | ||
| 5 | is what the feature list in -v is for. | ||
| 6 | """ | ||
| 7 | |||
| 8 | import socket | ||
| 9 | import struct | ||
| 10 | import subprocess | ||
| 11 | import unittest | ||
| 12 | |||
| 13 | from harness import TRACKER, Tracker, TrackerTestCase | ||
| 14 | |||
| 15 | # enum { OT_SYNC_PEER4, OT_SYNC_PEER6 } in src/ot_livesync.c | ||
| 16 | SYNC_PEER4 = 0 | ||
| 17 | SYNC_PEER6 = 1 | ||
| 18 | |||
| 19 | # src/trackerlogic.h | ||
| 20 | FLAG_SEEDING = 0x80 | ||
| 21 | FLAG_COMPLETED = 0x40 | ||
| 22 | FLAG_STOPPED = 0x20 | ||
| 23 | |||
| 24 | |||
| 25 | def has_livesync(): | ||
| 26 | done = subprocess.run([TRACKER, "-v"], capture_output=True, timeout=30) | ||
| 27 | return b"WANT_SYNC_LIVE" in done.stderr | ||
| 28 | |||
| 29 | |||
| 30 | def 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 | |||
| 36 | def peer6(address, port, flags): | ||
| 37 | return socket.inet_pton(socket.AF_INET6, address) + struct.pack("!H", port) + bytes([flags, 0]) | ||
| 38 | |||
| 39 | |||
| 40 | def 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") | ||
| 46 | class 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") | ||
| 136 | class 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") | ||
| 149 | class 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 | ||
| 183 | OWN_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. | ||
| 190 | UNJOINED_GROUP = "239.192.0.99" | ||
| 191 | |||
| 192 | |||
| 193 | @unittest.skipUnless(has_livesync(), "this build has no WANT_SYNC_LIVE") | ||
| 194 | class 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") | ||
| 214 | class 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 | |||
| 3 | The rest of the suite stops a tracker too, so a thread left behind already | ||
| 4 | shows up in teardown as the complaint that the tracker had to be killed. | ||
| 5 | These ask for the arrangements that park a thread in a blocking read in the | ||
| 6 | first place, and they time the exit, because a reader woken only by its own | ||
| 7 | receive timeout passes a correctness check while taking a second over it. | ||
| 8 | """ | ||
| 9 | |||
| 10 | import time | ||
| 11 | import unittest | ||
| 12 | |||
| 13 | from 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 | ||
| 18 | PATIENCE = 3.0 | ||
| 19 | |||
| 20 | |||
| 21 | def 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 | |||
| 37 | class 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 | |||
| 48 | class 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 | |||
| 3 | The second column is the minute a torrent was last touched, by the wall | ||
| 4 | clock, which is what the file has recorded for years and the only clock two | ||
| 5 | runs of the tracker agree on. | ||
| 6 | """ | ||
| 7 | |||
| 8 | import os | ||
| 9 | import time | ||
| 10 | import unittest | ||
| 11 | |||
| 12 | from harness import Tracker, TrackerTestCase | ||
| 13 | |||
| 14 | |||
| 15 | class 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 | |||
| 57 | class 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 | |||
| 96 | if __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 | |||
| 3 | Each mode is its own writer into a fixed buffer, so these pin the shape of | ||
| 4 | every one of them and, where the number means something, that it moves when | ||
| 5 | the thing it counts happens. | ||
| 6 | """ | ||
| 7 | |||
| 8 | import re | ||
| 9 | import unittest | ||
| 10 | import urllib.error | ||
| 11 | import xml.etree.ElementTree | ||
| 12 | |||
| 13 | from 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. | ||
| 18 | MRTG_MODES = ["peer", "conn", "scrp", "udp4", "tcp4", "torr", "fscr", "completed", "syncs"] | ||
| 19 | TEXT_MODES = ["herr", "top10", "top100", "renew"] | ||
| 20 | |||
| 21 | |||
| 22 | class 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 | |||
| 74 | class 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 | |||
| 124 | class 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 | |||
| 145 | if __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 | |||
| 3 | With workers configured, a connection is accepted and answered on a worker's | ||
| 4 | own stack. Anything it cannot finish there is copied to the heap and handed | ||
| 5 | to the event loop, which is the one place where a worker and the main thread | ||
| 6 | touch the same structures, so these drive all three outcomes: answered | ||
| 7 | inline, held open, and parked waiting for another thread entirely. | ||
| 8 | """ | ||
| 9 | |||
| 10 | import threading | ||
| 11 | import unittest | ||
| 12 | import urllib.parse | ||
| 13 | |||
| 14 | from harness import TrackerTestCase, bdecode | ||
| 15 | |||
| 16 | WORKERS = 4 | ||
| 17 | |||
| 18 | |||
| 19 | class 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 | |||
| 3 | The HTTP tests cover the torrent store; these cover the packet handling in | ||
| 4 | front of it, which has its own framing, its own connection id and its own | ||
| 5 | rules about what to answer and what to ignore. | ||
| 6 | """ | ||
| 7 | |||
| 8 | import socket | ||
| 9 | import struct | ||
| 10 | import unittest | ||
| 11 | |||
| 12 | from harness import Tracker, TrackerTestCase | ||
| 13 | |||
| 14 | MAGIC = 0x41727101980 | ||
| 15 | |||
| 16 | |||
| 17 | class 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 | |||
| 75 | class 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 | |||
| 129 | class 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 | |||
| 185 | class 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 | |||
| 200 | if __name__ == "__main__": | ||
| 201 | unittest.main() | ||
| 202 | |||
| 203 | |||
| 204 | class 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 | |||
| 3 | Driving the binary is the only way to see this: the feature list is a table | ||
| 4 | of #ifdefs, so it is only true for the flags the binary itself was built with. | ||
| 5 | """ | ||
| 6 | |||
| 7 | import subprocess | ||
| 8 | import unittest | ||
| 9 | |||
| 10 | from harness import TRACKER | ||
| 11 | |||
| 12 | |||
| 13 | class 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) | ||
