diff --git a/CHANGES.txt b/CHANGES.txt index 166b8e4..612dde7 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,5 +1,6 @@ === Unreleased +* `open` with a `local_port` of 0 returns and yields the port the OS picked, so several gateways can run without port clashes. Based on #6 by @thechile [mfazekas] * `require 'net/ssh/gateway'` now defines `Net::SSH::Gateway::VERSION` [mfazekas] * Run the tests on GitHub Actions for Ruby 2.6 to 4.0 [mfazekas] diff --git a/lib/net/ssh/gateway.rb b/lib/net/ssh/gateway.rb index b446cb1..3aacf95 100644 --- a/lib/net/ssh/gateway.rb +++ b/lib/net/ssh/gateway.rb @@ -101,13 +101,16 @@ def shutdown! # gateway.close(port) # # If +local_port+ is not specified, the next available port will be used. + # A +local_port+ of 0 lets the OS pick a free port, which avoids clashes + # between several gateways in one process; the port it picked is returned + # (or yielded). def open(host, port, local_port=nil) ensure_open! actual_local_port = local_port || next_port @session_mutex.synchronize do - @session.forward.local(actual_local_port, host, port) + actual_local_port = @session.forward.local(actual_local_port, host, port) end if block_given? diff --git a/test/net/ssh/gateway_test.rb b/test/net/ssh/gateway_test.rb index a3ce8dd..9cb7408 100644 --- a/test/net/ssh/gateway_test.rb +++ b/test/net/ssh/gateway_test.rb @@ -35,6 +35,20 @@ def test_open_with_explicit_local_port_should_use_that_port assert_equal [8181, "app1", 22], gateway_session.forward.active_locals[8181] end + def test_open_with_local_port_zero_should_return_the_port_the_os_picked + gateway_session, gateway = new_gateway(:ephemeral_port => 50123) + assert_equal 50123, gateway.open("app1", 22, 0) + assert_equal [50123, "app1", 22], gateway_session.forward.active_locals[50123] + end + + def test_open_with_local_port_zero_and_block_should_yield_and_close_the_picked_port + gateway_session, gateway = new_gateway(:ephemeral_port => 50123) + yielded = nil + gateway.open("app1", 22, 0) { |port| yielded = port } + assert_equal 50123, yielded + assert gateway_session.forward.active_locals.empty? + end + def test_ssh_should_return_connection_when_no_block_is_given gateway_session, gateway = new_gateway expect_connect_to("127.0.0.1", "user", :port => 65535).returns(result = mock("session")) @@ -93,7 +107,9 @@ def cancel_local(port) def local(lport, host, rport) raise Errno::EADDRINUSE if @options[:reserved] && @options[:reserved][lport] + lport = @options.fetch(:ephemeral_port) if lport == 0 @active_locals[lport] = [lport, host, rport] + lport end end