Skip to content

Commit

Permalink
Poll local socket to make sure SSH tunnel is ready before connecting
Browse files Browse the repository at this point in the history
  • Loading branch information
bphinz committed Nov 5, 2019
1 parent ac61fd8 commit 512d940
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions java/com/tigervnc/vncviewer/Tunnel.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.*;
import java.util.*;

import com.tigervnc.rdr.*;
Expand Down Expand Up @@ -209,13 +211,38 @@ private static void createTunnelExt(String gatewayHost, String remoteHost,
try {
Thread t = new Thread(new ExtProcess(cmd, vlog, true));
t.start();
// wait for the ssh process to start
Thread.sleep(1000);
// try for up to 5s
for (int i=0;i<50;i++) {
if (isTunnelReady(localPort))
return;
else
Thread.sleep(100);
}
throw new Exception("SSH Tunnel not ready");
} catch (java.lang.Exception e) {
throw new Exception(e.getMessage());
}
}

private static boolean isTunnelReady(int localPort) throws Exception {
// test the local forwarding socket to make
// sure the tunnel is up before connecting
SocketAddress sockAddr =
new InetSocketAddress("localhost", localPort);
java.net.Socket socket = new java.net.Socket();
boolean ready = false;
try {
socket.connect(sockAddr);
ready = socket.isConnected();
socket.close();
} catch (IOException e) {
// expected until tunnel is up
} catch (java.lang.Exception e) {
throw new Exception(e.getMessage());
}
return ready;
}

private static String fillCmdPattern(String pattern, String gatewayHost,
String remoteHost, int remotePort,
int localPort) {
Expand Down

0 comments on commit 512d940

Please sign in to comment.