forked from nats-io/nats.java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketDataPort.java
More file actions
225 lines (195 loc) · 7.33 KB
/
SocketDataPort.java
File metadata and controls
225 lines (195 loc) · 7.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// Copyright 2015-2018 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package io.nats.client.impl;
import io.nats.client.Options;
import io.nats.client.support.NatsUri;
import io.nats.client.support.WebSocket;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import static io.nats.client.support.NatsConstants.SECURE_WEBSOCKET_PROTOCOL;
/**
* This class is not thread-safe. Caller must ensure thread safety.
*/
public class SocketDataPort implements DataPort {
protected NatsConnection connection;
protected String host;
protected int port;
protected Socket socket;
protected boolean isSecure = false;
protected int soLinger;
protected InputStream in;
protected OutputStream out;
@Override
public void afterConstruct(Options options) {
soLinger = options.getSocketSoLinger();
}
@Override
public void connect(String serverURI, NatsConnection conn, long timeoutNanos) throws IOException {
try {
connect(conn, new NatsUri(serverURI), timeoutNanos);
}
catch (URISyntaxException e) {
throw new IOException(e);
}
}
@Override
public void connect(NatsConnection conn, NatsUri nuri, long timeoutNanos) throws IOException {
connection = conn;
Options options = connection.getOptions();
long timeout = timeoutNanos / 1_000_000; // convert to millis
host = nuri.getHost();
port = nuri.getPort();
try {
if (options.getProxy() != null) {
socket = new Socket(options.getProxy());
}
else {
socket = new Socket();
}
socket.setTcpNoDelay(true);
socket.setReceiveBufferSize(2 * 1024 * 1024);
socket.setSendBufferSize(2 * 1024 * 1024);
socket.connect(new InetSocketAddress(getIpV4Addresses(nuri).get(0).getHost(), port), (int) timeout);
if (soLinger > -1) {
socket.setSoLinger(true, soLinger);
}
if (options.getSocketReadTimeoutMillis() > 0) {
socket.setSoTimeout(options.getSocketReadTimeoutMillis());
}
if (isWebsocketScheme(nuri.getScheme())) {
if (SECURE_WEBSOCKET_PROTOCOL.equalsIgnoreCase(nuri.getScheme())) {
upgradeToSecure();
}
try {
socket = new WebSocket(socket, host, options.getHttpRequestInterceptors());
} catch (Exception ex) {
socket.close();
throw ex;
}
}
in = socket.getInputStream();
out = socket.getOutputStream();
}
catch (Exception e) {
try { socket.close(); } catch (Exception ignore) {}
socket = null;
if (e instanceof IOException) {
throw e;
}
throw new IOException(e);
}
}
private List<NatsUri> getIpV4Addresses(NatsUri nuri) {
if (nuri.hostIsIpAddress()) {
return Arrays.asList(nuri);
}
try {
InetAddress[] addresses = InetAddress.getAllByName(nuri.getHost());
return filterIpv6Address(Arrays.asList(addresses), nuri);
} catch (UnknownHostException e) {
System.out.println(String.format("[WARN] Ignoring Address %s as Error in resolving host: %s", nuri.getHost(), e.getMessage()));
}
return Arrays.asList(nuri);
}
private List<NatsUri> filterIpv6Address(List<InetAddress> inetAddresses, NatsUri nuri) {
List<NatsUri> natsUris = new ArrayList<>();
for (InetAddress addr : inetAddresses) {
try {
if (addr instanceof Inet6Address) {
continue;
}
natsUris.add(nuri.reHost(addr.getHostAddress()));
} catch (URISyntaxException e) {
System.out.println(String.format("[WARN] Ignoring Address %s as Error in while rehostToNri: %s", nuri.getHost(), e.getMessage()));
}
}
if (natsUris.size() < 1) {
natsUris.add(nuri);
}
Collections.shuffle(natsUris, ThreadLocalRandom.current());
return natsUris;
}
/**
* Upgrade the port to SSL. If it is already secured, this is a no-op.
* If the data port type doesn't support SSL it should throw an exception.
*/
public void upgradeToSecure() throws IOException {
Options options = connection.getOptions();
SSLContext context = options.getSslContext();
SSLSocketFactory factory = context.getSocketFactory();
Duration timeout = options.getConnectionTimeout();
SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket, host, port, true);
sslSocket.setUseClientMode(true);
final CompletableFuture<Void> waitForHandshake = new CompletableFuture<>();
sslSocket.addHandshakeCompletedListener((evt) -> {
waitForHandshake.complete(null);
});
sslSocket.startHandshake();
try {
waitForHandshake.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
} catch (Exception ex) {
connection.handleCommunicationIssue(ex);
return;
}
socket = sslSocket;
in = sslSocket.getInputStream();
out = sslSocket.getOutputStream();
isSecure = true;
}
public int read(byte[] dst, int off, int len) throws IOException {
return in.read(dst, off, len);
}
public void write(byte[] src, int toWrite) throws IOException {
out.write(src, 0, toWrite);
}
public void shutdownInput() throws IOException {
// cannot call shutdownInput on sslSocket
if (!isSecure) {
socket.shutdownInput();
}
}
public void close() throws IOException {
socket.close();
}
@Override
public void forceClose() throws IOException {
try {
// If we are being asked to force close, there is no need to linger.
socket.setSoLinger(true, 0);
}
catch (SocketException e) {
// don't want to fail if I couldn't set linger
}
close();
}
public void flush() throws IOException {
out.flush();
}
protected static boolean isWebsocketScheme(String scheme) {
return "ws".equalsIgnoreCase(scheme) ||
"wss".equalsIgnoreCase(scheme);
}
}