| 120 | |
| 121 | |
| 122 | class TcpCapture: |
| 123 | def __init__(self, tmpdir): |
| 124 | self.tmpdir = Path(tmpdir) |
| 125 | self.pcap = self.tmpdir / "traffic.pcap" |
| 126 | self.proc = None |
| 127 | self.port = None |
| 128 | |
| 129 | def start(self, port): |
| 130 | assert self.proc is None, "capture already started" |
| 131 | self.port = int(port) |
| 132 | |
| 133 | self.proc = subprocess.Popen( |
| 134 | [ |
| 135 | "dumpcap", |
| 136 | "-i", "lo", |
| 137 | "-w", str(self.pcap), |
| 138 | "-f", f"tcp port {self.port}", |
| 139 | ], |
| 140 | stdout=subprocess.DEVNULL, |
| 141 | stderr=subprocess.DEVNULL, |
| 142 | ) |
| 143 | |
| 144 | # allow filter attach |
| 145 | time.sleep(0.2) |
| 146 | |
| 147 | def stop(self): |
| 148 | if self.proc: |
| 149 | self.proc.terminate() |
| 150 | self.proc.wait(timeout=2) |
| 151 | self.proc = None |
| 152 | |
| 153 | def assert_constant_payload(self): |
| 154 | tshark_cmd = [ |
| 155 | "tshark", |
| 156 | "-r", str(self.pcap), |
| 157 | "-Y", "tcp.len > 0", |
| 158 | "-T", "fields", |
| 159 | "-e", "tcp.len", |
| 160 | ] |
| 161 | |
| 162 | out = subprocess.check_output(tshark_cmd, text=True) |
| 163 | lengths = [int(x) for x in out.splitlines() if x.strip()] |
| 164 | |
| 165 | assert lengths, f"No TCP payload packets captured on port {self.port}" |
| 166 | |
| 167 | uniq = set(lengths) |
| 168 | assert len(uniq) == 1, ( |
| 169 | f"Non-constant TCP payload sizes on port {self.port}: " |
| 170 | f"{sorted(uniq)}:" |
| 171 | + subprocess.check_output(["tshark", "-r", str(self.pcap)], text=True) |
| 172 | ) |
| 173 | |
| 174 | |
| 175 | @pytest.fixture |