Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
@@ -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]

Expand Down
5 changes: 4 additions & 1 deletion lib/net/ssh/gateway.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
16 changes: 16 additions & 0 deletions test/net/ssh/gateway_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down Expand Up @@ -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

Expand Down
Loading