Skip to content

Commit dd835f5

Browse files
committed
Close Socket to AWS KMS on exceptional path
Addresses Coverity-reported defect. JAVA-3315
1 parent 1ad2e13 commit dd835f5

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

driver-sync/src/main/com/mongodb/client/internal/KeyManagementService.java

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package com.mongodb.client.internal;
1818

19+
import com.mongodb.MongoSocketOpenException;
1920
import com.mongodb.MongoSocketWriteException;
2021
import com.mongodb.ServerAddress;
2122

@@ -40,26 +41,52 @@ class KeyManagementService {
4041
}
4142

4243
public InputStream stream(final String host, final ByteBuffer message) {
44+
Socket socket;
45+
try {
46+
socket = sslContext.getSocketFactory().createSocket();
47+
} catch (IOException e) {
48+
throw new MongoSocketOpenException("Exception opening connection to Key Management Service", new ServerAddress(host, port), e);
49+
}
50+
4351
try {
44-
Socket socket = sslContext.getSocketFactory().createSocket();
4552
socket.setSoTimeout(timeoutMillis);
4653
socket.connect(new InetSocketAddress(InetAddress.getByName(host), port), timeoutMillis);
54+
} catch (IOException e) {
55+
closeSocket(socket);
56+
throw new MongoSocketOpenException("Exception opening connection to Key Management Service", new ServerAddress(host, port), e);
57+
}
4758

59+
try {
4860
OutputStream outputStream = socket.getOutputStream();
4961

5062
byte[] bytes = new byte[message.remaining()];
5163

5264
message.get(bytes);
5365
outputStream.write(bytes);
66+
} catch (IOException e) {
67+
closeSocket(socket);
68+
throw new MongoSocketWriteException("Exception sending message to Key Management Service",
69+
new ServerAddress(host, port), e);
70+
}
5471

72+
try {
5573
return socket.getInputStream();
56-
5774
} catch (IOException e) {
58-
throw new MongoSocketWriteException("Exception sending message to Key Management Service", new ServerAddress(host, port), e);
75+
closeSocket(socket);
76+
throw new MongoSocketWriteException("Exception receiving message from Key Management Service",
77+
new ServerAddress(host, port), e);
5978
}
6079
}
6180

6281
public int getPort() {
6382
return port;
6483
}
84+
85+
private void closeSocket(final Socket socket) {
86+
try {
87+
socket.close();
88+
} catch (IOException e) {
89+
// ignore
90+
}
91+
}
6592
}

0 commit comments

Comments
 (0)