Close any LocalPortForwarders with the SSHClient that produced them (assuming they're still open).

This commit is contained in:
David Solin
2016-08-15 00:17:48 -05:00
parent 6f9ecf69e4
commit ba347f927d
2 changed files with 45 additions and 6 deletions

View File

@@ -139,6 +139,8 @@ public class SSHClient
/** {@code ssh-connection} service */
protected final Connection conn;
private List<LocalPortForwarder> forwarders;
/** Default constructor. Initializes this object using {@link DefaultConfig}. */
public SSHClient() {
this(new DefaultConfig());
@@ -431,6 +433,15 @@ public class SSHClient
@Override
public void disconnect()
throws IOException {
if (forwarders != null) {
for (LocalPortForwarder forwarder : forwarders) {
try {
forwarder.close();
} catch (IOException e) {
log.warn("Error closing forwarder", e);
}
}
}
trans.disconnect();
super.disconnect();
}
@@ -648,7 +659,12 @@ public class SSHClient
*/
public LocalPortForwarder newLocalPortForwarder(LocalPortForwarder.Parameters parameters,
ServerSocket serverSocket) {
return new LocalPortForwarder(conn, parameters, serverSocket);
if (forwarders == null) {
forwarders = new ArrayList<LocalPortForwarder>();
}
LocalPortForwarder forwarder = new LocalPortForwarder(conn, parameters, serverSocket);
forwarders.add(forwarder);
return forwarder;
}
/**

View File

@@ -28,6 +28,7 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.TimeUnit;
import static com.hierynomus.sshj.backport.Sockets.asCloseable;
@@ -134,11 +135,33 @@ public class LocalPortForwarder {
throws IOException {
log.info("Listening on {}", serverSocket.getLocalSocketAddress());
while (!Thread.currentThread().isInterrupted()) {
try {
final Socket socket = serverSocket.accept();
log.debug("Got connection from {}", socket.getRemoteSocketAddress());
startChannel(socket);
} catch (SocketException e) {
if (!serverSocket.isClosed()) {
throw e;
}
}
}
if (serverSocket.isClosed()) {
log.debug("LocalPortForwarder closed");
} else {
log.debug("LocalPortForwarder interrupted!");
}
}
/**
* Close the ServerSocket that's listening for connections to forward.
*
* @throws IOException
*/
public void close() throws IOException {
if (!serverSocket.isClosed()) {
log.info("Closing listener on {}", serverSocket.getLocalSocketAddress());
serverSocket.close();
}
log.debug("Interrupted!");
}
}