Skip to content

Commit

Permalink
#450 use Socket.connect() with a timeout that has been supported sinc…
Browse files Browse the repository at this point in the history
…e Java 1.4 instead of using old method of creating a separate thread and joining to that thread with timeout.
  • Loading branch information
norrisjeremy committed Dec 11, 2023
1 parent 485a0a2 commit 73f8bee
Showing 1 changed file with 14 additions and 47 deletions.
61 changes: 14 additions & 47 deletions src/main/java/com/jcraft/jsch/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@

package com.jcraft.jsch;

import java.net.Socket;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Vector;
Expand Down Expand Up @@ -369,55 +371,20 @@ static boolean array_equals(byte[] foo, byte bar[]) {
}

static Socket createSocket(String host, int port, int timeout) throws JSchException {
Socket socket = null;
if (timeout == 0) {
try {
socket = new Socket(host, port);
return socket;
} catch (Exception e) {
String message = e.toString();
throw new JSchException(message, e);
}
}
final String _host = host;
final int _port = port;
final Socket[] sockp = new Socket[1];
final Exception[] ee = new Exception[1];
String message = "";
Thread tmp = new Thread(() -> {
sockp[0] = null;
try {
sockp[0] = new Socket(_host, _port);
} catch (Exception e) {
ee[0] = e;
if (sockp[0] != null && sockp[0].isConnected()) {
try {
sockp[0].close();
} catch (Exception eee) {
}
}
sockp[0] = null;
}
});
tmp.setName("Opening Socket " + host);
tmp.start();
Socket socket = new Socket();
try {
tmp.join(timeout);
message = "timeout: ";
} catch (InterruptedException eee) {
}
if (sockp[0] != null && sockp[0].isConnected()) {
socket = sockp[0];
} else {
message += "socket is not established";
if (ee[0] != null) {
message = ee[0].toString();
socket.connect(new InetSocketAddress(host, port), timeout);
return socket;
} catch (Exception e) {
try {
socket.close();
} catch (Exception ignore) {
}
tmp.interrupt();
tmp = null;
throw new JSchException(message, ee[0]);

String message =
e instanceof SocketTimeoutException ? "timeout: socket is not established" : e.toString();
throw new JSchException(message, e);
}
return socket;
}

static byte[] str2byte(String str, Charset encoding) {
Expand Down

0 comments on commit 73f8bee

Please sign in to comment.