Close Socket to AWS KMS on exceptional path
Addresses Coverity-reported defect.
package com.mongodb.client.internal;
+import com.mongodb.MongoSocketOpenException;
import com.mongodb.MongoSocketWriteException;
import com.mongodb.ServerAddress;
@@ -40,26 +41,52 @@ class KeyManagementService {
}
public InputStream stream(final String host, final ByteBuffer message) {
+ Socket socket;
+ try {
+ socket = sslContext.getSocketFactory().createSocket();
+ } catch (IOException e) {
+ throw new MongoSocketOpenException("Exception opening connection to Key Management Service", new ServerAddress(host, port), e);
+ }
+
try {
- Socket socket = sslContext.getSocketFactory().createSocket();
socket.setSoTimeout(timeoutMillis);
socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), timeoutMillis);
+ } catch (IOException e) {
+ closeSocket(socket);
+ throw new MongoSocketOpenException("Exception opening connection to Key Management Service", new ServerAddress(host, port), e);
+ }
+ try {
OutputStream outputStream = socket.getOutputStream();
byte[] bytes = new byte[message.remaining()];
message.get(bytes);
outputStream.write(bytes);
+ } catch (IOException e) {
+ closeSocket(socket);
+ throw new MongoSocketWriteException("Exception sending message to Key Management Service",
+ new ServerAddress(host, port), e);
+ }
+ try {
return socket.getInputStream();
-
} catch (IOException e) {
- throw new MongoSocketWriteException("Exception sending message to Key Management Service", new ServerAddress(host, port), e);
+ closeSocket(socket);
+ throw new MongoSocketWriteException("Exception receiving message from Key Management Service",
+ new ServerAddress(host, port), e);
}
}
public int getPort() {
return port;
}
+
+ private void closeSocket(final Socket socket) {
+ try {
+ socket.close();
+ } catch (IOException e) {
+ // ignore
+ }
+ }
}
