Skip to content

Commit

Permalink
fix: Make sure socket is closed if an exception is thrown in createSo…
Browse files Browse the repository at this point in the history
…cket fixes Issue pgjdbc#2684
  • Loading branch information
davecramer committed Nov 29, 2022
1 parent 96824b0 commit 7c36ba6
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions pgjdbc/src/main/java/org/postgresql/core/PGStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -226,21 +226,29 @@ public void setMinStreamAvailableCheckDelay(int delay) {
}

private Socket createSocket(int timeout) throws IOException {
Socket socket = socketFactory.createSocket();
String localSocketAddress = hostSpec.getLocalSocketAddress();
if (localSocketAddress != null) {
socket.bind(new InetSocketAddress(InetAddress.getByName(localSocketAddress), 0));
}
if (!socket.isConnected()) {
// When using a SOCKS proxy, the host might not be resolvable locally,
// thus we defer resolution until the traffic reaches the proxy. If there
// is no proxy, we must resolve the host to an IP to connect the socket.
InetSocketAddress address = hostSpec.shouldResolve()
? new InetSocketAddress(hostSpec.getHost(), hostSpec.getPort())
: InetSocketAddress.createUnresolved(hostSpec.getHost(), hostSpec.getPort());
socket.connect(address, timeout);
}
return socket;
Socket socket = null;
try {
socket = socketFactory.createSocket();
String localSocketAddress = hostSpec.getLocalSocketAddress();
if (localSocketAddress != null) {
socket.bind(new InetSocketAddress(InetAddress.getByName(localSocketAddress), 0));
}
if (!socket.isConnected()) {
// When using a SOCKS proxy, the host might not be resolvable locally,
// thus we defer resolution until the traffic reaches the proxy. If there
// is no proxy, we must resolve the host to an IP to connect the socket.
InetSocketAddress address = hostSpec.shouldResolve()
? new InetSocketAddress(hostSpec.getHost(), hostSpec.getPort())
: InetSocketAddress.createUnresolved(hostSpec.getHost(), hostSpec.getPort());
socket.connect(address, timeout);
}
return socket;
} catch ( Exception ex ) {
if (socket != null) {
socket.close();
}
throw ex;
}
}

/**
Expand Down

0 comments on commit 7c36ba6

Please sign in to comment.