Skip to content

Close the control socket when connect fails - #89

Open
wtn wants to merge 1 commit into
ruby:masterfrom
wtn:leak
Open

wtn wants to merge 1 commit into
ruby:masterfrom
wtn:leak

Conversation

@wtn

@wtn wtn commented Nov 16, 2026

Copy link
Copy Markdown

Net::FTP#connect opens a TCP socket, reads the server greeting and, with ssl:, sets up TLS. When the greeting or the TLS setup raises, the socket stays open. With Net::FTP.new(host), the exception comes out of the constructor, so the caller never gets the Net::FTP object and has no way to call close. The socket stays open until garbage collection.

This condition can occur when a busy server greets with 421, when the server rejects AUTH TLS, PBSZ or PROT P, or when the TLS handshake fails with implicit_ftps: true. The 421 greeting is the most common case.

ftp = Net::FTP.new
ftp.connect(host, port) # server greets with "421 Too many connections"
#=> Net::FTPTempError
ftp.instance_variable_get(:@bare_sock).closed? #=> false

connect had a rescue for OpenSSL::SSL::SSLError and Net::OpenTimeout that called @sock.close. The plain FTP path had no rescue, and server replies such as 421 or 502 raise Net::FTPError subclasses, which the rescue did not catch. With implicit_ftps: true, @sock is assigned only after the handshake, so on a handshake failure the rescue closed the @sock from before connect and left the new socket open.

The 421 greeting case goes back to the first version of connect in 986a74a, which read the greeting with voidresp and had no rescue. The AUTH TLS, PBSZ and PROT P cases go back to bc82f22, which added TLS support with a rescue for OpenSSL::SSL::SSLError only. The implicit FTPS case goes back to f75ff61, which skips the plain @sock assignment for implicit FTPS, so @sock is set only after the handshake.

connect now wraps the steps after open_socket in begin/ensure and closes @bare_sock unless the steps finished, the same way transfercmd handles the data socket. After a failed connect, closed? returns true.

`connect` left the TCP socket open when the server rejected the session,
for example with a 421 greeting, and `Net::FTP.new(host)` raised before
returning an object the caller could close. `connect` now closes the
socket when a step after `open_socket` raises.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant