@@ -14,6 +14,7 @@ use std::{
1414 ffi:: { OsStr , OsString } ,
1515 fs:: { OpenOptions , copy, create_dir, write} ,
1616 io:: Write ,
17+ net:: TcpListener ,
1718 path:: { Path , PathBuf } ,
1819 process:: Command ,
1920 sync:: LazyLock ,
@@ -126,6 +127,7 @@ pub fn test_case(build_wrap_cmd: Option<&str>, test_case: &TestCase, stderr_expe
126127 prepend_out_dir_to_path ( & mut command) . unwrap ( ) ;
127128 command. env ( "BUILD_WRAP_CMD" , build_wrap_cmd) ;
128129 }
130+ let _tcp_listener = create_tcp_listener ( & mut command, test_case) . unwrap ( ) ;
129131 command. current_dir ( & temp_package) ;
130132
131133 let output = exec_forwarding_output ( command, false ) . unwrap ( ) ;
@@ -184,3 +186,26 @@ pub fn prepend_path(path: PathBuf, paths: &OsStr) -> Result<OsString> {
184186 let paths_joined = env:: join_paths ( paths_chained) ?;
185187 Ok ( paths_joined)
186188}
189+
190+ /// Creates a local TCP listener for the `tcp_connect` build-script test.
191+ ///
192+ /// The listener binds to an ephemeral loopback port, passes that port through
193+ /// `BUILD_WRAP_TCP_PORT`, and is returned so it stays open while the command runs.
194+ /// Non-`tcp_connect` test cases return `None`.
195+ ///
196+ /// `create_tcp_listener` creates a TCP listener so that a build script can attempt a real TCP
197+ /// connect. `sandboxer` is configured to restrict TCP connects. `ping` uses ICMP rather than TCP,
198+ /// so it cannot be used to test that restriction.
199+ fn create_tcp_listener ( command : & mut Command , test_case : & TestCase ) -> Result < Option < TcpListener > > {
200+ let TestCase :: BuildScript ( path) = test_case else {
201+ return Ok ( None ) ;
202+ } ;
203+ if path. file_name ( ) != Some ( OsStr :: new ( "tcp_connect.rs" ) ) {
204+ return Ok ( None ) ;
205+ }
206+ let listener = TcpListener :: bind ( ( "127.0.0.1" , 0 ) ) ?;
207+ let local_addr = listener. local_addr ( ) ?;
208+ let port = local_addr. port ( ) . to_string ( ) ;
209+ command. env ( "BUILD_WRAP_TCP_PORT" , port) ;
210+ Ok ( Some ( listener) )
211+ }
0 commit comments