/
ConnectionBase.java
518 lines (463 loc) · 14.9 KB
/
ConnectionBase.java
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/*
* Copyright (c) 2011-2019 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.core.net.impl;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.traffic.AbstractTrafficShapingHandler;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.FutureListener;
import io.vertx.core.*;
import io.vertx.core.impl.ContextInternal;
import io.vertx.core.impl.future.PromiseInternal;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.core.net.SocketAddress;
import io.vertx.core.spi.metrics.NetworkMetrics;
import io.vertx.core.spi.metrics.TCPMetrics;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import java.net.InetSocketAddress;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Abstract base class for connections managed by a vertx instance. This base implementation does not handle
* inbound/outbound message flow with a Netty channel.
*
* @author <a href="http://tfox.org">Tim Fox</a>
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
public abstract class ConnectionBase {
private static final long METRICS_REPORTED_BYTES_LOW_MASK = 0xFFF; // 4K
private static final long METRICS_REPORTED_BYTES_HIGH_MASK = ~METRICS_REPORTED_BYTES_LOW_MASK; // 4K
/**
* An exception used to signal a closed connection to an exception handler. Exception are
* expensive to create, this instance can be used for this purpose. It does not capture a stack
* trace to not be misleading.
*/
public static final VertxException CLOSED_EXCEPTION = new VertxException("Connection was closed", true);
public static final AttributeKey<SocketAddress> REMOTE_ADDRESS_OVERRIDE = AttributeKey.valueOf("RemoteAddressOverride");
public static final AttributeKey<SocketAddress> LOCAL_ADDRESS_OVERRIDE = AttributeKey.valueOf("LocalAddressOverride");
private static final Logger log = LoggerFactory.getLogger(ConnectionBase.class);
protected final VertxInternal vertx;
protected final ChannelHandlerContext chctx;
protected final ContextInternal context;
private Handler<Throwable> exceptionHandler;
private Handler<Void> closeHandler;
private Object metric;
private SocketAddress remoteAddress;
private SocketAddress realRemoteAddress;
private SocketAddress localAddress;
private SocketAddress realLocalAddress;
private Future<Void> closeFuture;
private long remainingBytesRead;
private long remainingBytesWritten;
// State accessed exclusively from the event loop thread
private ChannelPromise closeInitiated;
private boolean closeFinished;
protected ConnectionBase(ContextInternal context, ChannelHandlerContext chctx) {
PromiseInternal<Void> f = context.promise();
chctx
.channel()
.closeFuture()
.addListener(f);
this.vertx = context.owner();
this.chctx = chctx;
this.context = context;
this.closeFuture = f;
}
/**
* @return a promise that will be completed when the connection becomes closed
*/
public Future<Void> closeFuture() {
return closeFuture;
}
/**
* Fail the connection, the {@code error} will be sent to the pipeline and the connection will
* stop processing any further message.
*
* @param error the {@code Throwable} to propagate
*/
public void fail(Throwable error) {
chctx.pipeline().fireExceptionCaught(error);
}
protected final ChannelPromise wrap(FutureListener<Void> handler) {
ChannelPromise promise = chctx.newPromise();
promise.addListener(handler);
return promise;
}
/**
* Close the connection
*/
public final Future<Void> close() {
return close((Object) null);
}
static class CloseChannelPromise extends DefaultChannelPromise {
final Object reason;
final long timeout;
final TimeUnit unit;
public CloseChannelPromise(Channel channel, Object reason, long timeout, TimeUnit unit) {
super(channel);
this.reason = reason;
this.timeout = timeout;
this.unit = unit;
}
}
/**
* Close the connection
*/
public final Future<Void> close(Object reason) {
return close(reason, 0L, TimeUnit.SECONDS);
}
/**
* Close the connection
*/
public final Future<Void> close(Object reason, long timeout, TimeUnit unit) {
EventExecutor exec = chctx.executor();
CloseChannelPromise promise = new CloseChannelPromise(chctx.channel(), reason, timeout, unit);
if (exec.inEventLoop()) {
close(promise);
} else {
exec.execute(() -> close(promise));
}
PromiseInternal<Void> p = context.promise();
promise.addListener(p);
return p.future();
}
private void close(CloseChannelPromise promise) {
chctx
.channel()
.close(promise);
}
final void handleClose(ChannelPromise promise) {
if (closeInitiated != null) {
long timeout;
Object closeReason;
if (promise instanceof CloseChannelPromise) {
timeout = ((CloseChannelPromise)promise).timeout;
closeReason = ((CloseChannelPromise)promise).reason;
} else {
timeout = 0L;
closeReason = null;
}
if (timeout == 0L && !closeFinished) {
closeFinished = true;
closeInitiated = promise;
handleClose(closeReason, promise);
} else {
chctx
.channel()
.closeFuture()
.addListener(future -> {
if (future.isSuccess()) {
promise.setSuccess();
} else {
promise.setFailure(future.cause());
}
});
}
} else {
closeInitiated = promise;
if (promise instanceof CloseChannelPromise) {
CloseChannelPromise closeChannelPromise = (CloseChannelPromise) promise;
handleClose(closeChannelPromise.reason, closeChannelPromise.timeout, closeChannelPromise.unit, promise);
} else {
handleClose(null, 0L, TimeUnit.SECONDS, promise);
}
}
}
void handleClose(Object reason, long timeout, TimeUnit unit, ChannelPromise promise) {
if (closeFinished) {
// Need to add too "promise" to closeInitiated promise to ensure proper report of the flow
return;
}
closeFinished = true;
handleClose(reason, promise);
}
protected void handleClose(Object reason, ChannelPromise promise) {
chctx.close(promise);
}
public synchronized ConnectionBase closeHandler(Handler<Void> handler) {
this.closeHandler = handler;
return this;
}
public synchronized ConnectionBase exceptionHandler(Handler<Throwable> handler) {
this.exceptionHandler = handler;
return this;
}
/**
* @return the Netty channel - for internal usage only
*/
public final Channel channel() {
return chctx.channel();
}
public final ChannelHandlerContext channelHandlerContext() {
return chctx;
}
public final ContextInternal getContext() {
return context;
}
public final synchronized void metric(Object metric) {
this.metric = metric;
}
public final synchronized Object metric() {
return metric;
}
public NetworkMetrics metrics() {
return null;
}
protected void handleException(Throwable t) {
NetworkMetrics metrics = metrics();
if (metrics != null) {
metrics.exceptionOccurred(metric, remoteAddress(), t);
}
context.execute(t, err -> {
Handler<Throwable> handler;
synchronized (ConnectionBase.this) {
handler = exceptionHandler;
}
if (handler != null) {
context.dispatch(err, handler);
} else {
if (log.isDebugEnabled()) {
log.error(t.getMessage(), t);
} else {
log.error(t.getMessage());
}
}
});
}
protected void handleClosed() {
NetworkMetrics metrics = metrics();
if (metrics != null) {
flushBytesRead();
flushBytesWritten();
if (metrics instanceof TCPMetrics) {
((TCPMetrics) metrics).disconnected(metric(), remoteAddress());
}
}
context.execute(() -> {
Handler<Void> handler;
synchronized (ConnectionBase.this) {
handler = closeHandler;
}
if (handler != null) {
context.dispatch(handler);
}
});
}
public final void reportBytesRead(Object msg) {
NetworkMetrics metrics = metrics();
if (metrics != null) {
doReportBytesRead(msg, metrics);
}
}
private void doReportBytesRead(Object msg, NetworkMetrics metrics) {
long bytes = remainingBytesRead;
long numberOfBytes = sizeof(msg);
bytes += numberOfBytes;
long val = bytes & METRICS_REPORTED_BYTES_HIGH_MASK;
if (val > 0) {
bytes &= METRICS_REPORTED_BYTES_LOW_MASK;
metrics.bytesRead(metric(), remoteAddress(), val);
}
remainingBytesRead = bytes;
}
protected long sizeof(Object msg) {
if (msg instanceof ByteBuf) {
return ((ByteBuf)msg).readableBytes();
}
return 0L;
}
public final void reportBytesRead(long numberOfBytes) {
if (numberOfBytes < 0L) {
throw new IllegalArgumentException();
}
NetworkMetrics metrics = metrics();
if (metrics != null) {
long bytes = remainingBytesRead;
bytes += numberOfBytes;
long val = bytes & METRICS_REPORTED_BYTES_HIGH_MASK;
if (val > 0) {
bytes &= METRICS_REPORTED_BYTES_LOW_MASK;
metrics.bytesRead(metric(), remoteAddress(), val);
}
remainingBytesRead = bytes;
}
}
public final void reportsBytesWritten(Object msg) {
NetworkMetrics metrics = metrics();
if (metrics != null) {
long numberOfBytes = sizeof(msg);
long bytes = remainingBytesWritten;
bytes += numberOfBytes;
long val = bytes & METRICS_REPORTED_BYTES_HIGH_MASK;
if (val > 0) {
bytes &= METRICS_REPORTED_BYTES_LOW_MASK;
metrics.bytesWritten(metric, remoteAddress(), val);
}
remainingBytesWritten = bytes;
}
}
public final void reportBytesWritten(long numberOfBytes) {
if (numberOfBytes < 0L) {
throw new IllegalArgumentException();
}
NetworkMetrics metrics = metrics();
if (metrics != null) {
long bytes = remainingBytesWritten;
bytes += numberOfBytes;
long val = bytes & METRICS_REPORTED_BYTES_HIGH_MASK;
if (val > 0) {
bytes &= METRICS_REPORTED_BYTES_LOW_MASK;
metrics.bytesWritten(metric, remoteAddress(), val);
}
remainingBytesWritten = bytes;
}
}
public void flushBytesRead() {
NetworkMetrics metrics = metrics();
if (metrics != null) {
long val = remainingBytesRead;
if (val > 0L) {
remainingBytesRead = 0L;
metrics.bytesRead(metric(), remoteAddress(), val);
}
}
}
public void flushBytesWritten() {
NetworkMetrics metrics = metrics();
if (metrics != null) {
long val = remainingBytesWritten;
if (val > 0L) {
remainingBytesWritten = 0L;
metrics.bytesWritten(metric(), remoteAddress(), val);
}
}
}
public boolean isSsl() {
return chctx.pipeline().get(SslHandler.class) != null;
}
public boolean isTrafficShaped() {
return chctx.pipeline().get(AbstractTrafficShapingHandler.class) != null;
}
public SSLSession sslSession() {
ChannelHandlerContext sslHandlerContext = chctx.pipeline().context(SslHandler.class);
if (sslHandlerContext != null) {
SslHandler sslHandler = (SslHandler) sslHandlerContext.handler();
return sslHandler.engine().getSession();
} else {
return null;
}
}
public List<Certificate> peerCertificates() throws SSLPeerUnverifiedException {
SSLSession session = sslSession();
if (session != null) {
return Arrays.asList(session.getPeerCertificates());
} else {
return null;
}
}
public String indicatedServerName() {
if (chctx.channel().hasAttr(SslHandshakeCompletionHandler.SERVER_NAME_ATTR)) {
return chctx.channel().attr(SslHandshakeCompletionHandler.SERVER_NAME_ATTR).get();
} else {
return null;
}
}
public ChannelPromise channelFuture() {
return chctx.newPromise();
}
public String remoteName() {
java.net.SocketAddress addr = chctx.channel().remoteAddress();
if (addr instanceof InetSocketAddress) {
// Use hostString that does not trigger a DNS resolution
return ((InetSocketAddress)addr).getHostString();
}
return null;
}
private SocketAddress channelRemoteAddress() {
java.net.SocketAddress addr = chctx.channel().remoteAddress();
return addr != null ? vertx.transport().convert(addr) : null;
}
private SocketAddress socketAdressOverride(AttributeKey<SocketAddress> key) {
Channel ch = chctx.channel();
return ch.hasAttr(key) ? ch.attr(key).getAndSet(null) : null;
}
public SocketAddress remoteAddress() {
SocketAddress address = remoteAddress;
if (address == null) {
address = socketAdressOverride(REMOTE_ADDRESS_OVERRIDE);
if (address == null) {
address = channelRemoteAddress();
if (address != null && address.isDomainSocket() && address.path().isEmpty()) {
address = channelLocalAddress();
}
}
if (address != null) {
remoteAddress = address;
}
}
return address;
}
public SocketAddress remoteAddress(boolean real) {
if (real) {
SocketAddress address = realRemoteAddress;
if (address == null) {
address = channelRemoteAddress();
}
if (address != null) {
realRemoteAddress = address;
}
return address;
} else {
return remoteAddress();
}
}
private SocketAddress channelLocalAddress() {
java.net.SocketAddress addr = chctx.channel().localAddress();
return addr != null ? vertx.transport().convert(addr) : null;
}
public SocketAddress localAddress() {
SocketAddress address = localAddress;
if (address == null) {
address = socketAdressOverride(LOCAL_ADDRESS_OVERRIDE);
if (address == null) {
address = channelLocalAddress();
if (address != null && address.isDomainSocket() && address.path().isEmpty()) {
address = channelRemoteAddress();
}
}
if (address != null) {
localAddress = address;
}
}
return address;
}
public SocketAddress localAddress(boolean real) {
if (real) {
SocketAddress address = realLocalAddress;
if (address == null) {
address = channelLocalAddress();
}
if (address != null) {
realLocalAddress = address;
}
return address;
} else {
return localAddress();
}
}
}