1212import re
1313import socket
1414import subprocess
15+ import tempfile
1516from contextlib import asynccontextmanager
1617from datetime import datetime , timezone
1718from pathlib import Path
@@ -134,6 +135,8 @@ class Gateway:
134135 REST_PROXY_TIMEOUT_S = float (DATA_PLANE_LOAD_TIMEOUT_MAX_S ) # data-plane loads
135136 REST_PROXY_CONNECT_TIMEOUT_S = 10.0 # a service that never answers the TCP connect fails in seconds, not an hour
136137 REST_PROXY_TIMEOUT = httpx .Timeout (REST_PROXY_TIMEOUT_S , connect = REST_PROXY_CONNECT_TIMEOUT_S )
138+ CAPTURE_READ_BYTES = 64 * 1024
139+ CAPTURE_SNAPSHOT_ATTEMPTS = 3
137140
138141 def __init__ (
139142 self ,
@@ -432,7 +435,8 @@ async def traffic_captures(request: Request) -> Response:
432435
433436 @self ._mcp .custom_route ("/traffic/capture" , methods = ["GET" ])
434437 async def traffic_capture (request : Request ) -> Response :
435- return self ._refuse_uncontrolled (request ) or self ._serve_capture (request .query_params .get ("name" , "" ))
438+ return self ._refuse_uncontrolled (request ) or await asyncio .to_thread (
439+ self ._serve_capture , request .query_params .get ("name" , "" ))
436440
437441 @self ._mcp .custom_route ("/changes" , methods = ["GET" ])
438442 async def env_changes (request : Request ) -> Response :
@@ -1630,8 +1634,10 @@ def _serve_captures(self) -> Response:
16301634 return self ._json_response ({"format" : "pcap" , "captures" : captures }, 200 )
16311635
16321636 def _serve_capture (self , name : str ) -> Response :
1633- """traffic/v1's get: the capture file ``name``, one ``list`` names, streamed as it stands; tcpdump writes each
1634- packet as it captures it, so a file still being written ends on a whole packet, or at worst one torn."""
1637+ """traffic/v1's get: the capture file ``name``, one ``list`` names, as a copy taken whole before any of it is
1638+ sent (``_snapshot_capture``), so a file tcpdump's rotation rewrites while it downloads never arrives mixed or
1639+ cut short; 503 when every copy was rewritten under it. A file still being written ends on a whole packet, or at
1640+ worst one torn."""
16351641 if not _CAPTURE_FILE .fullmatch (name ):
16361642 return self ._json_response ({"ok" : False , "error" : {"code" : "invalid_params" ,
16371643 "message" : f"{ name !r} is not a capture's name, as list gives it" }}, 400 )
@@ -1643,14 +1649,42 @@ def _serve_capture(self, name: str) -> Response:
16431649 except OSError :
16441650 return self ._json_response ({"ok" : False , "error" : {"code" : "not_found" ,
16451651 "message" : f"no capture named { name !r} " }}, 404 )
1652+ with handle :
1653+ snapshot = self ._snapshot_capture (handle )
1654+ if snapshot is None :
1655+ return self ._json_response ({"ok" : False , "error" : {"code" : "unavailable" ,
1656+ "message" : f"capture { name !r} kept being rewritten while it was copied; "
1657+ "ask again" }}, 503 )
1658+ size = os .fstat (snapshot .fileno ()).st_size
16461659
16471660 def chunks ():
1648- with handle :
1649- while chunk := handle .read (65536 ):
1661+ with snapshot :
1662+ while chunk := snapshot .read (self . CAPTURE_READ_BYTES ):
16501663 yield chunk
16511664
16521665 return StreamingResponse (chunks (), media_type = PCAP_MEDIA_TYPE ,
1653- headers = {"Content-Disposition" : f'attachment; filename="{ name } "' })
1666+ headers = {"Content-Disposition" : f'attachment; filename="{ name } "' ,
1667+ "Content-Length" : str (size )})
1668+
1669+ def _snapshot_capture (self , handle : Any ) -> Any | None :
1670+ """A copy of the open capture ``handle`` in an unlinked temp file, read back from its start, or None when each
1671+ of ``CAPTURE_SNAPSHOT_ATTEMPTS`` copies found the file shorter than what it had copied: tcpdump truncated it to
1672+ reuse it, so the copy would mix two rounds of packets. The copy is gone once it's closed."""
1673+ for _ in range (self .CAPTURE_SNAPSHOT_ATTEMPTS ):
1674+ handle .seek (0 )
1675+ copy = tempfile .TemporaryFile ()
1676+ copied , rewritten = 0 , False
1677+ while chunk := handle .read (self .CAPTURE_READ_BYTES ):
1678+ copy .write (chunk )
1679+ copied += len (chunk )
1680+ if os .fstat (handle .fileno ()).st_size < copied :
1681+ rewritten = True
1682+ break
1683+ if not rewritten and os .fstat (handle .fileno ()).st_size >= copied :
1684+ copy .seek (0 )
1685+ return copy
1686+ copy .close ()
1687+ return None
16541688
16551689 def _serve_trajectory (self ) -> Response :
16561690 """Stream the whole env trajectory as JSONL; only a mid-write tail line can arrive torn."""
0 commit comments