forked from apache/nifi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
SSLSocketChannel.java
731 lines (642 loc) · 28.3 KB
/
SSLSocketChannel.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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.nifi.remote.io.socket.ssl;
import org.apache.nifi.remote.exception.TransmissionDisabledException;
import org.apache.nifi.remote.io.socket.BufferStateManager;
import org.apache.nifi.remote.io.socket.BufferStateManager.Direction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.TimeUnit;
/**
* SSLSocketChannel supports reading and writing bytes using TLS and NIO SocketChannels with configurable timeouts
*/
public class SSLSocketChannel implements Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(SSLSocketChannel.class);
private static final int MINIMUM_READ_BUFFER_SIZE = 1;
private static final int DISCARD_BUFFER_LENGTH = 8192;
private static final int END_OF_STREAM = -1;
private static final byte[] EMPTY_MESSAGE = new byte[0];
private static final long BUFFER_FULL_EMPTY_WAIT_NANOS = TimeUnit.NANOSECONDS.convert(1, TimeUnit.MILLISECONDS);
private static final long FINISH_CONNECT_SLEEP = 50;
private static final long INITIAL_INCREMENTAL_SLEEP = 1;
private static final boolean CLIENT_AUTHENTICATION_REQUIRED = true;
private final String remoteAddress;
private final int port;
private final SSLEngine engine;
private final SocketAddress socketAddress;
private final BufferStateManager streamInManager;
private final BufferStateManager streamOutManager;
private final BufferStateManager appDataManager;
private final SocketChannel channel;
private int timeoutMillis = 30000;
private volatile boolean interrupted = false;
private volatile ChannelStatus channelStatus = ChannelStatus.DISCONNECTED;
/**
* SSLSocketChannel constructor with SSLContext and remote address parameters
*
* @param sslContext SSLContext used to create SSLEngine with specified client mode
* @param remoteAddress Remote Address used for connection
* @param port Remote Port used for connection
* @param bindAddress Local address used for binding server channel when provided
* @param useClientMode Use Client Mode
* @throws IOException Thrown on failures creating Socket Channel
*/
public SSLSocketChannel(final SSLContext sslContext, final String remoteAddress, final int port, final InetAddress bindAddress, final boolean useClientMode) throws IOException {
this.engine = createEngine(sslContext, useClientMode);
this.channel = createSocketChannel(bindAddress);
this.socketAddress = new InetSocketAddress(remoteAddress, port);
this.remoteAddress = remoteAddress;
this.port = port;
streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
/**
* SSLSocketChannel constructor with SSLContext and connected SocketChannel
*
* @param sslContext SSLContext used to create SSLEngine with specified client mode
* @param socketChannel Connected SocketChannel
* @param useClientMode Use Client Mode
* @throws IOException Thrown on SocketChannel.getRemoteAddress()
*/
public SSLSocketChannel(final SSLContext sslContext, final SocketChannel socketChannel, final boolean useClientMode) throws IOException {
this(createEngine(sslContext, useClientMode), socketChannel);
}
/**
* SSLSocketChannel constructor with configured SSLEngine and connected SocketChannel
*
* @param sslEngine SSLEngine configured with mode and client authentication
* @param socketChannel Connected SocketChannel
* @throws IOException Thrown on SocketChannel.getRemoteAddress()
*/
public SSLSocketChannel(final SSLEngine sslEngine, final SocketChannel socketChannel) throws IOException {
if (!socketChannel.isConnected()) {
throw new IllegalArgumentException("Connected SocketChannel required");
}
socketChannel.configureBlocking(false);
this.channel = socketChannel;
this.socketAddress = socketChannel.getRemoteAddress();
final Socket socket = socketChannel.socket();
this.remoteAddress = socket.getInetAddress().toString();
this.port = socket.getPort();
this.engine = sslEngine;
streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
public void setTimeout(final int timeoutMillis) {
this.timeoutMillis = timeoutMillis;
}
public int getTimeout() {
return timeoutMillis;
}
/**
* Connect Channel when not connected and perform handshake process
*
* @throws IOException Thrown on connection failures
*/
public void connect() throws IOException {
channelStatus = ChannelStatus.CONNECTING;
try {
if (!channel.isConnected()) {
logOperation("Connection Started");
final long started = System.currentTimeMillis();
if (!channel.connect(socketAddress)) {
while (!channel.finishConnect()) {
checkInterrupted();
checkTimeoutExceeded(started);
try {
TimeUnit.MILLISECONDS.sleep(FINISH_CONNECT_SLEEP);
} catch (final InterruptedException e) {
logOperation("Connection Interrupted");
}
}
}
}
channelStatus = ChannelStatus.CONNECTED;
} catch (final Exception e) {
close();
throw new SSLException(String.format("[%s:%d] Connection Failed", remoteAddress, port), e);
}
try {
performHandshake();
} catch (final IOException e) {
close();
throw new SSLException(String.format("[%s:%d] Handshake Failed", remoteAddress, port), e);
}
}
/**
* Shutdown Socket Channel input and read available bytes
*
* @throws IOException Thrown on Socket Channel failures
*/
public void consume() throws IOException {
channel.shutdownInput();
final byte[] byteBuffer = new byte[DISCARD_BUFFER_LENGTH];
final ByteBuffer buffer = ByteBuffer.wrap(byteBuffer);
int readCount;
do {
readCount = channel.read(buffer);
buffer.flip();
} while (readCount > 0);
}
/**
* Is Channel Closed
*
* @return Channel Closed Status
*/
public boolean isClosed() {
if (ChannelStatus.CLOSED == channelStatus) {
return true;
}
// Read Channel to determine closed status
final ByteBuffer inputBuffer = streamInManager.prepareForWrite(engine.getSession().getPacketBufferSize());
int bytesRead;
try {
bytesRead = channel.read(inputBuffer);
} catch (final IOException e) {
LOGGER.warn("[{}:{}] Closed Status Read Failed", remoteAddress, port, e);
bytesRead = END_OF_STREAM;
}
logOperationBytes("Closed Status Read", bytesRead);
if (bytesRead == 0) {
return false;
} else if (bytesRead > 0) {
try {
final SSLEngineResult unwrapResult = unwrap();
if (Status.CLOSED == unwrapResult.getStatus()) {
readChannelDiscard();
engine.closeInbound();
} else {
streamInManager.compact();
return false;
}
} catch (final IOException e) {
LOGGER.warn("[{}:{}] Closed Status Unwrap Failed", remoteAddress, port, e);
}
}
// Close Channel when encountering end of stream or closed status
try {
close();
} catch (final IOException e) {
LOGGER.warn("[{}:{}] Close Failed", remoteAddress, port, e);
}
return true;
}
/**
* Close Channel and process notifications
*
* @throws IOException Thrown on SSLEngine.wrap() failures
*/
@Override
public void close() throws IOException {
logOperation("Close Requested");
if (channelStatus == ChannelStatus.CLOSED) {
return;
}
try {
engine.closeOutbound();
streamOutManager.clear();
final ByteBuffer inputBuffer = ByteBuffer.wrap(EMPTY_MESSAGE);
final ByteBuffer outputBuffer = streamOutManager.prepareForWrite(engine.getSession().getApplicationBufferSize());
SSLEngineResult wrapResult = wrap(inputBuffer, outputBuffer);
Status status = wrapResult.getStatus();
if (Status.OK == status) {
logOperation("Clearing Outbound Buffer");
outputBuffer.clear();
wrapResult = wrap(inputBuffer, outputBuffer);
status = wrapResult.getStatus();
}
if (Status.CLOSED == status) {
final ByteBuffer streamOutputBuffer = streamOutManager.prepareForRead(MINIMUM_READ_BUFFER_SIZE);
try {
writeChannel(streamOutputBuffer);
} catch (final IOException e) {
logOperation(String.format("Write Close Notification Failed: %s", e.getMessage()));
}
} else {
throw new SSLException(String.format("[%s:%d] Invalid Wrap Result Status [%s]", remoteAddress, port, status));
}
} finally {
channelStatus = ChannelStatus.CLOSED;
readChannelDiscard();
closeQuietly(channel.socket());
closeQuietly(channel);
logOperation("Close Completed");
}
}
/**
* Get application bytes available for reading
*
* @return Number of application bytes available for reading
* @throws IOException Thrown on failures checking for available bytes
*/
public int available() throws IOException {
final ByteBuffer appDataBuffer = appDataManager.prepareForRead(MINIMUM_READ_BUFFER_SIZE);
return appDataBuffer.remaining();
}
/**
* Read and return one byte
*
* @return Byte read or -1 when end of stream reached
* @throws IOException Thrown on read failures
*/
public int read() throws IOException {
final byte[] buffer = new byte[1];
final int bytesRead = read(buffer);
if (bytesRead == END_OF_STREAM) {
return END_OF_STREAM;
}
return Byte.toUnsignedInt(buffer[0]);
}
/**
* Read available bytes into buffer
*
* @param buffer Byte array buffer
* @return Number of bytes read
* @throws IOException Thrown on read failures
*/
public int read(final byte[] buffer) throws IOException {
return read(buffer, 0, buffer.length);
}
/**
* Read available bytes into buffer based on offset and length requested
*
* @param buffer Byte array buffer
* @param offset Buffer offset
* @param len Length of bytes to read
* @return Number of bytes read
* @throws IOException Thrown on read failures
*/
public int read(final byte[] buffer, final int offset, final int len) throws IOException {
logOperationBytes("Read Requested", len);
checkChannelStatus();
int applicationBytesRead = readApplicationBuffer(buffer, offset, len);
if (applicationBytesRead > 0) {
return applicationBytesRead;
}
appDataManager.clear();
final SSLEngineResult unwrapResult = unwrapBufferReadChannel();
final Status status = unwrapResult.getStatus();
if (Status.CLOSED == status) {
applicationBytesRead = readApplicationBuffer(buffer, offset, len);
if (applicationBytesRead == 0) {
return END_OF_STREAM;
}
streamInManager.compact();
return applicationBytesRead;
} else if (Status.OK == status) {
applicationBytesRead = readApplicationBuffer(buffer, offset, len);
if (applicationBytesRead == 0) {
throw new IOException("Read Application Buffer Failed");
}
streamInManager.compact();
return applicationBytesRead;
} else {
throw new IllegalStateException(String.format("SSLEngineResult Status [%s] not expected from unwrap", status));
}
}
/**
* Write one byte to channel
*
* @param data Byte to be written
* @throws IOException Thrown on write failures
*/
public void write(final int data) throws IOException {
write(new byte[]{(byte) data}, 0, 1);
}
/**
* Write bytes to channel
*
* @param data Byte array to be written
* @throws IOException Thrown on write failures
*/
public void write(final byte[] data) throws IOException {
write(data, 0, data.length);
}
/**
* Write data to channel performs multiple iterations based on data length
*
* @param data Byte array to be written
* @param offset Byte array offset
* @param len Length of bytes for writing
* @throws IOException Thrown on write failures
*/
public void write(final byte[] data, final int offset, final int len) throws IOException {
logOperationBytes("Write Started", len);
checkChannelStatus();
final int applicationBufferSize = engine.getSession().getApplicationBufferSize();
logOperationBytes("Write Application Buffer Size", applicationBufferSize);
int iterations = len / applicationBufferSize;
if (len % applicationBufferSize > 0) {
iterations++;
}
for (int i = 0; i < iterations; i++) {
streamOutManager.clear();
final int itrOffset = offset + i * applicationBufferSize;
final int itrLen = Math.min(len - itrOffset, applicationBufferSize);
final ByteBuffer byteBuffer = ByteBuffer.wrap(data, itrOffset, itrLen);
final BufferStateManager bufferStateManager = new BufferStateManager(byteBuffer, Direction.READ);
final Status status = wrapWriteChannel(bufferStateManager);
switch (status) {
case BUFFER_OVERFLOW:
streamOutManager.ensureSize(engine.getSession().getPacketBufferSize());
appDataManager.ensureSize(engine.getSession().getApplicationBufferSize());
continue;
case OK:
continue;
case CLOSED:
throw new IOException("Channel is closed");
case BUFFER_UNDERFLOW:
throw new AssertionError("Got Buffer Underflow but should not have...");
}
}
}
/**
* Interrupt processing and disable transmission
*/
public void interrupt() {
this.interrupted = true;
}
private void performHandshake() throws IOException {
logOperation("Handshake Started");
channelStatus = ChannelStatus.HANDSHAKING;
engine.beginHandshake();
SSLEngineResult.HandshakeStatus handshakeStatus = engine.getHandshakeStatus();
while (true) {
logHandshakeStatus(handshakeStatus);
switch (handshakeStatus) {
case FINISHED:
case NOT_HANDSHAKING:
channelStatus = ChannelStatus.ESTABLISHED;
final SSLSession session = engine.getSession();
LOGGER.debug("[{}:{}] [{}] Negotiated Protocol [{}] Cipher Suite [{}]",
remoteAddress,
port,
channelStatus,
session.getProtocol(),
session.getCipherSuite()
);
return;
case NEED_TASK:
runDelegatedTasks();
handshakeStatus = engine.getHandshakeStatus();
break;
case NEED_UNWRAP:
final SSLEngineResult unwrapResult = unwrapBufferReadChannel();
handshakeStatus = unwrapResult.getHandshakeStatus();
if (unwrapResult.getStatus() == Status.CLOSED) {
throw getHandshakeException(handshakeStatus, "Channel Closed");
}
streamInManager.compact();
appDataManager.clear();
break;
case NEED_WRAP:
final ByteBuffer outboundBuffer = streamOutManager.prepareForWrite(engine.getSession().getApplicationBufferSize());
final SSLEngineResult wrapResult = wrap(ByteBuffer.wrap(EMPTY_MESSAGE), outboundBuffer);
handshakeStatus = wrapResult.getHandshakeStatus();
final Status wrapResultStatus = wrapResult.getStatus();
if (wrapResultStatus == Status.BUFFER_OVERFLOW) {
streamOutManager.prepareForWrite(engine.getSession().getApplicationBufferSize());
} else if (wrapResultStatus == Status.OK) {
final ByteBuffer streamBuffer = streamOutManager.prepareForRead(MINIMUM_READ_BUFFER_SIZE);
final int bytesRemaining = streamBuffer.remaining();
writeChannel(streamBuffer);
logOperationBytes("Handshake Channel Write Completed", bytesRemaining);
streamOutManager.clear();
} else {
throw getHandshakeException(handshakeStatus, String.format("Wrap Failed [%s]", wrapResult.getStatus()));
}
break;
}
}
}
private SSLEngineResult unwrapBufferReadChannel() throws IOException {
SSLEngineResult unwrapResult = unwrap();
while (Status.BUFFER_UNDERFLOW == unwrapResult.getStatus()) {
final int channelBytesRead = readChannel();
if (channelBytesRead == END_OF_STREAM) {
throw new EOFException("End of Stream found for Channel Read");
}
unwrapResult = unwrap();
if (SSLEngineResult.HandshakeStatus.FINISHED == unwrapResult.getHandshakeStatus()) {
// RFC 8446 Section 4.6 describes Post-Handshake Messages for TLS 1.3
logOperation("Processing Post-Handshake Messages");
unwrapResult = unwrap();
}
}
return unwrapResult;
}
private int readChannel() throws IOException {
logOperation("Channel Read Started");
final ByteBuffer outputBuffer = streamInManager.prepareForWrite(engine.getSession().getPacketBufferSize());
final long started = System.currentTimeMillis();
long sleepNanoseconds = INITIAL_INCREMENTAL_SLEEP;
while (true) {
checkInterrupted();
if (outputBuffer.remaining() == 0) {
return 0;
}
final int channelBytesRead = channel.read(outputBuffer);
if (channelBytesRead == 0) {
checkTimeoutExceeded(started);
sleepNanoseconds = incrementalSleep(sleepNanoseconds);
continue;
}
logOperationBytes("Channel Read Completed", channelBytesRead);
return channelBytesRead;
}
}
private void readChannelDiscard() {
try {
final ByteBuffer readBuffer = ByteBuffer.allocate(DISCARD_BUFFER_LENGTH);
int bytesRead = channel.read(readBuffer);
while (bytesRead > 0) {
readBuffer.clear();
bytesRead = channel.read(readBuffer);
}
} catch (final IOException e) {
LOGGER.debug("[{}:{}] Read Channel Discard Failed", remoteAddress, port, e);
}
}
private void writeChannel(final ByteBuffer inputBuffer) throws IOException {
long lastWriteCompleted = System.currentTimeMillis();
int totalBytes = 0;
long sleepNanoseconds = INITIAL_INCREMENTAL_SLEEP;
while (inputBuffer.hasRemaining()) {
checkInterrupted();
final int written = channel.write(inputBuffer);
totalBytes += written;
if (written > 0) {
lastWriteCompleted = System.currentTimeMillis();
} else {
checkTimeoutExceeded(lastWriteCompleted);
sleepNanoseconds = incrementalSleep(sleepNanoseconds);
}
}
logOperationBytes("Channel Write Completed", totalBytes);
}
private long incrementalSleep(final long nanoseconds) throws IOException {
try {
TimeUnit.NANOSECONDS.sleep(nanoseconds);
} catch (final InterruptedException e) {
close();
Thread.currentThread().interrupt();
throw new ClosedByInterruptException();
}
return Math.min(nanoseconds * 2, BUFFER_FULL_EMPTY_WAIT_NANOS);
}
private int readApplicationBuffer(final byte[] buffer, final int offset, final int len) {
logOperationBytes("Application Buffer Read Requested", len);
final ByteBuffer appDataBuffer = appDataManager.prepareForRead(len);
final int appDataRemaining = appDataBuffer.remaining();
logOperationBytes("Application Buffer Remaining", appDataRemaining);
if (appDataRemaining > 0) {
final int bytesToCopy = Math.min(len, appDataBuffer.remaining());
appDataBuffer.get(buffer, offset, bytesToCopy);
final int bytesCopied = appDataRemaining - appDataBuffer.remaining();
logOperationBytes("Application Buffer Copied", bytesCopied);
return bytesCopied;
}
return 0;
}
private Status wrapWriteChannel(final BufferStateManager inputManager) throws IOException {
final ByteBuffer inputBuffer = inputManager.prepareForRead(0);
final ByteBuffer outputBuffer = streamOutManager.prepareForWrite(engine.getSession().getApplicationBufferSize());
logOperationBytes("Wrap Started", inputBuffer.remaining());
Status status = Status.OK;
while (inputBuffer.remaining() > 0) {
final SSLEngineResult result = wrap(inputBuffer, outputBuffer);
status = result.getStatus();
if (status == Status.OK) {
final ByteBuffer readableOutBuff = streamOutManager.prepareForRead(0);
writeChannel(readableOutBuff);
streamOutManager.clear();
} else {
break;
}
}
return status;
}
private SSLEngineResult wrap(final ByteBuffer inputBuffer, final ByteBuffer outputBuffer) throws SSLException {
final SSLEngineResult result = engine.wrap(inputBuffer, outputBuffer);
logEngineResult(result, "WRAP Completed");
return result;
}
private SSLEngineResult unwrap() throws IOException {
final ByteBuffer streamBuffer = streamInManager.prepareForRead(engine.getSession().getPacketBufferSize());
final ByteBuffer applicationBuffer = appDataManager.prepareForWrite(engine.getSession().getApplicationBufferSize());
final SSLEngineResult result = engine.unwrap(streamBuffer, applicationBuffer);
logEngineResult(result, "UNWRAP Completed");
return result;
}
private void runDelegatedTasks() {
Runnable delegatedTask;
while ((delegatedTask = engine.getDelegatedTask()) != null) {
logOperation("Running Delegated Task");
delegatedTask.run();
}
}
private void closeQuietly(final Closeable closeable) {
try {
closeable.close();
} catch (final Exception e) {
logOperation(String.format("Close failed: %s", e.getMessage()));
}
}
private SSLHandshakeException getHandshakeException(final SSLEngineResult.HandshakeStatus handshakeStatus, final String message) {
final String formatted = String.format("[%s:%d] Handshake Status [%s] %s", remoteAddress, port, handshakeStatus, message);
return new SSLHandshakeException(formatted);
}
private void checkChannelStatus() throws IOException {
if (ChannelStatus.ESTABLISHED != channelStatus) {
connect();
}
}
private void checkInterrupted() {
if (interrupted) {
throw new TransmissionDisabledException();
}
}
private void checkTimeoutExceeded(final long started) throws SocketTimeoutException {
if (System.currentTimeMillis() > started + timeoutMillis) {
throw new SocketTimeoutException(String.format("Timeout Exceeded [%d ms] for [%s:%d]", timeoutMillis, remoteAddress, port));
}
}
private void logOperation(final String operation) {
LOGGER.trace("[{}:{}] [{}] {}", remoteAddress, port, channelStatus, operation);
}
private void logOperationBytes(final String operation, final int bytes) {
LOGGER.trace("[{}:{}] [{}] {} Bytes [{}]", remoteAddress, port, channelStatus, operation, bytes);
}
private void logHandshakeStatus(final SSLEngineResult.HandshakeStatus handshakeStatus) {
LOGGER.trace("[{}:{}] [{}] Handshake Status [{}]", remoteAddress, port, channelStatus, handshakeStatus);
}
private void logEngineResult(final SSLEngineResult result, final String method) {
LOGGER.trace("[{}:{}] [{}] {} Status [{}] Handshake Status [{}] Produced [{}] Consumed [{}]",
remoteAddress,
port,
channelStatus,
method,
result.getStatus(),
result.getHandshakeStatus(),
result.bytesProduced(),
result.bytesConsumed()
);
}
private static SocketChannel createSocketChannel(final InetAddress bindAddress) throws IOException {
final SocketChannel socketChannel = SocketChannel.open();
if (bindAddress != null) {
final SocketAddress socketAddress = new InetSocketAddress(bindAddress, 0);
socketChannel.bind(socketAddress);
}
socketChannel.configureBlocking(false);
return socketChannel;
}
private static SSLEngine createEngine(final SSLContext sslContext, final boolean useClientMode) {
final SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(useClientMode);
sslEngine.setNeedClientAuth(CLIENT_AUTHENTICATION_REQUIRED);
return sslEngine;
}
private enum ChannelStatus {
DISCONNECTED,
CONNECTING,
CONNECTED,
HANDSHAKING,
ESTABLISHED,
CLOSED
}
}